Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku Internal Server Error on Django Application with ModuleNotFoundError: No module named '_tkinter' in logs
I am currently trying to deploy a django project via Heroku, but the app is displaying an Internal Server Error. Checked the logs by running heroku logs -tail <app-name> which I am assuming that the following error is causing the errror: ModuleNotFoundError: No module named '_tkinter' I've tried a different stackoverflow solution, but did not have any luck with it. Here are the following steps: pipenv install matplotlib Added the following in my models.py (even tried in settings.py) import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt Heroku Logs 2022-04-06T01:50:43.361025+00:00 app[web.1]: File "/app/config/urls.py", line 26, in <module> 2022-04-06T01:50:43.361025+00:00 app[web.1]: path('', include('users.urls')), 2022-04-06T01:50:43.361025+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/urls/conf.py", line 38, in include 2022-04-06T01:50:43.361025+00:00 app[web.1]: urlconf_module = import_module(urlconf_module) 2022-04-06T01:50:43.361026+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/importlib/__init__.py", line 126, in import_module 2022-04-06T01:50:43.361028+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2022-04-06T01:50:43.361028+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1050, in _gcd_import 2022-04-06T01:50:43.361028+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1027, in _find_and_load 2022-04-06T01:50:43.361029+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked 2022-04-06T01:50:43.361029+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 688, in _load_unlocked 2022-04-06T01:50:43.361029+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 883, in exec_module 2022-04-06T01:50:43.361029+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed 2022-04-06T01:50:43.361030+00:00 app[web.1]: File "/app/users/urls.py", line 2, in <module> 2022-04-06T01:50:43.361030+00:00 app[web.1]: from . import views 2022-04-06T01:50:43.361030+00:00 app[web.1]: File "/app/users/views.py", line 9, … -
How to simplify redundant code in Django queryset
I want to graph the number of client registrations per month/employee for this year. The code below is used to get the desired queryset, but there are many overlapping parts in annotations, so I want to minimize this code. Also, there is a hassle of having to change the year every time the year changes, so I hope this problem will also be resolved. (* For reference, the x-axis is "month" and the y-axis is "the employee name" (uploader_id__first_name )) [views.py] monthly_enroll = Feedback.objects\ .values('uploader_id__first_name').distinct().order_by('uploader_id__first_name')\ .annotate(jan=Count('client_id', filter=Q(enroll_date__gte='2022-01-01', enroll_date__lte='2022-01-31')), feb=Count('client_id', filter=Q(enroll_date__gte='2022-02-01', enroll_date__lte='2022-02-28')), mar=Count('client_id', filter=Q(enroll_date__gte='2022-03-01', enroll_date__lte='2022-03-31')), apr=Count('client_id', filter=Q(enroll_date__gte='2022-04-01', enroll_date__lte='2022-04-30')), may=Count('client_id', filter=Q(enroll_date__gte='2022-05-01', enroll_date__lte='2022-05-31')), jun=Count('client_id', filter=Q(enroll_date__gte='2022-06-01', enroll_date__lte='2022-06-30')), jul=Count('client_id', filter=Q(enroll_date__gte='2022-07-01', enroll_date__lte='2022-07-31')), aug=Count('client_id', filter=Q(enroll_date__gte='2022-08-01', enroll_date__lte='2022-08-31')), sept=Count('client_id', filter=Q(enroll_date__gte='2022-09-01', enroll_date__lte='2022-09-30')), oct=Count('client_id', filter=Q(enroll_date__gte='2022-10-01', enroll_date__lte='2022-10-31')), nov=Count('client_id', filter=Q(enroll_date__gte='2022-11-01', enroll_date__lte='2022-11-30')), dec=Count('client_id', filter=Q(enroll_date__gte='2022-12-01', enroll_date__lte='2022-12-31')),)\ .values_list('uploader_id__first_name', 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sept', 'oct','nov', 'dec')\ .order_by('uploader_id__first_name') -
External API Calls making django view slow
I am working with django.I have a problem pretty much like this question: Render slow loading results. However I am unable to resolve this. Problem is that I am making nearly 10-15 external api calls which is making rendering of template way too slow. I can't reduce that because that extenal API is my only source of data. What i want to do is to load template and then fetch the data from the extenal api. I think this is the best approach as users will have something to do while data is being fetched. Also i couldn't find a proper guide to implement this mechanism. Any help will be appreciated. -
File Inside Python Module Not Included (Django, Py2 to Py3 Conversion)
I am migrating a Django project from 2 to 3 and am running into an import(?) error. One of the apps/modules contains an __init__.py, admin.py, forms.py, models.py, urls.py, and view.py, but when the module is imported only admin, forms, and models are a part of it. A dir of the module looks like this: ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'admin', 'forms', 'models'] If I try something like from . import views, I get a SyntaxError. -
How can I connect to docker db from local django?
How can I connect to docker db from local django? version: '3' services: redis-1: container_name: redis1 build: ./docker/redis environment: X_REDIS_PORT: 7001 networks: redisnet: ipv4_address: 10.0.0.11 ports: - 7001:7001 redis-2: container_name: redis2 build: ./docker/redis environment: X_REDIS_PORT: 7002 networks: redisnet: ipv4_address: 10.0.0.12 ports: - 7002:7002 redis-3: container_name: redis3 build: ./docker/redis environment: X_REDIS_PORT: 7003 networks: redisnet: ipv4_address: 10.0.0.13 ports: - 7003:7003 redis-4: container_name: redis4 build: ./docker/redis environment: X_REDIS_PORT: 7004 networks: redisnet: ipv4_address: 10.0.0.14 ports: - 7004:7004 redis-5: container_name: redis5 build: ./docker/redis environment: X_REDIS_PORT: 7005 networks: redisnet: ipv4_address: 10.0.0.15 ports: - 7005:7005 redis-6: container_name: redis6 build: ./docker/redis environment: X_REDIS_PORT: 7006 networks: redisnet: ipv4_address: 10.0.0.16 ports: - 7006:7006 redis-cluster: container_name: redis-cluster image: redis:latest command: redis-cli -p 7001 --cluster create 10.0.0.11:7001 10.0.0.12:7002 10.0.0.13:7003 10.0.0.14:7004 10.0.0.15:7005 10.0.0.16:7006 --cluster-replicas 1 --cluster-yes depends_on: - redis-1 - redis-2 - redis-3 - redis-4 - redis-5 - redis-6 networks: redisnet: ipv4_address: 10.0.0.2 predixy: container_name: predixy build: ./docker/predixy depends_on: - redis-1 - redis-2 - redis-3 - redis-4 - redis-5 - redis-6 ports: - 7617:7617 volumes: - ./docker/predixy/conf:/etc/predixy/conf networks: redisnet: ipv4_address: 10.0.0.3 networks: redisnet: driver: bridge ipam: driver: default config: - subnet: 10.0.0.0/16 This is my docker-compose.yml file and I would like to connect the predixy (cluster proxy) floated on port 7617 with django … -
IntegrityError at /forum/post/15/comment/new/: NOT NULL constraint failed: forum_comment.name_id
I'm trying to implement a commenting feature for my blog style project, but I'm getting the following error: IntegrityError at /forum/post/15/comment/new/ NOT NULL constraint failed: forum_comment.name_id I suspect that the error has something to do with the comment author because I was reading similar posts where that was the problem, however I wasn't able to fully comprehend or adapt their problem onto mine because of the way I have setup my comments. Here's how my project setup looks: models.py: class Post(models.Model): titulo = models.CharField(max_length=150) contenido = MarkdownxField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def formatted(self): return markdownify(self.contenido) def __str__(self): return self.titulo def get_absolute_url(self): return reverse("post-detail", kwargs={"pk": self.pk}) class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) name = models.ForeignKey(User, on_delete=models.CASCADE) body = MarkdownxField() date_added = models.DateTimeField(default=timezone.now) def __str__(self): return '%s - %s' % (self.post.titulo, self.name) views.py: class CommentCreateView(CreateView): model = Comment form_class = CommentForm #fields = ['body'] template_name = "forum/comment_form.html" class Meta: ordering=['-time'] def form_valid(self, form): form.instance.post = Post.objects.get(pk=int(self.kwargs['pk'])) return super().form_valid(form) def get_success_url(self): return reverse_lazy('') forms.py: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['body'] widgets = { 'body': MarkdownxField() } urls.py: path('post/<int:pk>/comment/new/', CommentCreateView.as_view(), name='comment-create'), Any kind of help would be greatly appreciated, thanks in advance... -
React Native File Upload not working using Axios
I am trying to upload a file to the server and the server APIs are written using django. The file upload is working perfectly from Postman but when i try to upload from mobile app (React Native) using axios the backend is not able to read it. Following is the Frontend Snippet: let accessToken = await AsyncStorage.getItem('accessToken') let formData = new FormData() formData.append('doc_type', this.state.selectedDoc.id) formData.append('document', this.state.selectedFiles) // <- This is the fetched file in array format . [{filname:'abc', size:12344,.....}] formData.append('description', this.state.description.value) formData.append('data', JSON.stringify(this.state.selectedDoc.fields)) let url = `${AppConstants.url}api/${AppConstants.apiVersion}/upload_doc` var config = { method: 'post', url: url, data: formData, headers: { 'Authorization': `Bearer ${accessToken}`, } } axios(config) .then((resp) => { resolve(resp) }) .catch((err) => { reject(err) }); And the backend-end if else statement is as follows: if(request.FILES.getlist("document")): files = request.FILES.getlist("document") .... .... .... else: return response.JsonResponse({ 'success' : False, 'message' : 'Please Upload a file' }, status = status.HTTP_200_OK) The above else block is executed even though the UI is sending a valid file. Request you to please share a solution. -
Annotate GIS Intersection in Nested Subquery
I am trying to execute a complex Django query involving a nested subquery. Starting with the Stick model, I want to annotate the ownership_pct from the StickOwnership model (which is straightforward given the FK relationship). Next, I also want to annotate the ownership_pct from the BoxOwnership model such that the associated Box has the maximum overlap with the Stick. For reference, here are the models: Stick: lateral_line_string = models.LineStringField() Box: polygon = models.MultiPolygonField() BoxOwnership: box = auto_prefetch.ForeignKey("Box") owner = auto_prefetch.ForeignKey("Owner") ownership_pct = DecimalField StickOwnership: stick= auto_prefetch.ForeignKey("Stick") owner = auto_prefetch.ForeignKey("Owner") ownership_pct = DecimalField Here is what I have written so far: sticks = Sticks.objects.all() # starting queryset is arbitrary owner_in_question = Owner.objects.first() # owner is arbitrary stick_ownership_subquery = StickOwnership.objects.filter(stick=OuterRef('pk'),owner=owner_in_question).only('ownership_pct') box_subquery = box.objects.filter(polygon__intersects=OuterRef(OuterRef('lateral_line_string'))).annotate(length=Length(Intersection(OuterRef(OuterRef('lateral_line_string')), F('polygon')))).order_by('-length').only('pk') box_ownership_subquery = BoxOwnership.objects.filter(box=Subquery(box_subquery.first().pk), owner=owner_in_question).only('ownership_pct') sticks = sticks.annotate(stick_ownership=Subquery(stick_ownership_subquery.values('ownership_pct'))).annotate(box_ownership=Subquery(box_ownership_subquery.values('ownership_pct'))) The box_subquery is throwing this error: Traceback (most recent call last): File "venv/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 3251, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-8-0b4d9b715187>", line 1, in <module> box_subquery = Box.objects.filter(polygon__intersects=OuterRef(OuterRef('lateral_line_string'))).annotate(length=Length(Intersection(OuterRef(OuterRef('lateral_line_string')), F('polygon')))) File "venv/lib/python3.10/site-packages/django/db/models/query.py", line 1225, in annotate return self._annotate(args, kwargs, select=True) File "venv/lib/python3.10/site-packages/django/db/models/query.py", line 1273, in _annotate clone.query.add_annotation( File "venv/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1074, in add_annotation annotation = annotation.resolve_expression( File "venv/lib/python3.10/site-packages/django/contrib/gis/db/models/functions.py", line 71, in resolve_expression res = super().resolve_expression(*args, **kwargs) File "venv/lib/python3.10/site-packages/django/db/models/expressions.py", line 762, in … -
ValueError: Cannot assign "15": "Comment.post" must be a "Post" instance
I'm trying to setup a comment system for my posts in a project that I've been working on for the past couple of months, and I'm getting the following error when trying to use the post_id (the number or pk) to identify the post that the comment is being made on: ValueError at /forum/post/15/comment/new/ Cannot assign "15": "Comment.post" must be a "Post" instance. This is how I have setup the comments: models.py: class Post(models.Model): titulo = models.CharField(max_length=150) contenido = MarkdownxField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def formatted(self): return markdownify(self.contenido) def __str__(self): return self.titulo def get_absolute_url(self): return reverse("post-detail", kwargs={"pk": self.pk}) class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) name = models.ForeignKey(User, on_delete=models.CASCADE) body = MarkdownxField() date_added = models.DateTimeField(default=timezone.now) def __str__(self): return '%s - %s' % (self.post.titulo, self.name) views.py: class CommentCreateView(CreateView): model = Comment form_class = CommentForm #fields = ['body'] template_name = "forum/comment_form.html" def get_post_id(request, post_id): post=Post.objects.get(id=post_id) class Meta: ordering=['-time'] def form_valid(self, form): form.instance.post = self.kwargs['pk'] return super().form_valid(form) def get_success_url(self): return reverse_lazy('') forms.py: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['body'] widgets = { 'body': MarkdownxField() } urls.py: path('post/<int:pk>/comment/new/', CommentCreateView.as_view(), name='comment-create'), Any help is greatly appreciated. Thanks in advance. -
Python: How can I change the title of a page in Django based on variable?
I am working with a Django app which uses the same template for different 'pages'--basically, the page can either be a "Create Entry" page or an "Edit Entry" page. The page changes based on the following parameters: {% if props.data.id %} Edit {% else %} Create {% endif %} The logic being: if an id exists for this entry, the page will display as a Edit page. Otherwise, the page will display as a Create page. I would like the title of the page to change depending on the same parameters. So the two versions of the page should be: Create Entry Edit Entry Here's the code I'm currently trying: {% if props.data.id %} {% with action='Edit' %} {% endwith %} {% else %} {% with action='Create' %} {% endwith %} {% endif %} {% block title %} {{ action }} Entry {% endblock %} I haven't gotten this to work yet. Am I on the right track? I was using 'with' since that seems to be the recommended way to set variables in Django, but I'm wondering if there's a better way to do this. -
Web-sockets & Django
This is a table of posts, I want to update status(red highlighted) when ever a user comment on a post. I used websockets to show realtime comments on the page(if tab is open comment will show without page refresh). But if user post a comment I want to update this status in real time. enter image description here Kindly help me if you know anything. -
Refresh webpage on database change (Django)
First of all, I am a beginner in web dev so excuse me if this seems vague/weird. I am making a werewolf-based browser multiplayer game, and I would like to refresh the datas on front-end whenever an user makes a move. I was thinking about a channel layer, but I would like to know if this was possible to do without, I don't need users to communicate between each other, simply a connection client/server where the webpage/content refresh whenever a data is being added/removed/modified within the database. And channel layers seems complicated for a beginner such as me Thanks for the help ! -
CSS showing on local computer, but not on Heroku (Python, Django)
I have built a website using both bootstrap styling, and also a stylesheet for other changes I wish to make along the way. I have it displaying a certain way on my local machine, but I can't get it refelected on my site. Is there something that I need to add to my settings.py file to know that it should read the static css file? Here is my html file for this one: {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title> Insure Need </title> {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> </head> <body> <nav class="navbar navbar-expand-md navbar-light bg-light mb-4 border"> <a class="navbar-brand" href="{% url 'website:welcome' %}">InsureNeed</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span></button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="{% url 'website:insureNeeds' %}">InsureNeed</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'website:learn' %}">Learn</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'website:contact' %}">Contact</a> </li> </ul> </div> </nav> <main role="main" class="container"> <div class="pb-2 mb-2 border-bottom"> {% block page_header %}{% endblock page_header %} </div> <div> {% block content %}{% endblock content %} </div> </main> <!--{% include 'website/footer.html' %}--> </body> … -
Dockerfile - activate Python virtualvenv - ubuntu
I am trying to create an Docker Image that contains an Apache Webserver with Django. I am using virtual environments in my production environment and I don't know how to activate it in a Dockerfile. This is my Dockerfile: FROM ubuntu/apache ARG GITLAB_USERNAME ARG GITLAB_TOKEN RUN apt-get update RUN apt-get upgrade -y RUN apt-get install -y python3 python3-pip apache2 libapache2-mod-wsgi-py3 libpq-dev git RUN pip3 install virtualenv RUN mkdir -p /var/www WORKDIR "/var/www" RUN git clone https://${GITLAB_USERNAME}:${GITLAB_TOKEN}@gitlab.com/g5362/gnsave.git RUN mv gnsave/Netto\ umgeschrieben/ ./GNSave RUN rm -r gnsave WORKDIR "/GNSave/" RUN virtualenv gnsave RUN source gnsave/bin/activate && pip install -r requirements.txt RUN a2enmod wsgi RUN chown -R www-data:www-data /var/www/GNSave RUN chmod -R u+w /var/www/GNSave RUN chmod -R 775 /var/www/GNSave/assets COPY django.conf /etc/apache2/sites-available/django.conf RUN a2dissite 000-default RUN a2ensite django RUN /etc/init.d/apache2 restart The error messae I get is: /bin/sh: 1: source: not found My question is if I should split the django and apache into two dockers and compose them or if there is a workaround for activation venvs in my Dockerfile. Thanks in advance! -
pymongo fails with error 'sys' is not defined
I have a Django app that queries mongodb. requirements.txt: # other dependencies pymongo==4.1.0 View: client = pymongo.MongoClient("mongodb+srv://*****@****.mongodb.net/test_db?retryWrites=true&w=majority") When this line is executed, the Django server throws the following error: venv/lib/python3.9/site-packages/pymongo/uri_parser.py, line 467, in parse_uri Exception: name 'sys' is not defined How do I fix this error? I'm on Python3.9 and latest Django. -
Is a good pratice use React as OAuth authorization screen?
I has my application using react to frontend and django as backend server, I need to implement an oauth provider in my backend. I want to know if is a good pratice use react to show the authorization screen of the oauth. Should I use django rest framework to provide oauth endpoints, to list the scopes with react forwarding the client secret to the API? -
Difference between two multiple arrays by the index in PYTHON
Hi guys i just start to programming and im trying to get this right. A = [['1','Jack','33'], ['2','Maria','23'], ['3','Christian','9'] ] B = [['1','Jack','33'], ['2','Maria','23'], ['3','Christian','9'], ['4','Denis','45'] ] I want to check the array B[0] and print out just "4 Denis 45" -
How to convert class type to string python SDK
I have this code that prints information related to VM. The output is in the class type. How can I convert it to a form so that I can understand it? from azure.common.credentials import ServicePrincipalCredentials from azure.mgmt.compute import ComputeManagementClient credential = ServicePrincipalCredentials(client_id='XXXX', secret='XXXX', tenant='XXXX') compute_client = ComputeManagementClient( credential, 'XXXX') for vm in compute_client.virtual_machines.list_all(): print(vm.storage_profile) I am getting output in the form. It is showing the class type of this output <'azure.mgmt.compute.v2019_03_01.models.storage_profile_py3.StorageProfile'> -
How can I use low-level caching in Django ListView CBV?
I know how to use low-level caching in base generic view (from django.views.generic import View) CBV! but I don't know where to use low-level caching in ListView CBV in django! I mean should I use it in get_queryset() function or get_object() and so on? Please share if you have any experience and do not rate it negatively because I could not find it anywhere! -
query from multi table in django
i have 3 tables class list_c (models.Model): list_name=models.CharField(max_length=50,verbose_name="",blank=True) def __str__(self): return self.list_name class Meta: verbose_name = '' verbose_name_plural = '' class candidate (models.Model): can_name = models.CharField(max_length=60, verbose_name='') can_da2ira = models.ForeignKey(da2ira,on_delete=models.CASCADE,verbose_name='') can_list = models.ForeignKey(list_c,on_delete=models.CASCADE,verbose_name="",related_name='list') def __str__(self): return self.can_name class Meta: verbose_name = '' verbose_name_plural = '' class result (models.Model): r_can = models.ForeignKey(candidate,on_delete=models.CASCADE,verbose_name="", related_name='can') r_iktira3 = models.ForeignKey(kalam_iktira3,on_delete=models.CASCADE,verbose_name="",related_name='qalam') r_result = models.IntegerField(verbose_name="") i have Django 4 project with 3 models and view how can get this : i need to get in template table (can_name ,list_name,sum(r_result ) -
Create Quiz in Django
My needs is to create a Quiz in Django and for now i'm starting with Admin section. models.py: class Answer(models.Model): objects = None answer = models.CharField(max_length=200, null=False) answer_pic = models.ImageField(upload_to='poll', storage=fs) def __str__(self): return self.answer class Question(models.Model): objects = None question = models.CharField(max_length=200, null=False) description = models.CharField(max_length=255, null=True) question_pic = models.ImageField(upload_to='poll/', storage=fs, null=True) choices = models.ManyToManyField(Answer, related_name='QuestionsChoices') correct = models.ManyToManyField(Answer, related_name='QuestionsCorrect') mandatory = models.BooleanField(default=True) multiple = models.BooleanField(default=False) randomize = models.BooleanField(default=False) def __str__(self): return self.question class Quiz(models.Model): objects = None STATUS_CHOICES = ( (1, 'Draft'), (2, 'Public'), (3, 'Close'), ) nom = models.CharField(max_length=200, null=False) questions = models.ManyToManyField(Question, related_name='Quizs') status = models.IntegerField(choices=STATUS_CHOICES, default=1) published = models.DateTimeField() date_added = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now_add=True) def __str__(self): return self.nom forms.py class QuestionForm(forms.ModelForm): question = forms.CharField( widget=forms.TextInput(attrs={'size': 20, 'class': 'form-control'}), label="Question :", required=True, help_text='Intitulé de la question', ) description = forms.CharField( widget=forms.Textarea(attrs={'rows': 2, 'cols': 40, 'class': 'form-control'}), label="Description :", required=True, help_text='Description de la question (obligatoire)', ) question_pic = forms.ImageField( label="Illustration : ", widget=forms.FileInput(attrs={'class': 'form-control'}), required=False, help_text='Choisir une illustration', ) mandatory = forms.BooleanField( label="Réponse obligatoire ?", initial=False, required=False, help_text='Question obligatoire ou pas ?', ) multiple = forms.BooleanField( label="Plusieurs réponses possible ?", initial=False, required=False, help_text='Plusieurs réponses possible ?', ) randomize = forms.BooleanField( label="Affichage aléatoire des réponses ?", initial=False, … -
Is there a way to control the messages after redirect or even clear messages?
Is there a way for me to stop the other validations after the first redirect in views.py from django.contrib import messages # from django.core.exceptions import ValidationError from django.shortcuts import render, redirect def register(request): if request.method == 'POST': form = request.POST phone_number = validate_phone(request, form.get("phone_number")) username = validate_user_name(request, form.get("username")) password = validate_password(request, password1=form.get("password1"),password2=form.get("password2")) ....other_fields.... return render(request, 'registration.html',) def validate_user_name(request, username): username = username.strip() new = MyUser.objects.filter(username=username) if new.count(): messages.error(request, "User with that Username Already Exist") return redirect("pre_register") # raise ValidationError("User with that Username Already Exist", code="username_error") return username def validate_password(request, password1, password2): if password1 and password2 and password1 != password2: messages.error(request, "Passwords don't match") return redirect("pre_register") # raise ValidationError("Password don't match") return password2 ....other_validations.... in registration.html: <h3 class="register-heading">Apply as a Member</h3> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message.tags }} : {{message}}</li> {% endfor %} <form method="post"> <input type="text" class="form-control" placeholder="Username *" value="" required="required" name="username"/> <input type="text" minlength="10" maxlength="10" name="phone_number" class="form-control" placeholder="Your Phone *" value="" required="required"/> <input type="password" class="form-control" placeholder="Password *" value="" required="required" , name="password1"/> <input type="password" class="form-control" placeholder="Confirm Password *" value="" required="required" , name="password2"/> </form> Let's say a user enters a username that already exists, what I want is: To keep the … -
How to dynamically change name of html button using javascript as soon as page loads
Is it possible to change the words displayed on button using javascript? Im trying to change the words Day 1, Day 2, and Day 3 on the buttons to the current date and next 2 days, (Day 1-> 4/05, Day 2 -> 4/06, Day 3 -> 4/07) In my views I'm passing some queries as context #appointmentApp.views time_selector_view(request): #list of the next 2 dates day = datetime.datetime.now() dates.append(day) while (i < 3): day = day datetime.timedelta(days = 1) dates.append(day) i += 1 #3 queries for each date in the list timeslots = Timeslots.objects.filter(date_sel=dates[0].date()) timeslots2 = Timeslots.objects.filter(date_sel=dates[1].date()) timeslots3 = Timeslots.objects.filter(date_sel=dates[2].date()) #I want each time slot query to have its own tab context = { 'dates' : dates, 'time_slots1' : timeslots, 'time_slots2' : timeslots2, 'time_slots3' : timeslots3 } return render(request, appointment_template/time_selector.html, context) my html page <!-- want to change the words displayed on the buttons --> <!-- appointment_template/time_selector.html --> {% extends "base.html" %} {% block content %} <body> <!-- Is it possible to change the words displayed on the buttons, Day 1 Day 2 and Day 3 using javascript?--> <div class="time_slot_tabs"> <button class="time_slot_tab_button" onclick="openCity(event, 'Day1')" id="defaultOpen">Day 1</button> <button class="time_slot_tab_button" onclick="openCity(event, 'Day2')">Day 2</button> <button class="time_slot_tab_button" onclick="openCity(event, 'Day3')">Day 3</button> </div> <div id="Day1" class="time_slot_tab_content"> {%for … -
null value in column violetes not-null constraint in Django rest-api
I have created API called test_api and trying to send data to using POSTman In my models.py I have a model structured like this class test_API(models.Model): IDnumber = models.IntegerField(unique = True, primary_key = True, null=False, editable = False, blank=True) State = models.CharField(max_length = 256, null = True) Exlcludmethod = models.CharField(max_length=256, null=True) I migrate this to postgresql database and all values in those columns are empty. Then I used postman to send some data to API end point Getting error saying <null value in column "IDnumber" violates not-null constraint DETAIL: Failing row contains (null, CA, remove). > What is the reason for this I searched but could not find a solution why this is happening IntegrityError null value in column "name" of relation "tag" violates not-null constraint null value in column "list_name" violates not-null constraint DETAIL: -
ProgrammingError - relation "blog_app_post" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "blog_app_post"
I have a problem with my database every time I deploy it to heroku. The code works okay on localhost but shows ProgrammingError when deployed. When ever I remove the category from the codes, it seems to work but still having another issue with the auth dashboard. Here is the view.py code class BlogView(ListView): model = Post template_name = 'blog.html' ordering = ['-post_date'] paginate_by = 10 def get_context_data(self, *args, **kwargs): genres_menu = Category.objects.all() context = super(BlogView, self).get_context_data(*args, **kwargs) context["genres_menu"] = genres_menu print(context) return context Here is the model.py code from django.db import models from django.contrib.auth.models import User from django.urls import reverse from datetime import datetime, date from ckeditor.fields import RichTextField class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name def get_absolute_url(self): return reverse('blog') class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) thumbnail = models.ImageField(null=True, blank=True, upload_to="thumb_images/blog_post") snippet = models.CharField(max_length=255, default='This is a default snippet') likes = models.ManyToManyField(User, related_name='blog_posts') def total_likes(self): return self.likes.count() def \__str_\_(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('blog') Here is the url.py code from .views import BlogView urlpatterns = \[ path('blog/', BlogView.as_view(), name='blog'), \] Here is the template code {% if genres_menu %} <div class="widget-area"> <div class="widget-collapse-btn"> …