Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where to write pure python code in Django?
I have learned the basics of Django. I would like to make a website with 4 calculators and my question is where to put pure python code responsible for all calculations(like all functions and math)? Should I write my calculator in views.py or create new file for example calcA.py ? I am asking because I would like to learn good practice of writting projects in Django. My concept is for each calculator I will make app so for 4 calculators I will make 4 apps. In each app folder I will create models.py which is kind of sketch/outline that will be placed in templates. In each app folder, in views.py I will write calculators using python. Am I correct? -
How to call this form using ajax below code
I have made Django Form with Html code how to make ajax call.I am new to Ajax. the problem is when we put input the output will come but form is invisible.if ajax will call this then everything will be fine forms.py from django import forms class ReportForm(forms.Form): text = forms.CharField(widget=forms.Textarea(attrs={'rows': 5, 'cols': 100})) html {% extends 'base.html' %} {% block content %} <h1>StopWordsRemoval</h1> <div> <form action = "" method = "post" > {% csrf_token %} {{ form.as_p}} <button type="submit">stopwordsremoval</button> </div> <div > <ul> <li>{{ naturallanguageprocessing }}</li> <a href="{% url 'stopwordsremoval' %}" </a> <style> div { width: 1000px; border: 5px solid green; padding: 10px; margin: 10px; } </style> </div> </div> {% endblock %} -
Arithmetic operations between Django fields belonging to the same class model. Is it possible?
i have the need to divide a class field (Value) in Django-admin model with a fixed value (coefficient) in the same class. The result of this operation should populate another field (Points) of the same class. Both values are of same type (integers). For example a user enter a value of '180', then he leaves coefficient to its default '10'. When it saves the new entry it should show up Points = 18 So for the moment i defined 'coefficient' field in Django models.py which defaults to 10. 'Value' field is editable as i said above. I thought to use F() to perform math operations between fields however i am not sure if this is the correct tool or there's something simpler. When i set up the following expression on my model i see alot complaints when i make db migrations. Points = Visits.objects.all().annotate(div=F('Value') / F('Coefficient')) Since i am new to Django i appreciate any help on this, maybe i am misunderstanding something obvious. -
How to filter and loop through objects in a Django template
I'm modifying the default article.html template that came with Aldryn Newsblog to allow for a comment form and listing of the comments for that specific article. I have included the form without a problem. But I can't figure out how to query the comments. Here is my template: {% load cms_tags staticfiles sekizai_tags %} comments will go here {% for item in get_blog_comments %} <div class="comment paragraph"> <h4>{{ item.author }}</h4> <p>{{ item.comment }}</p> <p>{{ item.date }}</p> </div> {% endfor %} And models.py: class BlogComment(models.Model): ip_address = models.CharField(max_length=255, verbose_name="IP Address") date = models.DateTimeField(default=datetime.now) article = models.CharField(max_length=255) author = models.CharField(max_length=255) comment = models.CharField(max_length=1000) def get_blog_comments(self, request): return BlogComment.objects.all() And in views.py I have this: def get_blog_comments(req): return BlogComment.objects.all() no one can seem to tell if the get function should exist in views or models. but either way I can't get it to query any comments. As you can see, I'm using objects.all() and it's not showing anything. I haven't even begun to figure out how to filter by article... -
Allow users to create new data models in Django app
I want to give users the ability to create new data models,and specify the relations between these models. My use case is a world simulator. Let's say it has Places, Characters, Incidents, etc models. The user should be able to create additional models, and also specify relations between different models. E.g. We could create subgroups of Characters called Heroes and Villains. We may decide that a Character cannot be both a Hero and a Villain. There may also be many-to-many relationships, e.g. a Character can be in many Incidents, and an Incident can involve many Characters. How do I do this in django? Is it even possible or feasible for users to be changing the actual data models? Or is there some other way to do it implement it -
Django - How to display a form field conditionally
I have a form with 'x' number of fields but I only want some fields presented to the user based on a 'status' field attached per user. Forms.py class ReqForm(forms.Form): item_code = forms.IntegerField(required=False) description = forms.CharField(widget=forms.HiddenInput(), max_length=100) extra_information = forms.CharField(widget=forms.Textarea, required=False) quantity = forms.IntegerField(min_value=0, required=False) price = forms.DecimalField(min_value=0,decimal_places=3, required=False) purchase_order = forms.CharField(max_length=9, required=False) po_line = forms.IntegerField(required=False) req_delivery_date = forms.DateField(required=False) act_delivar_date = forms.DateField(required=False) signature = forms.CharField(min_length=0, max_length=10) For ex. someone with a level 1 status would not be able to see 'item_code','purchase_order', 'po_line' etc. Overall I want a user to create a requisition but that requisition have lines depending on how many items they are including so I built this form into a formset for it to display 3 times. I am attaching my models below as well because i am not sure if im going about this the right way. Models.py class Requisition(models.Model): username = models.ForeignKey( 'users.CustomUser', on_delete=models.CASCADE, related_name='req_user') signature = models.CharField(max_length=10, blank=True, null=True) status = models.ForeignKey('RequisitionStatus', related_name='req_status', on_delete=models.CASCADE) class RequisitionLine(models.Model): parent_req = models.ForeignKey('Requisition', on_delete=models.CASCADE, related_name='par_req_line' ) sequence = models.PositiveIntegerField() item_code = models.ForeignKey( 'items.ItemMaster', on_delete=models.CASCADE, related_name='req_item', blank=True) description = models.CharField(max_length=50, blank=True) extra_information = models.TextField(blank=True) quantity = models.PositiveIntegerField(blank=True) price = models.DecimalField(max_digits=19, decimal_places=2, blank=True) purchase_order = models.CharField(max_length=9, blank=True) po_line = models.PositiveSmallIntegerField(blank=True) req_delivery_date β¦ -
django wait for db operations to be complete
I have a function that iterates over a list and if needed adds a django record and uses.save() After that loop another function is called that accesses the table that just may or may not have had save operations done on it. It seems that there are still pending saves when the second function is called. Is there a method in django to wait for the current operations to be done or what is the best practice for this type of race condition? I put a sleep in before calling the second function and it did happen to give it enough time to finish. This is not good because the sleep is arbitrary. -
Django-filter BooleanField with custom values
After successfully implementing crispy-forms and django-tables2 it came for me to implement filtering in tables using django-filter and I am ripping my hair out. First of all I find it much worse documented and probably this is why I can't find info that I need. I would like to have a dropdown in the form with which I can select weather to show All users, Superusers, Normal users. So I have moved from BooleanFilter to ChoiceFilter with custom choices. class UserFilter(filters.FilterSet): SUPERUSER_CHOICES = { ('', 'All'), ('True', 'Superusers'), ('False', 'Normal users') } username = filters.CharFilter(field_name='username', lookup_expr='icontains') is_superuser = filters.ChoiceFilter(field_name='is_superuser', lookup_expr='exact', choices=SUPERUSER_CHOICES,) test = filters.Filter class Meta: model = User fields = ['username', 'is_superuser'] And this is what I get: Why are these dashes there? How to get rid of them? Maybe I don't even need to use ChoiceFilter to change values of options? -
return json object to index.html and render data to dataTable columns
I want to use dataTable to render data to its columns in index.html after I login to my site . dataTable does not show any data. I knew my issue is in views.py, since I want to return json object to index.html. When I use HttpReponse to return json object, it correctly returned json object as in format below but not in index.html. My approach is that I want to return json object to index.html and render data in dataTable columns. Any helps will be highly appreciated!! views.py @login_required def index(request): if request.user.is_authenticated(): #if (Employee.objects.filter(emp_type__contains = "user").filter(user__username__contains = request.user.username)): if (Employee.objects.filter(Q(emp_type__icontains = "user") | Q(emp_primary__icontains = 2)).filter(user__username__icontains = request.user.username)): projects = Project.objects.filter(user__id__icontains = request.user.id) '''paginator = Paginator(projects, 16) page = request.GET.get("page") try: projects = paginator.page(page) except PageNotAnInteger: projects = paginator.page(1) except EmtyPage: projects = paginator.page(paginator.num_pages) ''' data = serializers.serialize("json", projects) output = [d['fields'] for d in json.loads(data)] #return render(request, 'polls/index.html', {"data": data}) #return render(request, 'polls/index.html', {'projects': projects}) return HttpResponse(data, content_type="application/json") elif (Employee.objects.filter(emp_type__contains = "admin").filter(user__username__contains = request.user.username)): projects = Project.objects.all() '''paginator = Paginator(projects, 16) page = request.GET.get("page") try: projects = paginator.page(page) except PageNotAnInteger: projects = paginator.page(paginator.num_pages) ''' data = serializers.serialize("json", projects) output = [d['fields'] for d in json.loads(data)] #return render(request, 'polls/index.html', β¦ -
How To Implement Google Login With Django Rest Framework While Making An REST API For Android App?
I am in the process of making an android app on java, but i am having trouble in implementing "login with google" for my android app while using Django as the backend. Is there any github repo or any tutorial. Kindly share the link. -
Django 'No module named 'suit.apps' error
I'm trying to customize Django admin site. I ran the command "pip install django-suit", everything installed correctly according to CMD, then I made a new .py file called with apps.py in the main folder(same folder that contains settings.py) and here is the code from suit.apps import DjangoSuitConfig class SuitConfig(DjangoSuitConfig): layout = 'horizontal' and added 'database.apps.SuitConfig',in the settings.py. When I type the command "python manage.py makemigrations database" or "python manage.py runserver" the CMD gives me this error Does anyone know what am I missing? -
Should I learn mobile development after Web development?
I am currently in highschool and I am close to finishing a udemy web development course (frontend and django backend) I know python and basic c . But when i created my first few websites it occurred to me it will be more efficient to put my ideas into apps ? Should I now after web development start with apps ? And if I do what language and frameworks should I use based on what I already know ( I want to build native apps ios or android or both Not phonegap etc apps) I have not dived into the topic of RESTful API but is there a way to use the same database for a django website and a native mobile app coded with another language ? Again, not ports like phonegap Sorry, I know this is alot of questions that actually should be one . Thanks in advance -
VS Code Django Debug - Unverified Breakpoint
I can't seem to have success in setting up the debugger for django, I've tried many times and searched on google and I'm now giving up and opening the question here, hoping to get some help. Here's my debug configuration: { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": ["runsslserver", "--settings=django_settings.settings_app_artist", "127.0.0.1:8000"], "debugOptions": ["RedirectOutput", "Django"] }, The server starts and everything is running fine But I can't set breakpoints, it says "Unverified Breakpoint" What am I doing wrong? Thanks -
django 2.1 no such table when running standalone script
I am attempting to write a standalone script that uses Django's ORM to load some data into one of my tables. I have run python setup.py makemigrations and python setup.py migrate and both have completed successfully. I am able to bring up the server and make additions/changes/removals using the Admin interface. I then can use a sqlite DB browser to verify these operations completed successfully. I am also able to make the exact same change using the python manage.py shell interface: Β» python manage.py shell 0 [2018-08-20-11:48:34] Python 3.5.1 (default, Apr 20 2016, 09:08:58) [GCC 4.8.5] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from api import models >>> models.Format.objects.create(source="Test") <Format: Test> However, the following script does not work and throws an error: #!/usr/bin/env python import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.settings") django.setup() from api import models models.Format.objects.create(source="TEST") The full error: Traceback (most recent call last): File "/path/to/env/lib/python3.5/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/path/to/env/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 296, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: api_format The above exception was the direct cause of the following exception: Traceback (most recent call last): File "mdf_format_api/test.py", line 10, in <module> models.Format.objects.create(source="TEST") File "/path/to/env/lib/python3.5/site-packages/django/db/models/manager.py", line β¦ -
Linkedin-api This resource is no longer available under v1 APIs
I am using allauth for django to authenticate with linkedin, but when I am trying to authenticate it is returning in api response that "This resource is no longer available under v1 APIs" below are my settings for django app. 'SCOPE': [ 'w_share','r_emailaddress','r_basicprofile','rw_company_admin' ], 'PROFILE_FIELDS': [ 'id', 'first-name', 'last-name', 'email-address', 'picture-url', 'public-profile-url', ] please guide me what I am doing wrong. -
Django CMS FieldError: Local field 'created_by' in class 'PageUser' clashes with field of similar name from base class 'User'
I have an existing django 1.9 application on python 3.5 and I'm trying to bring django cms into it. Right now, I'm following the manual install instructions here: http://docs.django-cms.org/en/release-3.3.x/how_to/install.html I want to use the existing postgres db for storing cms data. Right now, all I've done is add the cms apps to INSTALLED_APPS as well as the middleware and the templates, all in the settings file. When I launch my app I get the FieldError. I ran through this http://docs.django-cms.org/en/develop/reference/configuration.html#custom-user-requirements and made sure our custom User was inheriting properly and had the right fields and methods. Our custom User model does inherit from a custom mixin that adds a created_by to the user model. I can't find a workaround that solves this. Any suggestions would be greatly appreciated. -
Docusign: Email To Sign Not Being Received
I am developing a Django webapp for my company that will allow for users (or our sales associates) to enter in customer information, from which Weasyprint will generate a PDF that contains all of the information, and allow the user to sign the docusign digitally using Docusign's Python SDK. Everything is working at this point, minus the sending of the email to the recipient to be signed. I am unsure of why this is happening, and after seeking help from Docusign's employees, none of them seem to have any idea as to what is going wrong. Here is the code with which I am creating and sending the envelope: loa = LOA.objects.filter().order_by('-id')[0] #Model in my SQLite database being used to retrieve the saved PDF for sending. localbillingname = loa.billingname.replace(" ", "_") username = "myusername" integrator_key = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" base_url = "https://demo.docusign.net/restapi" oauth_base_url = "account-d.docusign.com" redirect_uri = "http://MyRedirectUrl.com/" private_key_filename = "path/to/pKey.txt" user_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" client_user_id = 'Your Local System ID' #This is the actual string being used # Add a recipient to sign the document signer = docusign.Signer() signer.email = loa.email signer.name = loa.ainame signer.recipient_id = '1' signer.client_user_id = client_user_id sign_here = docusign.SignHere() sign_here.document_id = '1' sign_here.recipient_id = '1' sign_here.anchor_case_sensitive = 'true' β¦ -
datetime difference in days
I have a model as, class Event(models.Model): name = models.CharField(max_length=100) start = models.DateTimeField() end = models.DateTimeField() @property def diff_days(self): return (self.end - self.start).days How can I get the diff_days result using .annotate() in database level? -
How to make a booking form in django which timeslots and dates available are customizeable on admin
sorry i am a new on Django and I want to do something but cannot figure out how to do it. its basically a form for booking online appointment. in admin i need to be able to put a schedule for today+the next 30days, each day will have different timeslot available and have default timeslots to 17,18,19,20,21,22,23,24 TIMESLOT_LIST = ( (0, '08:30 β 09:00'), (1, '09:00 β 09:30'), (2, '09:30 β 10:00'), (3, '10:00 β 10:30'), (4, '10:30 β 11:00'), (5, '11:00 β 11:30'), (6, '11:30 β 12:00'), (7, '12:00 β 12:30'), (8, '12:30 β 13:00'), (9, '13:00 β 13:30'), (10, '13:30 β 14:00'), (11, '14:00 β 14:30'), (12, '14:30 β 15:00'), (13, '15:00 β 15:30'), (14, '15:30 β 16:00'), (15, '16:00 β 16:30'), (16, '16:30 β 17:00'), (17, '17:00 β 17:30'), (18, '17:30 β 18:00'), (19, '18:00 β 18:30'), (20, '18:30 β 19:00'), (21, '19:00 β 19:30'), (22, '19:30 β 20:00'), (23, '20:00 β 20:30'), (24, '20:30 β 21:00'), ) on the page, when client pick a date, he should see which timeslots are available on the day he picked. i have seen many calendar app or other, but they dont let you choose which timeslot on which date β¦ -
Django (How to prevent users from directly accessing URLs in main_app/urls.py if the User is logged out and user.is_authenticated = FALSE
Django How to prevent users from directly accessing URLS in main_app/urls.py if the user is logged out and user.is_authenticated = FALSE Please note that I used Class Based Views in views.py. The condition if request.user.is_authenticated(): is not working. See below: class EmployeeCreate(CreateView): model = Employee fields = ['first_name', 'last_name', 'role'] def post(self, request, *args, **kwargs): if request.user.is_authenticated(): if "cancel" in request.POST: return HttpResponseRedirect(reverse('main_app:index')) elif "another" in request.POST: return HttpResponseRedirect(reverse('main_app:employee-add')) else: return super(EmployeeCreate, self).post(request, *args, **kwargs) -
How can I find out which line of my Django code is creating a particular postgres query?
In my Django code, some postgres queries are created by the django query set. One of the queries, which can be created by two different view functions in the home page is being done during runtime. I don't know which one is doing the query. For debuggin purposes Is there anyway to trace back a postgres query to which line of code generated it during runtime? -
Is it correct to modify old migration files in Django?
I'm trying to migrate my Django project from Python 2.7/Django 1.11 to Python 3.7/Django 2.1. And I'm a little bit confused with one issue. Django 2.1 marks as errors all models.ForeignKey(...) code strings in my project with: TypeError: __init__() missing 1 required positional argument: 'on_delete' It is because since Django 2.x, 'on_delete' method is required for ForeignKey fields (Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries) If you'll read this post, solution is pretty simple, you just need to add one of 'on_delete' options, for example: models.ForeignKey(..., on_delete=models.CASCADE,) But Django complains not only about actual 'models.py' file but also about all (!) migrations that include "ForeignKey" fields adding or alteration. So my question is, is it safe to modify old migration files in Django? And is it what I should do in this situation? -
Django: AttributeError: view object has no attribute 'kwargs'
I am building a view that I am passing in a uuid from the url. However when I try to access the kwarg, I get a "AttributeError: view object has no attribute 'kwargs'" error. In my template, I am passing a UUID: create/97261b96-23b8-4915-8da3-a90b7a0bdc8e/ The URL: re_path( r"^create/(?P<uuid>[-\w]+)/$", views.DetailCreateView.as_view(), name="detail_create"), The View: class DetailCreateView(SetHeadlineMixin, LoginRequiredMixin, InlineFormSetView): inline_model = Detail headline = "Create a Detail" form_class = DetailForm extra = 10 success_message = "Detail Added" template_name = "details/detail_create.html" def get_object(self, **kwargs): return Post.objects.get_subclass(uuid=self.kwargs.get('uuid')) def __init__(self, *args, **kwargs): super(DetailCreateView, self).__init__(*args, **kwargs) self.object = self.get_object() self.model = self.object.__class__() For context on what is happening - Post is a model that is an InheritanceManager that other models (Product & Variation) inherit from. Both models Product & Variation have a manytomanyfield to Detail. Upon creating a Detail, I will be adding it to either the Product object or Variation object. To set the model for the InlineFormSetView, I am trying to use the UUID to query for the object and dynamically set that based upon the class of the object I am trying to create a Detail for. Question Any ideas why I can't access the kwargs which is being sent in the URL path? -
Apache2 on Ubuntu gives Py_Initialize ImportError: No module named encodings
I'm working on Ubuntu with Apache2, Python 3.6.1. I followed the directions here to set it up with Django and mod_wsgi: How To Serve Django Applications with Apache and mod_wsgi on Ubuntu 14.04 I've looked at a lot of similar questions and still can't get it to work. The Apache error log spews the "ImportError: No module named 'encodings' almost constantly. Here are the relevant settings in my Apache2 files: In 000-default.conf: WSGIDaemonProcess myproject python-home=/home/user/myproject/myprojectenv/ python-path=/home/user/myproject/myprojectenv/bin/python WSGIProcessGroup myproject WSGIScriptAlias / /home/user/myproject/myprojectenv/myproject/myproject/wsgi.py In apache2.conf: WSGIPythonPath /home/user/myproject/myprojectenv Note that, when I check sys.prefix it equals what I have in the WSGIPythonPath above. Yes, I've activated the virtual environment. For my environment variables, I have: PATH = /home/user/myproject/myprojectenv/bin:$PATH PYTHONPATH = /home/user/myproject/myprojectenv/bin:$PYTHONPATH PYTHONHOME = not set I've tried various combinations of the environment variables being set and not being set. None that I've tried have worked. When I followed the steps from the link above, I'm not sure that a new mod_wsgi was built that is for Python 3.6.1. I had tried (on another copy of my VM) to explicitly build a Python shared library and to build mod_wsgi with that. It failed miserably. I hesitate to go that route again unless I'm sure β¦ -
Django: How do i extract the email ID of users on the admin page
How do I extract the email ID of users from the Users columns? I've managed to make sure that the name of the users are extracted through the Users table. class Project(models.Model): STATUS_CHOICE = ( ('Project Manager', 'Project Manager'), ('Technician', 'Technician'), ('Tester', 'Tester') ) STATUS_CHOICE_1 = ( ('Work Assigned', 'Work Assigned'), ('Work in Progress', 'Work in Progress'), ('Testing', 'Testing'), ('Completed', 'Completed') ) project_name = models.CharField(max_length=100) project_description = models.CharField(max_length=100) Admin_Name = models.CharField(max_length=100) Admin_Mail_ID = models.EmailField(max_length=50) Project_Manager_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Project_Manager_1_users") Project_Manager_1_Mail_ID = models.EmailField(max_length=50) Project_Manager_2 = models.CharField(max_length=50, blank=True, null=True) Project_Manager_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Technician_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Technician_1_users") Technician_1_Mail_ID = models.EmailField(max_length=50) Technician_2 = models.CharField(max_length=50, blank=True, null=True) Technician_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Technician_3 = models.CharField(max_length=50, blank=True, null=True) Technician_3_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Tester_1 = models.CharField(max_length=50, blank=True, null=True) Tester_1_Mail_ID = models.EmailField(max_length=50, default='Example@gmail.com') Additional_User_1 = models.CharField(max_length=50, blank=True, null=True) Additional_User_1_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True) Additional_User_1_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Additional_User_2 = models.CharField(max_length=18, blank=True, null=True) Additional_User_2_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True) Additional_User_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Additional_User_3 = models.CharField(max_length=18, blank=True, null=True) Additional_User_3_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True) Additional_User_3_Mail_ID = models.EmailField(max_length=50, blank=True, null=True) Status_of_the_project = models.CharField(max_length=18, choices=STATUS_CHOICE_1) Created = models.DateTimeField(auto_now_add=True, null=True, blank=True) Finish_Date = models.DateTimeField(null=True, blank=True) Supporting_Documents = models.FileField(null=True, blank=True) I'm not that great at coding β¦