Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Good practice for helper functions in Django views
I am working in a project in Django. On my views.py I need to make use of multiple helper functions. In order to keep my code clean, I am going to create another file to wrap all these functions. I was planning to call the file just functions.py or helpers.py. Which is the good practice to add helper functions for Django views? Is there any kind of convention, rule or anything? Thanks! -
Why is it possible to create an object in the shell with empty attributes even though they are set as 'null=False, blank=False'?
I am just starting to learn how to write tests in Django, so I am a beginner. I am now trying to test a view called create_person which allows the user to input the first and last name, in order to create a person object. To make it clear this is the Person class: class Person(models.Model): first_name = models.CharField(max_length=100, null=False, blank=False) last_name = models.CharField(max_length=100, null=False, blank=False) slug = models.SlugField() def __str__(self): return F"%s %s" % (self.first_name, self.last_name) I know that even without specifying blank and null values (which by default are set to False) the validation at template level will stop the user from creating a Person object, but I would like to see this working in the backend too. Having the following view: def create_person(request): form = PersonForm() template_name = 'create_person.html' persons = Person.objects.all() works = Work.objects.all() if request.method == 'POST': form = PersonForm(request.POST) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] Person.objects.create(first_name=first_name, last_name=last_name) return redirect(home) context = {'form': form, 'persons': persons, 'works': works, } return render(request, template_name, context) And wanting to only test the person context variable, I have written the following test: def test_no_name_person(self): """ A person with no name given cannot be created and is not … -
how to set multiple dependent dropdown lists using ajax and django forms.I tried one way it is working on one dropdown
options.html {% for issue in issues %} <option value="">select issue type</option> <option value ="{{ issue.ID }}" title="{{ issue.DESCRIPTION }}" data-pic="/{{ issue.ICON }}" {% include "django/forms/widgets/attrs.html" %}> <h7>{{ issue.NAME }}</h7> </option> {% endfor %} {% for root in rootcause %} <option value="{{ root.ID }}" title="{{ root.DESCRIPTION }}" {% include "django/forms/widgets/attrs.html" %}> <h7>{{ root.NAME }}</h7> </option> {% endfor %} Ajax call <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> richText('id_DESCRIPTION'); richText('workDesc'); richText('environment'); $("#id_PROJECT").change(function () { var url = $("#IssuecreateForm").attr("data-types-url"); var PROJECTId = $(this).val(); $.ajax({ url: url, data: { 'PROJECT': PROJECTId }, success: function (data) { $("#id_TYPE").html(data); $("#id_ROOT_CAUSES").html(data); } }); }); </script> views.py def PROJECT(request): PROJECT_id = request.GET.get('PROJECT') print(PROJECT_id) issues = IssueType.objects.filter(PROJECT_id=PROJECT_id).exclude(TYPE__in=('EPIC','IS_SUB_TASK')).order_by('NAME') rootcause=RootCause.objects.filter(PROJECT_id=PROJECT_id,LIVE=True) print(issues) return render(request, 'project_management/user/projects/options.html', {'issues': issues,'rootcause':rootcause}) -
list object has no attribute model in drf
I am trying to return a list(created using queryset) from the overriden get_queryset() method. I can't return queryset directly as i have to change the columns names returned in the queryset. def get_queryset(self): project_id=self.request.query_params.get('projectid') labelled_img= LabelledImage.objects.filter(project_id=project_id).values('label_id') queryset=ArtialClass.objects.filter(labels__label_id__in=labelled_img).values_list('class_name').annotate(total=Count('class_id')).order_by('class_name') pagination.PageNumberPagination.page_size = 1000 return [{'class_name':i[0],'total':i[1]} for i in queryset] In normal scenario, the code is working fine. But when i am trying to append Filter class filter_backends = (filters.DjangoFilterBackend,) filterset_class = ListClassFilter I am getting the following error: model = queryset.model AttributeError: 'list' object has no attribute 'model' -
Unable to see the Django default page on command "python manage.py runserver"
I first created a virtual environment of python in user directory. Then I navigated to desktop and run a command to start a project django-admin startproject eitan. This command created a folder called eitan on desktop. Below is the tree structure of directory eitan - . ├── a │ ├── __init__.py │ ├── __init__.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── app_users │ ├── __init__.py │ ├── __init__.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── db.sqlite3 ├── eitan │ ├── __init__.py │ ├── __init__.pyc │ ├── settings.py │ ├── settings.pyc │ ├── urls.py │ ├── urls.pyc │ ├── wsgi.py │ └── wsgi.pyc └── manage.py I also create two Django application called a and app_users inside the eitan directory. Then I executed command python manage.py runserver 0.0.0.0:8080 which started the Django server on http://127.0.0.1:8080/. The server URL http://127.0.0.1:8080/ was not showing the default landing page (the launching rocket icon) of Djnago application. Instead it was asking me to start Djnago appication. Below is the screenshot of the result I … -
Start django on production with python version 3.7 [closed]
On production i am using Django 2.1 + Nginx + uWSGI. Now i am planing to migrate to Django 3. Django 3 requires Python version 3.6+, but my current python version is 3.5. I am installed python 3.7 on my dev server from souce as make altinstall so on dev server i can run it as python37 manage.py runserver, but on production server how can i define python version to 3.7 to start server? I am not using virtualenv at production. -
Django permission: how to manage permissions not linked to a particular model?
I develop a Django project with different apps For now, I manage permissions to different apps using permissions related to a model But I have developped an export app (data exported from all tables in xls) that is not related to a particular model I could set my 'can_export' permission in a Meta class of one of the exported tables but I wonder if there is another way? -
xlsx/csv utf-8' codec can't decode byte 0xa9 in position 10: invalid start byte
I am getting CSV file and xlsx file from client to server and I opening with below format: decoded_file = files.read().decode('utf-8').splitlines() reader = csv.DictReader(decoded_file) other_data={} # this dict will get the data except questions and answers other_data_list=[] # this will contain the whole data which have to be added to the file txt question_value="" answer_value="" The csv file is working accurate but when I upload xlsx file it gives me below error of: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa9 in position 10: invalid start byte how can I read xlsx, I have to use the above format. -
Inserting server video in wysiwyg
At the moment I am using RichTextUploadingField from ckeditor_uploader.fields. It is a great wysiwyg module. It allows to upload images and flash content as well. However, I need to add functionality for video upload as well. How can I do that? I can't find any modules for this and I am surprised no one has ever needed it. I am thinking of implementing it myself but where do I begin (are there any tutorials or something?) to build a custom plugin for CKEditor for Django? P.S. I am also open to changing CKEditor for something else if they provided Video Upload through the server (not just having an embed video functionality). -
Sending(From) Mail configuration in django
I was configured email SMTP configurations in settings.py file as below EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'from mail' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 Now its working fine but my problem is after deploying the project how can I change any parameter like from_mail/password by user input form...Simply I need to update/change email or password...plz help me any one by sharing best approach Thanks in advance -
AttributeError: 'str' object has no attribute 'as_widget' [closed]
I was trying to replicate code from https://github.com/OmkarPathak/Django-to-do However i have stumbled upon an error which gives me in tags.py file located in todo/tasks/templatetags/tags.py which states - AttributeError: 'str' object has no attribute 'as_widget' here's the complete traceback: Traceback (most recent call last): File "/home/mayureshkadam/PycharmProjects/Django-to-do/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/mayureshkadam/PycharmProjects/Django-to-do/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/mayureshkadam/PycharmProjects/Django-to-do/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/mayureshkadam/PycharmProjects/Django-to-do/todo/tasks/views.py", line 36, in tasks return render(request, 'tasks.html', {'form': form, 'tasks': tasks, 'user': user}) File "/home/mayureshkadam/PycharmProjects/Django-to-do/venv/lib/python3.7/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/home/mayureshkadam/PycharmProjects/Django-to-do/venv/lib/python3.7/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/home/mayureshkadam/PycharmProjects/Django-to-do/venv/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/home/mayureshkadam/PycharmProjects/Django-to-do/venv/lib/python3.7/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/home/mayureshkadam/PycharmProjects/Django-to-do/venv/lib/python3.7/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/home/mayureshkadam/PycharmProjects/Django-to-do/venv/lib/python3.7/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "/home/mayureshkadam/PycharmProjects/Django-to-do/venv/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated return self.render(context) File "/home/mayureshkadam/PycharmProjects/Django-to-do/venv/lib/python3.7/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/home/mayureshkadam/PycharmProjects/Django-to-do/venv/lib/python3.7/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/home/mayureshkadam/PycharmProjects/Django-to-do/venv/lib/python3.7/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "/home/mayureshkadam/PycharmProjects/Django-to-do/venv/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated return self.render(context) File "/home/mayureshkadam/PycharmProjects/Django-to-do/venv/lib/python3.7/site-packages/django/template/loader_tags.py", line 62, in render result = block.nodelist.render(context) File "/home/mayureshkadam/PycharmProjects/Django-to-do/venv/lib/python3.7/site-packages/django/template/base.py", line 936, in render bit = … -
Redirect after login using JWT authentication
Im using this library django-rest-framework-simplejwt and want to I want to be able to redirect to the endpoint after successfully obtaining a token. I have a standard implementation of getting a token taken from the documentation from rest_framework_simplejwt import views as jwt_views urlpatterns = [ path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), ] Is there any way to change the operation of the TokenObtainPairView function to redirect to the endpoint? -
Django & uWSGI ImproperlyConfigured Problem(SQLite 3.8.3 or later is required)
I have already read some articles about "SQLite 3.8.3 or later is required" problem, commonly about old sqlite3 version and might be solved by installing a latest version with LD_LIBRARY_PATH=new/installed/sqlite3. Well, it did solve my problem partly. When I finished the above procedure, I did run python3 manage.py runserver successfully. BUT, when I was going to move the project to uwsgi, I got django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). Following my uWSGI shell cmd: uwsgi --http :8000 --pythonpath /mnt/datasource/<privacy_hidden>/venv/bin/python3 --virtualenv=/mnt/datasource/app-repos-management/back/venv --wsgi-file delivery/wsgi.py --master --processes 4 --threads 4 Relative Output Is: *** Starting uWSGI 2.0.18 (64bit) on [Mon Mar 2 16:55:39 2020] *** compiled with version: 4.8.5 20150623 (Red Hat 4.8.5-39) on 02 March 2020 08:43:11 os: Linux-3.10.0-1062.4.3.el7.x86_64 #1 SMP Wed Nov 13 23:58:53 UTC 2019 nodename: localhost.localdomain machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 4 current working directory: /mnt/datasource/<privacy_hidden> detected binary path: /home/user/.local/bin/uwsgi your processes number limit is 31049 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uWSGI http bound on :8000 fd 4 uwsgi socket 0 bound to TCP address 127.0.0.1:45914 … -
504 gateway timeout from nginx/uwsgi
I'm trying to debug a long-running Django page (it could take a minute or two to respond**). I've think I've set the relevant timeout params in my nginx config: location @proxy_to_app_en { proxy_set_header X-Forwarded-Proto https; uwsgi_pass_header X_FORWARDED_PROTO; include uwsgi_params; uwsgi_read_timeout 300s; proxy_read_timeout 300s; uwsgi_pass app_en; uwsgi_pass_request_headers on; uwsgi_param HTTP_AUTHORIZATION $http_x_api_auth; } and I've also set harakiri in the relevant uwsgi config to 300 seconds. Despite this, I'm still getting a 504 from nginx after exactly 30 (thirty) seconds. Is there some other timeout setting I'm missing? What's causing nginx to timeout and return a 504 after just 30 secs? Thanks :) ** it wouldn't normally, but I'm running django-debug-toolbar on it, which seems to slow everything down massively. -
How to correctly include SVG spritesheets in Django Templates
I created an SVG sprite sheet and am now looking at various ways of using it in my Django templates. The easiest way is this: Add the spritesheet in the templates/ folder (e.g. templates/svg_spritesheet.svg) Include it in the Django template like so: {% include "svg_spritesheet.svg" %} Call upon a given svg in the HTML code via: <svg><use xlink:href="#my_svg"></use></svg> This has worked out for me. But this method has imperfections. For example: I normally park my static assets at {{ STATIC_URL }}. That is better for organization purposes. Secondly, I employ webserver level caching for assets in {{ STATIC_URL }}. I do not employ such caching for my /templates folder however. So naturally, it seems to me that it would be better if I parked my SVG spritesheets at {{ STATIC_URL }}. But once I do that, how do I include it in my Django template? None of the following methods work: {% include 'static/svg_spritesheet.svg' %} {% include '{{ STATIC_URL }}svg_spritesheet.svg' %} <object type="image/svg+xml" data="{{ STATIC_URL }}svg_spritesheet.svg"></object> <link type="image/svg+xml" href="{{ STATIC_URL }}svg_spritesheet.svg"> Can an expert give an illustrative example of how to use SVG sprite sheets that are placed at {{ STATIC_URL }}? Thanks in advance (in case warranted, I'm using … -
Angular frontend Django backend log in
I have tried cors headers, I created API. I'm able to login and create user. Already created super user at the backend. The problem I'm having is with homepage. Once the user login, they are not redirected to home component. Also my login form is in app component not a seperate component. Can anyone help me out? I'm new at this.. I have entire project at this repository link: https://github.com/karan8891/Capstone?files=1 -
Pycharm: type error on field extension in Django
I defined my own extension of FloatField to add unit attributes like so: class MetricFloatField(models.FloatField): """ Implements a Float Field for quantities in the Metric System, with a unit and a unit multiplier """ def __init__(self, unit_prefix="", unit="", *args, **kwargs): self.unit_prefix = unit_prefix self.unit = unit super().__init__(*args, **kwargs) def deconstruct(self): unit_prefix, unit, args, kwargs = super().deconstruct() if not self.unit_prefix == "": kwargs['unit_prefix'] = self.unit_prefix if not self.unit == "": kwargs['unit'] = self.unit return unit_prefix, unit, args, kwargs It works perfectly, but I get annoyed with Pycharm not recognizing types, e.g. class CylindricalComponent(Models.model): thickness = MetricFloatField(default=0.0, unit=unit.m) length = MetricFloatField(default=0.0, unit=unit.m) inner_diameter = MetricFloatField(default=0.0, unit=unit.m) outer_diameter = MetricFloatField(default=0.0, unit=unit.m) @property def volume(self): return (pow(self.outer_diameter / 2, 2) - pow(self.inner_diameter / 2, 2)) * np.pi * self.length On mathematical operations, it gives me: Expected type 'int', got 'MetricFloatField' instead Inspection info: This inspection detects type errors in function call expressions. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Types of function parameters can be specified in docstrings or in Python 3 function annotations. When using standard FloatField this doesn't occur. Any idea how I can fix this? I don't want to disable … -
ERROR: relation "auth_user" does not exist at character 280
I am trying to deploy my Django application & postgres in Kubernetes. I am using:- Django: 2.1.9 Psql: 9.6.3 All the pods and deployment are running successfully in the minikube dashboard. When I try to run the Django deployment service in the browser by entering the superuser credentials, it says wrong username & password. Although I am creating the superuser in the Django web application. The postgres deployment logs give the below error:- ERROR: relation "auth_user" does not exist at character 280 I am new to kubernetes and Django. I tried to find a solution online but did not find any fix. Any help is appreciated! Thanks in advance! -
Can I override the way that a bootswatch theme works?
I am using the Bootswatch Lux theme on my Django based site, but bold text just appears as little different from normal text. Is it possible/wise to change the css is some way to produce a greater differentiation between normal and bold text? -
Django-invitations, Django-Allauth: pass model field data from custom invitation to (custom) user object
I'm combining django-invitations with django-allauth for user invitation and signup. I'd like the Administrator (when creating an invitation through the Django Admin) to provide extra data (here a foreign key to Patient object). This is archieved by adding an extra field to the (custom) invitation model: class PatientInvitation (AbstractBaseInvitation): email = models.EmailField(unique=True, verbose_name=_('e-mail address'), max_length=app_settings.EMAIL_MAX_LENGTH) created = models.DateTimeField(verbose_name=_('created'), default=timezone.now) patient = models.ForeignKey(Patient, blank=True, null=True, on_delete=models.CASCADE) @classmethod def create(cls, email, inviter=None, patient=None, **kwargs): key = get_random_string(64).lower() instance = cls._default_manager.create( email=email, key=key, inviter=inviter, patient=patient, **kwargs) return instance def key_expired(self): expiration_date = ( self.sent + datetime.timedelta( days=app_settings.INVITATION_EXPIRY)) return expiration_date <= timezone.now() def send_invitation(self, request, **kwargs): current_site = kwargs.pop('site', Site.objects.get_current()) invite_url = reverse('invitations:accept-invite', args=[self.key]) invite_url = request.build_absolute_uri(invite_url) ctx = kwargs ctx.update({ 'invite_url': invite_url, 'site_name': current_site.name, 'email': self.email, 'key': self.key, 'inviter': self.inviter, }) When the invited user signs up, I would like this data to end up in the Custom user model: class customUser(AbstractUser): username_validator = MyValidator() is_patient = models.BooleanField(default=False) patient = models.ForeignKey(Patient, null=True, blank=True, on_delete=models.CASCADE) username = models.CharField( _('username'), max_length=150, unique=True, ) I've looked into the signals to pass the data, but couldn't find how exactly to do this. Another option seems to add the PK of the foreign key to a hidden field … -
How can I change the submit button text on a fom created with Django AbstractEmailForm class
I have a form that I have created class FoodDiaryPage(AbstractEmailForm): template = "food_diary/food_diary_form.html" intro = RichTextField(blank=True) thank_you_text = RichTextField(blank=True) content_panels = AbstractEmailForm.content_panels + [ FieldPanel('intro', classname="full"), InlinePanel('form_fields', label="Form fields"), FieldPanel('thank_you_text', classname="full"), MultiFieldPanel([ FieldRowPanel([ FieldPanel('from_address', classname="col6"), FieldPanel('to_address', classname="col6"), ]), FieldPanel('subject'), ], "Email"), ] How can I change the submit button text from 'Submit Query'? -
Django search for child models via foreign key
I have a models.py file that more or less looks like this: class Match(models.Model): match_id = models.BigIntegerField() class Team(models.Model): team_id = models.CharField(max_length=4) match = models.ForeignKey( Match, related_name='teams', on_delete=models.CASCADE, ) win = models.BooleanField() class Player(models.Model): player_id = models.IntegerField() team = models.ForeignKey( Team, related_name='players' on_delete=models.CASCADE, ) For each match, I want to find the two teams that played, and for each team, I want to find the players that were on the team. This is what I tried so far: match_id = 123456789 match_info = Match_model.objects.get(match_id=match_id) red_info = Team_model.objects.get(match=match_info, team_id='Red') blue_info = Team_model.objects.get(match=match_info, team_id='Blue') red_players = Player_model.objects.filter(team=red_info) blue_players = Player_model.objects.filter(team=blue_info) but Django is giving me the error: Team matching query does not exist. How would I go about fixing this error? Any pointers on how to correct my queries would be greatly appreciated! -
mongo DB+flask vs Django. Which one do you think is better for python based website? [closed]
Hi~ I want to make a python based website. Which language do you think is better to make a python based website? mongo DB + flask vs Django of course, they all have pros and cons but I want to ask you if you are in my situation, what would you choose? and why? -
how to create django multiple user types
I am working on a project where I need to have 3 types of Users. Admin Vendor Customer My first approach to this problem was to define all models by sub-classing the AbstractUser model class Customer(AbstractUser): pass class Vendor(AbstractUser): pass so the question is do i need to craete a UsermManager for every usertype model ? -
Check if ManyToMany relationship on certain date exists, then exclude that entry
I have this model: class Assignment(models.Model) assignment_date = models.DateField(blank=True, null=True) chosen_driver = models.ManyToManyField('driver.Driver', blank=True, verbose_name=_( "Chosen driver"), related_name="driver_chosen") ... A chosen driver can only have one assignment per day. So when getting the Assignment queryset I want to check for the assignment_date and then see if the Driver model already has an assignment with this date. So I though something like this: driver = get_object_or_404(Driver, pk=1) dcl = [] for entry in driver.driver_chosen.all(): dcl.append(entry.assignment_date) Then we have a list with all the dates of assignments where this Driver is chosen. Then when constructing the queryset of Assignment maybe something like this to compare the dates to each other and exclude from the queryset: for entry in Assignment.objects.all() if entry.assignment_date in dcl: queryset = Assignment.objects.exclude(entry.pk) return queryset But this returns a TypeError: cannot unpack non-iterable int object error. Can someone help?