I'am new to Python programming and Django Framework.
I have this app named Devices with multiple tables related with each other (Brand, Version, Location etc) and has crud. What I would like to do is to reuse my functions(list,create,detail etc.) instead of creating individual functions for each table.
Right now I'am unable to change BrandForm dynamically to example VersionForm. Is this possible? and am I doing the right thing?
urls.py
from django.urls import path
from .views import *
app_name = 'devices'
urlpatterns = [
# BRAND
path('brand/create', create_view, name='brand-create'),
# VERSION
path('version/create', create_view, name='version-create'),
]
views.py
from .models import *
from .forms import BrandForm, VersionForm
# GET PAGE NAME TO GET MODEL NAME
def get_page_name(request):
currentUrl = request.get_full_path()
page = currentUrl.split('/')[-2].split('.')[0] # Example /devices/brand/list; Get 2nd URL
return page
def create_view(request):
page = get_page_name(request) # GET PAGE MODEL NAME
page_title = 'Create ' + page.capitalize()
model = apps.get_model('devices', page.capitalize())
status = "created"
if request.method == 'POST':
form = BrandForm(request.POST)
else:
form = BrandForm()
return save_brand_form(request, form, 'devices/brand/create.html', page_title, status)
While it's possible to fix your solution, it will be non-standard, very hard to read and probably full of bugs. Luckily, django provide very good solution to implement CRUD - class-based views.
So, in your case:
urls.py
from .views import BrandCreateView, VersionCreateView
urlpatterns = [
path('brand/create', BrandCreateView.as_view()),
path('version/create', VersionCreateView.as_view()),
]
views.py
from django.views.generic.edit import CreateView
from .models import Brand, Version
from .forms import BrandForm, VersionForm
class BrandCreateView(CreateView):
model = Brand
form_class = BrandForm
template_name = 'devices/brand/create.html'
class VersionCreateView(CreateView):
model = Version
form_class = VersionForm
template_name = 'devices/version/create.html'
Related
I have a view for creating blog posts which redirects the user to a form to fill the blog post content like this:
from django.views import View
from app.models import BlogPost
class CreateBlogPost(View):
def post():
new_post = BlogPost.objects.create()
return redirect(reverse('post_edit'), args=[new_post.id])
class EditBlogPost(View):
...
And my urls are the following:
from django.urls import path
from app.views import CreateBlogPost
urlpatterns = [
path('post', CreateBlogPost.as_view(), name='post_create'),
path('post/<int:pk>/edit', EditBlogPost.as_view(), name='post_edit')
]
I would like to: test the CreateBlogPost by asserting that it redirects to post/<some_id>/edit.
I've tried: using the method assertRedirects from django's SimpleTestCase, but couldn't find a way to make this work.
I'm also using pytest-django, in case that's relevant.
I am new to django and postgresql,I am currently doing CRUD and I have been able to make the create and insert page,I am able to ad the details as it appearas in the database
but it isnt appearing in the read page
here's the code in views.py
def show_cat(request):
showcategory = Categories.objects.filter(isactive=True)
#print(showall)
serializer = CategoriesSerializer(showcategory,many=True)
#print(serializer.data)
return render(request,'polls/show_cat.html',{"data":serializer.data})
def insert_cat(request):
if request.method == "POST":
insertcategory = {}
insertcategory['category_name']=request.POST.get('category_name')
insertcategory['category_description']=request.POST.get('category_description')
form = CategoriesSerializer(data=insertcategory)
if form.is_valid():
form.save()
print("hkjk",form.data)
messages.success(request,'Record Updated Successfully...!:)')
return redirect('categories:show_cat')
else:
print(form.errors)
return redirect('categories:show_cat')
else:
insertcategory = {}
form = CategoriesSerializer(data=insertcategory)
if form.is_valid():
print(form.errors)
return render(request,'polls/insert_cat.html')
urls.py
from django.urls import path
from categories import views
from django.urls.conf import include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns=[
path('',views.show_cat,name="show_cat"),
path('insert_cat/',views.insert_cat,name="insert_cat"),
path('edit_cat/',views.edit_cat,name="edit_cat"),
path('del_cat/',views.del_cat,name="del_cat")
]
I have tried everything possible but I am not able to display the data on the 'read'page,please help
I am new to django restframework. GET request works fine, the data from database is retrived on client side, but while doing the post request no data is added to database. I want to retrieve the data from react axios from django api and store it in database. It is not showing any error but it is also not adding the json data in database.
here is views.py
class formAPI(APIView):
def get(self,request):
if request.method=='GET':
formData=Form.objects.all()
serializer=FormSerializer(formData,many=True)
return Response(serializer.data)
def post(self,request):
if request.method == 'POST':
data_Serializer = FormSerializer(data=request.data)
if data_Serializer.is_valid():
data_Serializer.save()
return Response(data_Serializer.data,status=status.HTTP_201_CREATED)
return Response({'key': 'value'})
here is models.py
from django.contrib.gis.db import models
from phonenumber_field.modelfields import PhoneNumberField
# Create your models here.
class Form(models.Model):
Province=models.CharField(max_length=100,null=False)
District=models.CharField(max_length=100,null=False)
PalikaType=models.CharField(max_length=100,null=False)
PalikaName=models.CharField(max_length=100,null=False)
Ward_No=models.CharField(max_length=100,null=False)
Ward_Office_Address=models.CharField(max_length=100,null=False)
Ward_Contact_No=PhoneNumberField()
X_Cords=models.FloatField(null=False)
Y_Cords=models.FloatField(null=False)
Chairperson_Name=models.CharField(max_length=100,null=False)
Chaiperson_Contact_No=PhoneNumberField()
Secretary_Name=models.CharField(max_length=100,null=False)
Secretary_Contact_No=PhoneNumberField()
Area=models.FloatField(max_length=100,null=False)
Total_Households=models.IntegerField(null=False)
Total_Population=models.IntegerField(null=False)
Total_Male_Population=models.IntegerField(null=False)
Total_Female_Population=models.IntegerField(null=False)
Website= models.URLField(max_length=200)
Email=models.EmailField(max_length=254)
location= models.PointField(srid=4326,null=False)
def __str__(self):
return 'PalikaName: %s' % self.name
here is the data to be stored
{ Province: "province 1",
District: "bhaktapur",
PalikaType: "gaupalika",
PalikaName: "madhyapur gaupalika",
Ward_No: "5",
Ward_Office_Address: "balkumari",
Ward_Contact_No: "+9779818523950",
X_Cords: 85.385252,
Y_Cords: 27.675952,
Chairperson_Name: "kumar sanu",
Chaiperson_Contact_No: "+9779815523950",
Secretary_Name: "ranja",
Secretary_Contact_No: "+9779813523950",
Area: 784.0,
Total_Households: 422,
Total_Population: 32,
Total_Male_Population: 224,
Total_Female_Population: 124,
Website: "http://madhyapurthimimun.gov.np/en",
Email: "info#madhyapurthimimun.gov.np",
}
here is urls.py
from django.contrib import admin
from django.conf.urls import url
from django.urls import path, include # add this
from rest_framework import routers # add this
from formback import views
from rest_framework.urlpatterns import format_suffix_patterns
router = routers.DefaultRouter() # add this
router.register(r'form', views.FormView, 'Form')
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include(router.urls)),
url(r'^getform/', views.formAPI.as_view()),
]
here is serializers.py
from rest_framework import serializers
from .models import Form
class FormSerializer(serializers.ModelSerializer):
class Meta:
model = Form
fields = '__all__'
Thank you in advance
I created several date-based views in Django, and while views for year and month function as expected, the view to display days is not detected. For instance, if I try to get /balance/2018/, or /balance/2018/04/ the views will be displayed, while /balance/2018/04/02 will fail. I understand that the problem must be with urls.py configuration, but I just cannot find it in documentation. I also tried passing day_format='%d' to as_view method, without any results.
my urls.py file
from django.urls import path, re_path
from .views import ArticleYearArchiveView, ArticleMonthArchiveView, ArticleDayArchiveView
from . import views
urlpatterns = [
path('', views.index, name='index'),
path(r'<int:year>/<int:month:>/<int:day>/', views.ArticleDayArchiveView.as_view(day_format='%d'), name='show_day'),
path(r'<int:year>/<int:month>/', views.ArticleMonthArchiveView.as_view(month_format='%m'), name='show_month'),
path(r'<int:year>/', views.ArticleYearArchiveView.as_view(), name='show_year'),
]
my views.py file
from django.shortcuts import render
from django.views.generic.dates import YearArchiveView, MonthArchiveView, DayArchiveView
from django.http import HttpResponse
from django.db.models import Sum
from .models import Category, Article
import datetime
# Create your views here.
def index(request):
num_of_articles = Article.objects.all().count()
num_of_categories = Category.objects.all().count()
return render(request, 'index.html', context = {
'num_of_articles':num_of_articles,
'num_of_categories':num_of_categories})
class ArticleYearArchiveView(YearArchiveView):
queryset = Article.objects.all()
date_field = 'financial_day'
make_object_list = True
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['summation'] = Article.objects.all().filter(financial_day__year=kwargs['year'].year).aggregate(Sum('amount_of_money'))['amount_of_money__sum']
return context
class ArticleMonthArchiveView(MonthArchiveView):
queryset = Article.objects.all()
date_field = 'financial_day'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['summation'] = Article.objects.all().filter(financial_day__year=kwargs['month'].year).filter(financial_day__month=kwargs['month'].month).aggregate(Sum('amount_of_money'))['amount_of_money__sum']
return context
class ArticleDayArchiveView(DayArchiveView):
queryset = Article.objects.all()
date_field = 'financial_day'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['summation'] = Article.objects.all().filter(financial_day__year=kwargs['day'].year).filter(financial_day__month=kwargs['day'].month).filter(financial_day__day=kwargs['day'].day).aggregate(Sum('amount_of_money'))['amount_of_money__sum']
return context
#Here it'll show ARTICLE DETAILS for a given SLUG url
def show_article(request, article_slug):
response = "You are looking at the article %s."
return HttpResponse(response % article_slug)
Error text is:
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/balance/2018/04/02
Using the URLconf defined in spendings_calculator.urls, Django tried these URL patterns, in this order:
admin/
balance/ [name='index']
balance/ <int:year>/<int:month:>/<int:day>/ [name='show_day']
balance/ <int:year>/<int:month>/ [name='show_month']
balance/ <int:year>/ [name='show_year']
The current path, balance/2018/04/02, didn't match any of these.
You have a stray : after month - <int:month:>. Remove it:
path(r'<int:year>/<int:month>/<int:day>/', views.ArticleDayArchiveView.as_view(day_format='%d'), name='show_day'),
Also, note that you are defining the URL for balance/2018/04/02/ (with a trailing slash) but you are going to http://localhost:8000/balance/2018/04/02 (without a trailing slash). Once you have fixed the typo above, Django should redirect you to the URL with the trailing slash.
In the last few weeks I've switched from developing an application that processes a simple XML file, then writes its contents to an Oracle DB (cx_Oracle) and outputs in HTML, to using a Django framework. The Django framework switch wasn't necessary, but since I have an opportunity to develop something by using Django, I thought why not as it is a new area for me and can't damage my CV.
Anyway, I'm having issues with knowing what to write in my urls.py file when importing a Class from the views.py file. Here are the current contents:
urls.py
from myproj.views import Pymat_program
pymatProgram = Pymat_program()
urlpatterns = (
url(r'^pymat/$', pymatProgram.abc),
)
views.py
class Pymat_program:
def abc(self, request):
test = "<html><body>Random text.</body></html>"
return HttpResponse(test)
I've tried various permutations of using request, not using request, and also how the class is called in the url tuple, all to no avail. When I use a definition outside of the class (i.e. not in any class), then this is correctly displayed in HTML.
You don't want to wrap your program in a class. (In general, in Python you should treat modules like, say, Java might treat classes with static members only.)
There are two approaches, really:
Function-based views
urls.py
from myproj.views import abc_view
urlpatterns = (
url(r'^pymat/$', abc_view),
)
views.py
def abc_view(request):
test = "<html><body>Random text.</body></html>"
return HttpResponse(test)
Class-based views
urls.py
from myproj.views import AbcView
urlpatterns = (
url(r'^pymat/$', AbcView.as_view()),
)
views.py
from django.views.generic import View
class AbcView(View):
def get(self, request, *args, **kwargs):
test = "<html><body>Random text.</body></html>"
return HttpResponse(test)
Since you are using class based views in Django, so you have to call this class in URL like:
from myproj.views import Pymat_program
pymatProgram = Pymat_program()
urlpatterns = (
url(r'^pymat/$', pymatProgram.as_view()),
)
and then use get or post methods name in class like:
class Pymat_program:
model = ModelName
def post(self, request, *args, **kwargs):
....
2nd way is to use function based views:
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^articles/2003/$', views.view_name),
]
views.py
from django.http import HttpResponse
import datetime
def view_name(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
for more details look into class based views docs