Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with model relationship and forms
Im building a warhammer project where a user: 1.Create a list 2.Select the soldier he want to add to the list and the weapons attached to the soldier Im struggling to understand how to list the weapons and the amounts he can choose. I try to "copy" this site: https://imgur.com/LitpaLa It's in French but I hope you get the idea My page: https://imgur.com/o20ZesU My models: class List(models.Model): faction = models.ForeignKey(Faction, on_delete=models.CASCADE) title = models.CharField(max_length=30) class Weapon(models.Model): name = models.CharField(max_length=30) points = models.IntegerField() type_of_weapon = models.CharField(max_length=30,choices=TYPE_OF_WEAPON) class Soldier(models.Model): title = models.CharField(max_length=30) weapons = models.ManyToManyField(Weapon) class SoldierToList(models.Model): soldier = models.ForeignKey(Soldier, on_delete=models.CASCADE,) list = models.ForeignKey(List, on_delete=models.CASCADE,) amount_of_units = models.IntegerField(default=1) And the form I use to add a unit to a list: class SoldierToListForm(forms.ModelForm): def init(self, *args, **kwargs): self.faction_id = kwargs.pop('faction_id') super(SoldierToListForm, self).init(*args, **kwargs) self.fields['soldier'].queryset = Soldier.objects.filter(factions=self.faction_id) class Meta: model = SoldierToList fields = ('soldier','amount_of_units', ) Thanks for your help guys -
Django - Bcrypt: Authentication not working, TypeError
I am trying to use the Django User-Management with bcrypt. I want to simply take a plaintext password and check it against the stored hash. Bcrypt is installed, and my settings.py hashers look like this: PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.SHA1PasswordHasher', 'django.contrib.auth.hashers.MD5PasswordHasher', 'django.contrib.auth.hashers.CryptPasswordHasher', ) The user was created like this: my_user = User.objects.create_user('user', 'email@email.com', 'password') However, every time I try to compare the two: user = authenticate(username="user", password="password") I get the following error: TypeError at /login/ startswith first arg must be bytes or a tuple of bytes, not str Does anyone know how to fix this? -
Django Admin hide a field only in ADD form
In my django project i have this model: class v_pers(models.Model): a_id = models.ForeignKey(v_aree, on_delete=models.CASCADE) t_id = models.ForeignKey(v_tipopers, on_delete=models.CASCADE) p_name = models.CharField(max_length=100) p_sname = models.CharField(max_length=100) p_title = models.CharField(max_length=50) p_image = models.ImageField(upload_to ='pers') p_desc = models.TextField() def image_tag(self): return mark_safe('<img src="/%s" width="150" height="150" />' % (self.p_image)) image_tag.short_description = 'Image' class Meta: verbose_name = "Personale" verbose_name_plural = "Personale" def __str__(self): return self.p_name in my admin.py: class vpersAdmin(admin.ModelAdmin): readonly_fields = ["image_tag"] admin.site.register(v_pers, vpersAdmin) well, in my django admin i would hide my field image_tag only in ADD form and not in change, but if i cannot find how hide just in add form instead both So many thanks ina dvance -
Running Tests of Python and Django Module
I am wondering if there is a standard way to run tests for a Python package that is available on PyPi and Github. Suppose we have this package: https://github.com/Nekmo/djangocms-comments If one wants to run its tests, how would he do it? That is, I get that it should be python setup.py test or something like that. Prior to that, one needs to create a virtual environment with Django in it. After these steps, the command still errors with settings not being setup properly. Hence my question: am I doing something wrong or was this package simply not setup very well for running tests? More generally, what's the most optimal way to contribute code to such module? Should I set it up in a project and install into a virtual environment via pip install -e ./djangocms_comments? Or is there another way as well? Is it possible to run the tests of a package installed in a virtual environment? -
html and javascript audio player with django backend
I'm creating a music streaming website for my final year project.Most of my work is done except actually making the audio play and stream with django.I was wondering if i can make an audio player with html5 and js and get django to render it.Can any one point me to the right direction. -
Serving Django MVC and Django Rest Framework from same Model
This may be an opinionated question but sorry I am too curious. I learned to develop Django Model-View-Template websites ( multi page websites) and Django Rest Framework. From the same Django Model can I create Rest API's and MVC templates together ? I wanted to develop a Blog website that use session authentication and based on MVC architecture. The same server should create API's because the Mobile app for the Blog may consume the API's and use Token Authentication (using Djoser). If I use same User model for session and token authentication, Can mobile blog app users use their username and password to access website version ? -
how to reference a http://localhost location within a Django html page
I am trying to get hls.js to show a CCTV video on a webpage. I have ffmpeg runing on the same machine. In python, this requireshls1.loadSource("http//:xxx.xxx.xx.x/path_to/stream.m3u8"); If, in place of xxx.xxx.xx.x, I use localhost, 127.0.0.1, host_name or the IP_address_of_host I get error GET /path_to_django_app_folder/http://path_to/stream.m3u8 HTTP/1.1" 404 3239 If I drop http address i.e. hls1.loadSource("/path_to/stream.m3u8"); then I get GET /path_to/stream.m3u8 HTTP/1.1" 404 3103 I am sure it is simple but I can't see how to point hls to the relvant folder with an http: string. The file is located in /home/user_name/project_name/path_to/stream.m3u8 Thank you -
How to create a new model object and display the form information in DetailView?
I have a group of patients and location templates. Each patient has a DetailView where the user can link a location to a patient with extra information. How I handle this is I created a form with a dropdown menu and some extra fields different for each patient. When the user chooses a location template from the dropdown menu and fills in the rest of the form(specific to the patient), I want to create another location object with more details, link it to the patient and display this location information on the DetailView page. I believe all these are supposed to happen in PatientDetailView but I am not very experienced with Django, so I hope there is an easy solution. models.py class Patient(models.Model): name = models.CharField(max_length=200) idn = models.CharField(max_length=200, unique=True) date_of_birth = models.DateField() date_of_confirm = models.DateField() case_number = models.IntegerField() def get_absolute_url(self): return reverse("patient_detail", kwargs={'pk':self.pk}) def __str__(self): return self.name class Location(models.Model): patient = models.ForeignKey(Patient, related_name='locations', on_delete=models.CASCADE, null=True, blank=True) location_name = models.CharField(max_length=50, null=True, blank=True) address = models.CharField(max_length=300, null=True, blank=True) district = models.CharField(max_length=300, null=True, blank=True) grid_x = models.IntegerField(null=True, blank=True) grid_y = models.IntegerField(null=True, blank=True) date_from = models.DateField(null=True, blank=True) date_to = models.DateField(null=True, blank=True) details = models.CharField(max_length=300, null=True, blank=True) category = models.CharField(max_length=300, null=True, blank=True) def __str__(self): … -
How to set nginx to serve React and Django properly
I use Linux server to serve React app as frontend and Django as a backend. The gunicorn config is as follows: [Unit] Description=gunicorn daemon After=network.target [Service] User=name Group=www-data WorkingDirectory=/var/www/backend/app ExecStart=/var/www/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/name/backend.sock app.wsgi:application [Install] WantedBy=multi-user.target And nginx config is as follows: server { listen 80; root /var/www/frontend/build; server_name example.com; location = /favicon.ico { access_log off; log_not_found off; } location / { } location /graphql { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-NginX-Proxy true; proxy_ssl_session_reuse off; proxy_set_header Host $http_host; proxy_cache_bypass $http_upgrade; proxy_redirect off; proxy_pass http://unix:/home/name/backend.sock; } } The Django app urls.py is as follows: urlpatterns = [ path('admin/', admin.site.urls), path('reports/', include('reports.urls')), path('graphql/', csrf_exempt(GraphQLView.as_view(graphiql=True))) ] If I do a fetch request to www.example.com/graphql it works fine. But if I want to access Django admin dashboard as follows www.example.com/admin/ it doesn't work. If I understand it good, location /graphql {} means that Django apps runs on that url. Thus, If I want to access to some of the urls in urls.py file, i use www.example.com/graphql/url from urls.py Should it not be then www.example.com/graphql/graphql How to access admin dashboard? What I do not understand good? -
Add my own constraints to django crispy forms
I'm learning to program so I apologize for the broad (and likely silly) question. I am making a website in Django and using crispy forms. I want to add my own constraints and error messages to the form, which I know i can do when I clean the data or with validation. However, when I do this the error msgs appear differently to the crispy forms standard validation msgs (such as for a required field or that a username already exists. Please see this image for an example, the top error msg is a standard crispy one (which I would like all my msgs to be like, for consistency and to hopefully to further my understanding), whereas the one beneath is one I generated in my clean method. https://imgur.com/It0oCGG I just cannot find any information what-so-ever on how to do this. I found the link below, which mentions validation, but it doesn't seem to help me (or perhaps it's just beyond me) https://django-crispy-forms.readthedocs.io/en/latest/crispy_tag_forms.html#ajax-validation-recipe https://imgur.com/It0oCGG Any help or a push in the right direction (a resource maybe) would be greatly appreciated. Thank you. -
Django: Change font-color inside a javascript-function
Good day, the font-color of my html-body is changed via a css-file with following code: body { background-color: #6d6a6a; color: white; } Now I've included a Bootstrap-Popover... <button type="button" class="btn btn-sm btn-danger" data-toggle="popover" title="Popover title" data-content="And here's some amazing content. It's very engaging. Right?">Click to toggle popover</button> ...and the necessary script... <script> $(function () { $('[data-toggle="popover"]').popover() }) </script> But because of my css-file, some parts of text inside my popver (the "title" to be exact) are also rendered in white! I'm really new to javascript, so is it possible - and when it's possible, what would be the best solution - to change my font-color inside my Popover to black? Thanks to all of you! -
Cannot start a project in Atom text editor
Using command:'django-admin startproject first_project' showing ImportError:No module named 'secrets'.enter image description here -
Using MultiFieldPanel inside a StructBlock
If you have a StructBlock class (used inside a StreamField)... Can you still use the Wagtail panels to group some fields (eg MultiFieldPanel) and (ideally!) use the collapsible class on the panel to hide them in some kind of "Advanced" panel? I have tried adding the block.TextBlock definitions into the array for a panel the, however neither the Panel nor the Fields appeared in the form. I cant see anything in the docs about using Panels in StructBlocks: https://docs.wagtail.io/en/v2.8.1/reference/pages/panels.html https://docs.wagtail.io/en/v2.8.1/topics/streamfield.html -
html template not rendering correctly for dynamic html content in django
I have strange issue in HTML template rendering, I have template index.html, in that template i passing dynamic content, here i have placed that code <p class="font-secondary paragraph-lg text-dark" style="color: black;"> {{ portal_contact_home_about|safe }} </p> in portal_contact_home_about this variable it contains data like "<p>Lorem ipsum</p>", so data should have to be render like this <p class="font-secondary paragraph-lg text-dark" style="color: black;"> <p>Lorem ipsum</p> </p> but it is rendering it as wrong way <p class="font-secondary paragraph-lg text-dark" style="color: black;"></p> <p>Lorem ipsum</p> can anyone please help me how to resolve this issue ? -
Connecting React with Python backend
I have created a form using React that uploads a image. This image should be sent to python where it is taking the image as input and giving the category of the image as output. I have designed the React and Python files as well, but I have no idea on how to integrate both. How to send API request to python and get back the response to React? -
I can't display django form fields based on user type or access type
I have a form defined in my forms.py there is this field on my form called "user" which is my foreing key or a reference to my User model. I want this field to display if you are a "CDA Admin" then is field should not display if you are a "CDA member". "CDA Admin" and "CDA member" are ways of determining user type. I know I can achieve this same thing by creating another form, views, linking to urls, etc and creating templates. I don't want to go through that process I want to easily manage it in one place. How do I handle this on my forms.py if possible views and templates? Please, I will really need someone to help me with code samples Below is what I have done so far options.py CDA_EXECUTIVE = 'CDA Executive' CDA_MEMBER = 'CDA Member' CMO = 'CMO' CDA_ADMIN = 'CDA Admin' CHOOSE = '' USER_TYPE = [ (CDA_EXECUTIVE, 'CDA Executive'), (CDA_MEMBER, 'CDA Member'), (CHOOSE, 'Choose User Type'), (CMO, 'CMO'), (CDA_ADMIN, 'CDA Admin'), ] models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser from django.utils.translation import ugettext_lazy as _ class User(AbstractBaseUser, PermissionsMixin): member_id = … -
how to upload files using nested serializer in Django
I have a problem uploading images/files through a nested serializer. I couldn't to see any article or documentation about this nested serializer to handle this. and if you have any library already there to handle such a problem please let me know. here am storing images location path in attachment table related with corresponding student like models misc/models.py class Attachment(BaseModel): file = models.FileField(upload_to=file_upload_location) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() uploader = GenericForeignKey('content_type', 'object_id') student/models.py class Profile(BaseModel): name= models.CharField(max_length=250) attachments = GenericRelation(Attachment) student/serializers.py from misc.models import Attachemnets class ProfileSerializer(WritableNestedModelSerializer): attachments = AttachmentSerializer(many=True, write_only=True, partial=True) class Meta: model = Profile exclude = ('created_at', 'updated_at') -
How can i save 404 requests in Django?
I have a Django app and that work perfect, I want get all request 404 for save. like: 127.0.0.1:8000/admin/hello # result is 404 because i haven't this url I want get /admin/hello because I haven't this Url. how can I do? -
Django CBV handle file upload from form
I've written this form, simple and not linked to a model or Form object (I find it easier this way to style the form and control it's behaviour with js) <form action="{% url 'upload_music_file' %}" method="POST" id="upload-form" enctype="multipart/form-data">{% csrf_token %} <div class="form-group"> <input type="file" class="form-control-file" id="csv-file"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> and the CBV that handles the post request class MusicFileUploadView(TemplateView): template_name = "music_file_upload.html" def get(self, request, *args, **kwargs): return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): print( request.FILES.keys() ) return super().get(request, *args, **kwargs) problem is I don't see the file in the request objects [01/May/2020 08:39:07] "GET /static/img/icon.png HTTP/1.1" 200 4822 dict_keys([]) [01/May/2020 08:39:19] "POST /upload-music-file HTTP/1.1" 200 7266 [01/May/2020 08:39:20] "GET /static/img/icon.png HTTP/1.1" 200 4822 dict_keys([]) [01/May/2020 08:39:28] "POST /upload-music-file HTTP/1.1" 200 7266 dict_keys([]) [01/May/2020 08:41:13] "POST /upload-music-file HTTP/1.1" 200 7266 [01/May/2020 08:41:13] "GET /static/js/upload_file.js?v=1.0.1 HTTP/1.1" 304 0 which means either the form didn't send it or Django CBV implementation I have isn't the right way to find the file. -
Django foreignKey that doesn't use model's primary key to match to foreign object's primary key?
Lets say I have two models that look like this: ModelA uuid (primary key) id ModelB id (primary key) size I want to add a field to ModelA. I want this field to be a ForeignKey that joins on ModelA.id == ModelB.id. I've searched all throughout the Django Docs and have only found how to change the foreign object's field used in the join, but I haven't found a way to change "this" object's field used in the join. Is it possible to specify a non primary key field from "this" object that is used to create a foreign key by being joined on a matching primary key from the foreign object? -
Working pagination with filters inside URL
My pagination in HTML template looks like that: {% if items.has_other_pages %} <nav aria-label="Page navigation example"> <ul class="pagination justify-content-center"> {% if items.has_previous %} <li class="page-item"><a class="page-link" href="?page={{ items.previous_page_number }}">&laquo;</a> </li> {% else %} <li class="page-item disabled"><a class="page-link" href="#"><span>&laquo;</span></a></li> {% endif %} {% for i in items.paginator.page_range %} {% if items.number == i %} <li class="page-item active"><a class="page-link" href="#">{{ i }} <span class="sr-only">(current)</span></a></li> {% else %} <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if items.has_next %} <li class="page-item"><a class="page-link" href="?page={{ items.next_page_number }}">&raquo;</a></li> {% else %} <li class="page-item disabled"><a class="page-link" href="#"><span>&raquo;</span></a></li> {% endif %} </ul> </nav> {% endif %} When I enter my page my url looks like this: http://localhost:8000/bikes/all , when I use pagination without filters it looks like this http://localhost:8000/bikes/all?page=2. When I use my filters URL looks like this: http://localhost:8000/bikes/all?q=&price_from=&price_to=&cat=Gravel+Bike&bra=&size=&lab= , but when I try to use pagination with the filters, the URL goes back to http://localhost:8000/bikes/all?page=2. Any idea how to fix it so it would keep the filters on inside URL? -
How to link form content with a model?
I have a group of patients. I also have a group of locations. In each patient's DetailView page, I want the user to be able to view the patient information and also link particular locations to the patient. I created a form, so the user can choose a location from a dropdown menu and then enter date, etc.. to the rest of the form. I want to be able to connect this information to the page of the current patient the user is at. forms.py class PastLocationForm(forms.Form): locations = forms.ModelChoiceField(queryset=Location.objects.all().order_by('location_name')) date_from = forms.DateField(input_formats=settings.DATE_INPUT_FORMATS) date_to = forms.DateField(input_formats=settings.DATE_INPUT_FORMATS) category = forms.CharField(max_length=20) views.py class PatientDetailView(DetailView, FormMixin): model=Patient form_class = PastLocationForm def get_success_url(self): return reverse('patient_detail', kwargs={'pk': self.object.pk}) def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): instance = form.save(commit=False) return super().form_valid(form) models.py class Patient(models.Model): name = models.CharField(max_length=200) idn = models.CharField(max_length=200, unique=True) date_of_birth = models.DateField() date_of_confirm = models.DateField() case_number = models.IntegerField() def get_absolute_url(self): return reverse("patient_detail", kwargs={'pk':self.pk}) def __str__(self): return self.name class Location(models.Model): patient = models.ForeignKey(Patient, related_name='locations', on_delete=models.CASCADE, null=True, blank=True) location_name = models.CharField(max_length=50, null=True, blank=True) address = models.CharField(max_length=300, null=True, blank=True) district = models.CharField(max_length=300, null=True, blank=True) grid_x = models.IntegerField(null=True, blank=True) … -
Django custom url pattern
Can i generate custom url pattern like this with or without restframework www.domain.com/sample,175,Skoda_Superb,_2000_Km,_Polski_Salon Here 175 is mysql index id. Skoda_Superb is a category model. _2000_km attribute comes from 175 index. _Polski_Salon is a subcategory -
How can I run a python 2.7 project with Django 1.8 on ubuntu 18.04 when python 3 is my default amd djamgo 1.11 is installed in my virtualenv?
I need to run a Django project which was originally coded in python 2.7 and Django version 1.8 on my linux system. How do I switch between the different versions of python and run the project through terminal and not through a python IDE. -
extend request time DjangoRestFramework API
I have deployed my djangorestframework project on heroku, but the API has a request time out, how can I extend my API request time?