Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JSON field sometimes contains string, sometimes object
I'm using Django rest framework to validate JSON received from a banking API (webhook) that sends financial transactions. The serializer has been working for a few years now. The merchant field in the JSON would always contain the merchant as a nested object with the merchant's ID, name etc. But now I am sometimes receiving just the merchant's ID as a string and the JSON now fails validation. How do I set up my serializer to allow eith string or object in the merchant field? serializers.py class MerchantSerializer(serializers.Serializer): id = serializers.CharField(required=True, max_length=50) name = serializers.CharField(required=True, max_length=100) atm = serializers.BooleanField(required=False, allow_null=True) address = AddressSerializer(required=False, allow_null=True) logo = serializers.URLField(required=False, allow_null=True, max_length=500, min_length=None, allow_blank=True) class DataSerializer(serializers.Serializer): account_id = serializers.CharField(required=True, max_length=50) amount = serializers.IntegerField(required=True) created = serializers.DateTimeField() currency = serializers.CharField(required=True, max_length=3) description = serializers.CharField(required=True, max_length=250) id = serializers.CharField(required=True, max_length=50) category = serializers.CharField(required=True, max_length=100) decline_reason = serializers.CharField(required=False, allow_null=True, allow_blank=True, max_length=100) merchant = MerchantSerializer(required=False, allow_null=True) counterparty = CounterpartySerializer(required=False, allow_null=True) metadata = MetadataSerializer(required=False, allow_null=True) -
Handling upload of many files in django
Im trying to upload many image files at once to my django website. The images are put into an html form and the post request is sent with all these images (thousands). My problem is that once the images reach my server, the app crashes because too many files are open. I'm not sure how to correctly handle the post request - I'm thinking there must be a way to iterate through all the images and save and close them instead of having them all open at one time. Here is my upload method in views.py: def upload(request): if request.method == 'POST': username = request.user dataset_access = DatasetAccess.objects.get(user=username) dataset_name = request.POST['dataset_name'] if '-' in dataset_name: messages.error(request, 'Invalid Character: \' - \' ') return redirect('upload') if Dataset.objects.all().filter(title=dataset_name): messages.error(request, 'A Dataset by this name already exists!') return redirect('upload') else: notes = request.POST.get("notes") dataset = Dataset.objects.create( title = dataset_name, num_datapoints = 0, owner = username, notes = notes, ) dataset_access.dataset.add(dataset) dataset_access.save() images = request.FILES.getlist('images') dataset.create_datapoints(images,xmls,jsons,username) messages.success(request, "Dataset uploaded successfully!") return redirect('manage', dataset.title) return render(request, 'datasets/upload.html') -
How to configure SSL(HTTPS) Elasticbeanstalk
Hello Im trying to use HTTPS in ELasticBeanstalk, I already Have an SSL Certificate in certificate manager Note: My certificate status in Certificate Manager is "okay" Note: HTTP I can access my aplication I will send the link: my site in http Note: even if I configured the certificate in loadbalancer when I enter my domain it's like my EB aplication it's not being linked dont get any error: I put the SSL certificate in LoadBalancer( I used 2018, any earlier fail to deploy) I get this error on my aplication: Now I will send Prints of my LoadBalancer: Note: I also tried to get my EC2 LoadBalancer and add as a dns in my domain when I try to access it I get the error Bad Gateway 400 -
Upload issue Geonode
I am working on a website based on opensource Geonode. While extending the upload document section - (Hidden field permissions) This field is required. shows up. I didnt touch the geonode code. just added header and footer of personal choice. -
password_reset_confirm.html and password_reser_complete.html in not rendering in django
I have implemented password reset functionality in Django it working fine but when I open account recovery link from the Gmail browser redirects me to Django's built-in password_reset_confirm page I want it to redirect me to my custom password_reset_confirm.html urls.py code app_name="accounts" urlpatterns=[ path('password_reset/',auth_views.PasswordResetView.as_view( template_name='password_reset.html', success_url=reverse_lazy('accounts:password_reset_done')),name='password_reset'), path('password_reset_done/', auth_views.PasswordResetDoneView.as_view(template_name='password_reset_done.html'), name='password_reset_done'), path('password_reset_confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='password_reset_confirm.html',success_url=reverse_lazy('accounts:password_reset_complete')),name='password_reset_confirm.html'), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='password_reset_complete.html'), name='password_reset_complete'), ] I also want to check while entering email into the input field to send the email. if the user's entered email-id does not exist then it should show a message "this email does not exist" -
This was likely an oversight when migrating to django.urls.path()
So hello guys, I am new to this django and i have encountered this type of error enter image description here while this if my url.py from unicodedata import name from django.urls import path from Project.views import viewAppointment, addDiagnosis from . import views app_name = "Project" urlpatterns = [ path('', views.index , name='index'), path('counter', views.counter, name='counter'), path('Register', views.Register, name= 'Register'), path('login', views.login, name='login'), path('logout', views.logout, name = 'logout'), path('post/str:pk', views.post, name = 'post'), path('profile', views.profile, name='profile'), path(r'^appointment/appointment=(?P<appointment_id>[0- 100]+)', viewAppointment, name='appointment'), path(r'^appointment/appointment=(?P<appointment_id>[0- 100]+)/AddDiagnonsis', addDiagnosis, name='AddDiagnosis') ] meanwhile this is my views.py def viewAppointment(request, appointment_id): appointment = Appointment.objects.filter(id=appointment_id) return render(request, 'appointment_form.html', {'Appointment': appointment}) def addDiagnosis(request): return True -
Validate forms.TimeField() in Django
I am quite new in Django world. I was working on forms.TimeField() validation (image below) but can not find solution yet :( Whenever user enters "letters" or extra "number" form field should raise ValidationError(_('Please follow the right format')) like this image below I tried with def clean_max_check_out_time(self): cleaned_data = super().clean() default_check_out_time = cleaned_data['default_check_out_time'] if type(default_check_out_time) is not datetime.time: raise ValidationError(_('Please follow the right format')) return default_check_out_time and def clean_max_check_out_time(self): testtime = '00:00:00' if(default_check_out_time >= testtime): raise ValidationError(_('Please follow the right format')) With these codes when I click submit Button it gives me KeyError How can I fix this. Thank you for your help in advance -
show text as it is entered in input box
I have created a Q&A website in Django I want to print text in the same format as it entered This is the text This is on a new line It should print in this format as it is entered but it prints like this This is the text This is on a new line my forum.html code <div class="card-body cardbody"> <p>{{post.post_content|truncatewords:"10"|linebreaks}}</p>{% if post.post_content|length|get_digit:"-1" > 50 %} <a href="/discussion/{{post.id}}" data-abc="true"><button class="btn btn-light" style="color:blue; font-size: 13px;">Show more </button> </a> {% endif %} </div> please help me to do this -
Is Django unchained, in any way related to the Django framework
I Have not watched the movie Django unchained but I was wondering whether it takes any inspiration from the website creating framework. -
How can i send data to two different column from the same form field?
In my project i am using Django 1.11.10 and postgresql for database. When someone enters data to 'order_id' field i want to send it a item_barcode column whether its first 2 character is letters. How can I do that? models.py from django.db import models class Customer(models.Model): item_barcode = models.TextField(max_length=50,unique=True,null=True) order_id = models.TextField(max_length=50,unique=True,null=True) full_name = models.TextField(max_length=50) company = models.TextField(max_length=60,blank=True) email = models.EmailField(max_length=40) phone_number = models.TextField(max_length=17) note = models.TextField(max_length=256,blank=True) def __str__(self): return self.order_id forms.py class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = ( 'order_id','full_name','company','email', 'phone_number','note') views.py def guaform(request): form = CustomerForm() if request.method == "POST": form = CustomerForm(request.POST) if form.is_valid(): form.save(commit=True) else: HttpResponse("Error from invalid") return render(request,'customer_form.html',{'form':form}) *My database columns is same of the models.py -
Django app with celery, tasks are always "PENDING". How can I fix this bug?
I have following celery settings in settings.py CELERY_BROKER_URL = "amqp://admin:admin2017@localhost" CELERY_IMPORTS = ("web.task",) When I use the form to submit a task to celery I see state is always pending enter image description here the following code is used in models: class AnaysisStatus(models.IntegerChoices): #TODO PENDING = 1 COMPLETED = 2 FAILED = 0 class Analysis(models.Model): STATUS_CHOICES = ((1,"PENDING"),(2,"COMPLETED"),(0,"FAILED")) user = models.ForeignKey(User,on_delete=models.CASCADE) status = models.IntegerField(choices=AnaysisStatus.choices,null= True) created_at = models.DateTimeField(auto_now_add=True,null=True) file = models.FileField(null=True) data = models.JSONField(null=True) I'm very new to celery and django so any help is greatly appreciated. Note: I'm not even sure if I need to install broker locally at this point amqp looks like RabitMQ? If so I plan on deploying this to Google Cloud without having to use google tasks if that is relevant. -
Django: how to filter form field based off of many to many relationship?
Currently, when a user creates a task, they can assign it to all users. I only want them to be able to assign a task based on the members of the project. I feel like the concept I have right now works but I need to replace the ????. projects/models.py class Project(models.Model): name = models.CharField(max_length=200) description = models.TextField() members = models.ManyToManyField(USER_MODEL, related_name="projects") tasks/models.py class Task(models.Model): name = models.CharField(max_length=200) start_date = models.DateTimeField() due_date = models.DateTimeField() is_completed = models.BooleanField(default=False) project = models.ForeignKey( "projects.Project", related_name="tasks", on_delete=models.CASCADE ) assignee = models.ForeignKey( USER_MODEL, null=True, related_name="tasks", on_delete=models.SET_NULL ) tasks/views.py class TaskCreateView(LoginRequiredMixin, CreateView): model = Task template_name = "tasks/create.html" # fields = ["name", "start_date", "due_date", "project", "assignee"] form_class = TaskForm def get_form_kwargs(self): kwargs = super(TaskCreateView, self).get_form_kwargs() kwargs["user"] = self.request.user kwargs["project_members"] = ?????????? return kwargs tasks/forms.py class TaskForm(ModelForm): class Meta: model = Task fields = ["name", "start_date", "due_date", "project", "assignee"] def __init__(self, *args, **kwargs): user = kwargs.pop("user") project_members = kwargs.pop("project_members") super(TaskForm, self).__init__(*args, **kwargs) self.fields["project"].queryset = Project.objects.filter(members=user) self.fields["assignee"].queryset = Project.objects.filter( members=????????? ) -
what is the best way to refresh a page automatically?
I am trying to create a simple movie list app with django.I have two page. One for users nad one for movies' list table.Users can add items to the list on their own page and list should be update after every single request. though I know that i can refresh the list page rapidly I was wondering is there another and better way to do this? -
Setting up a Django web scraper using selenium
I'm a high school teacher trying to build a web scraper for other staff members to use. I want to use Django to build the UI, and then use Selenium to scrape a few password protected sites. I'm not sure how to configure Django and Selenium so that when other teachers use the app, the correct web driver is installed. I guess my question is this: how do I get the Django app to detect what browser other users are using, and then choose the appropriate web driver? Cheers. -
Django: TypeError: expected string or bytes-like object when assigning a datetime object to a DateTimeField
I'm running into a really strange issue with the Django ORM. I have a model with a DateTimeField declared like so: class AvailabilityRecord(models.Model): class Meta: ordering = ['pk'] publication_date = models.DateTimeField(auto_now_add=True) And am assigning a value to publication date like so: avail_record, created = AvailabilityRecord.objects.get_or_create( publication_date=datetime(2015, 10, 9, 23, 55, 59, 342380) ) When I try to do this, I receive the error: File "/opt/homebrew/lib/python3.9/site-packages/django/utils/dateparse.py", line 107, in parse_datetime match = datetime_re.match(value) TypeError: expected string or bytes-like object It appears Django doesn't accept datetime objects for the DateTimeField, which I find strange. Is this actually the case, that I need to convert it to a string every time before assigning a value? I am using Django 3.2.12 -
How can I fix this error "premium is not one of valid choices please select valid choice" from drop down in django?
Context: I was able to set a user to PREMIUM from the admin panel but after resetting the database I see this error. I'm unable to figure out what's going on or how to fix it. The error is: "Select a valid choice. PREMIUM is not one of the available choices". Here is code for my Profile class: class Profile(models.Model): PREMIUM_CHOICES = (("FREE",0),("PREMIUM",1)) user = models.OneToOneField(User,primary_key=True,on_delete=models.CASCADE) premium = models.IntegerField(choices=PREMIUM_CHOICES,default=0) due_date = models.DateField(null=True) I've looked at several answers on Stackoverflow: MongoDB database. Error "Select a valid choice. That choice is not one of the available choices." Here is screen capture of the error: -
I want to place a placeholder in my forms textarea in Django
I want to write a placeholder at the end of the textarea says: '*required'. How can I do this for my fields? forms.py class CustomerForm2(forms.ModelForm): class Meta: model = Customer fields = ( 'order_id','full_name','company','email', 'phone_number','note') } -
Django-filter error: 'Meta.fields' must not contain non-model field names
I am working with Django REST framework and django-filters and and I'd like to use the reverse relationship annotation_set as one of filters for a GET API that uses the model Detection. The models are the following: class Detection(models.Model): image = models.ImageField(upload_to="detections/images") def local_image_path(self): return os.path.join('images' f"{self.id}.jpg") class Annotation(models.Model): detection = models.ForeignKey(Detection, on_delete=models.CASCADE) attribute = models.CharField(max_length=255) The serializer is: class DetectionSerializer(UniqueFieldsMixin, serializers.ModelSerializer): local_image_path = serializers.CharField() class Meta: model = Detection fields = '__all__' And the viewset is: class DetectionTrainingViewSet( mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet ): queryset = Detection.objects.all() serializer_class = DetectionSerializer filterset_fields = ('annotation_set__id', ) @action(methods=['GET'], detail=False) def list_ids(self, request): queryset = self.get_queryset() filtered_queryset = self.filter_queryset(queryset) return Response(filtered_queryset.values_list('id', flat=True)) When I make a call to the endpoint, I get the error: 'Meta.fields' must not contain non-model field names: annotation_set__id Shouldn't the field exist? Note: I tried to add other fields to the Annotation model and then use annotation_set__newfield but I still have the error. I can confirm that the newfield exists because it is correctly serialized and return by the API when I comment out the line that set the filterset_fields. -
Django server not starting after importing python project as package
I have a deep learning python project named 'predict'. I want to use it in my django views so I use from predict.Prediction import Prediction where predict = root directory of python project, Prediction.py is the file that I need to use. Whenever I run python manage.py runserver, I get the error as: Server not starting issue. I have the init file in the root folder predict (python project) structure. I am stuck on this from long and clueless as to what is the issue. -
CSS grid using DIVs that works on local server not wotking when uploded to Django site
I am trying to create a CSS grid using DIVs to display a row of 3 boxes. <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> html { font-size: 22px; } body { padding: 1rem; background-color: rgba(2, 26, 63); } .card { background-color: rgba(24,109,238, 0.7); transition: 0.5s; border-radius: 10px; color: white; padding: 1rem; height: 4rem; } .card:hover{ box-shadow: 0 0 20px 0px rgba(80, 230, 236, 0.8); } .card h3{ text-align: center; } .cards { max-width: 800px; margin: 0 auto; display: grid; grid-gap: 1rem; font-size: small; } /* Screen larger than 600px? 2 column */ @media (min-width: 600px) { .cards { grid-template-columns: repeat(2, 1fr); } } /* Screen larger than 900px? 3 columns */ @media (min-width: 900px) { .cards { grid-template-columns: repeat(3, 1fr); } } </style> </head> <body> <Div class="cards"> <Div class="card" onclick="window.location='opnotener'"> <h3>NLP-NER 4 Op Notes</h3> <P>Natural Lanugage Processing - Named Entity Rrecognition tool for surgical Procedure Notes.</P> </Div> <Div class="card" onclick="window.location='#'"> <h3>Surgical EPR</h3> <P>Surgical EPR that covers the entire surgical landscape with sub-speciality pipeleines.</P> </Div> <Div class="card" onclick="window.location='opnoteannotator'"> <h3>Op Note Annotator</h3> <P>Surgical procedure notes Annotator with drag and drop speciality specific entities.</P> </Div> </Div> </body> </html> The intended output should be like below and … -
Using custom font in django Css
I'm trying to use a custom font in my Django app. Here are the relevant lines from my base.html: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'recipebook/style.css' %}"> Here are my relevant lines from the css file: @font-face { font-family: "FiraCode-Retina"; src: url("fonts/FiraCode-Retina.ttf") format("truetype"); } Here is my file structure: My CSS is working except for the font. What steps am I missing to get this working? -
QuerySet basic methods typing
Lets say i have a model Event, i want Event.objects.filter(blablabla) to return a QuerySet[Event], not just a QuerySet. For this purpouse, i created a Manager. I need the manager in a separate file, since i have many Managers. So an ideal thing to do would be something like class EventManager(models.Manager): def filter(self, *args, **kwargs) -> QuerySet[Event]: return super().filter(*args, **kwargs) But i can't import the Event model, since it would be a circular import (Event.objects is the EventManager). How can i provide type hints for the filter and get functions?. -
Django Jinja template display value from dictionary key
I have problem to display data in jinja template. I have a dictionary which looks like: data = { 'Game1': {'win': 0, 'lost': 2, 'all': 2}, 'Game2': {'win': 1, 'lost': 0, 'all': 1}, 'Game3': {'win': 2, 'lost': 0, 'all': 2} } This dictionary is passed to template as game_details. I want to display this data like: Game: Game1 Win: 0 Lost: 2 All: 2 Game: Game2 Win: 1 Lost: 0 All: 1 Game: Game3 Win: 2 Lost: 0 All: 2 Using python there is no problem, because I can call data by key, but in my template I'm trying to call them like: {% for key, value in game_details.items %} Game: {{ key }}<br/> Win: {{ value['win'] }} {% endfor %} which leads to TemplateSyntaxError. Could not parse the remainder: '['win']' from 'value['win']'. How can I call a specific value from dictionary using key in jinja template? -
I need to Ctrl-C/Pause after every manage.py command in Django
No, I'm not talking about runserver listening for requests. Whenever i run makemigrations, migrate or scripts i wrote using django-extensions command runscript, I need to stop the execution of the program before typing in another. This was not the case before restarting my PC this morning. I'm building a small QR code ticketing app and it was working up until this morning. I fixed a bug regarding opencv since and the app is functional again, but this command line issue is bothering me. I'm going to have to make the /admin and scripts available to a few of my colleagues tomorrow and i'm afraid we won't know when the script running is actually done since it doesn't prompt or allow another command. Having a script executed terminated early because of this would be catastrophic. Any help would be appreciated urgently! whenever i run a command, the blank line not accepting input appears -
Failed to build backports.zoneinfo
in terminal I run command docker build ., but dockerfile fail to install. Building wheel for backports.zoneinfo (pyproject.toml): finished with status 'error' error: subprocess-exited-with-error × Building wheel for backports.zoneinfo (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [35 lines of output] running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-cpython-38 creating build/lib.linux-x86_64-cpython-38/backports copying src/backports/__init__.py -> build/lib.linux-x86_64-cpython-38/backports creating build/lib.linux-x86_64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/__init__.py -> build/lib.linux-x86_64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_zoneinfo.py -> build/lib.linux-x86_64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_common.py -> build/lib.linux-x86_64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_version.py -> build/lib.linux-x86_64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_tzpath.py -> build/lib.linux-x86_64-cpython-38/backports/zoneinfo running egg_info writing src/backports.zoneinfo.egg-info/PKG-INFO writing dependency_links to src/backports.zoneinfo.egg-info/dependency_links.txt writing requirements to src/backports.zoneinfo.egg-info/requires.txt writing top-level names to src/backports.zoneinfo.egg-info/top_level.txt reading manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' warning: no files found matching '*.png' under directory 'docs' warning: no files found matching '*.svg' under directory 'docs' no previously-included directories found matching 'docs/_build' no previously-included directories found matching 'docs/_output' adding license file 'LICENSE' adding license file 'licenses/LICENSE_APACHE' writing manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt' copying src/backports/zoneinfo/__init__.pyi -> build/lib.linux-x86_64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/py.typed -> build/lib.linux-x86_64-cpython-38/backports/zoneinfo running build_ext building 'backports.zoneinfo._czoneinfo' extension creating build/temp.linux-x86_64-cpython-38 creating build/temp.linux-x86_64-cpython-38/lib gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -DTHREAD_STACK_SIZE=0x100000 -fPIC -I/usr/local/include/python3.8 -c lib/zoneinfo_module.c -o build/temp.linux-x86_64-cpython-38/lib/zoneinfo_module.o -std=c99 error: command 'gcc' failed: No such file or directory [end of output] note: This error originates from a subprocess, …