Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to extend django UserCreationForm model to include phone number field
I cant seem to find any posts here regarding extending the Django UserCreationForm model to include a phone number field for users to enter their number and then validate the phone number using phonenumbers.parse in the backend to check if the number is in the respective format and whether it exists or not. I need to know what code I should include in my forms.py under my "users" app. I've tried including normal html text field for the phonenumbers and it does not belong to the default UserCreationForm model in Django and neither can it be stored in the database. (I need it to be stored in the database for the phone numbers). I am only using forms.py, views.py and register.html to be rendered in views as shown below, currently I am not using models.py. /* forms.py */ from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm # from validate_email import validate_email class UserRegisterForm(UserCreationForm): email = forms.EmailField() phone_number = forms.IntegerField(required=True) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user /* views.py */ from django.shortcuts import render, redirect from django.contrib import … -
Setting the choice field of one variable according to the value of another variable in the same form
I'm trying to plot graphs based on the values of the form variables in my django template. I have 4 variables (ChoiceFields) in my form I want my second choice field to change the choices with respect to the value of first variable Eg. is var1='age' var2_options=['M','F'] if it is var1='Education', var2_options=['Bachelors','Masters','High School'] here's my code: views.py- class HomeView(TemplateView): template_name='charts.html' def get(self, request): form = HomeForm() return render(request, self.template_name, {'form':form}) def post(self,request): form=HomeForm(request.POST) if form.is_valid(): text_1 = form.cleaned_data['post_1'] global z z=text_1 text = form.cleaned_data['post'] global b b=text text1 = form.cleaned_data['post1'] global c c=text1 text2 = form.cleaned_data['post2'] global d d=text2 args = {'form':form, 'text_1':text_1,'text':text, 'text1':text1, 'text2':text2} return render(request, self.template_name, args) charts.html (template) <form method="POST"> {%csrf_token%} {{form.as_ul}} <button type="submit">get</button> {{form.as_ul}} <button type="submit">PLOT GRAPH</button> </form> forms.py class HomeForm(forms.Form): post_1 = forms.ChoiceField(choices=((None,None),('लिंग :','sex :'),('शिक्षण:','education:'),('जात :','caste :'),('व्यवसाय :','occupation :'))) post = forms.ChoiceField(choices=((None,None),('लिंग :','लिंग :'),('शिक्षण:','शिक्षण:'),('जात :','जात :'),('व्यवसाय :','व्यवसाय :'))) post1 = forms.ChoiceField(choices=((None,None),('लिंग :','लिंग :'),('शिक्षण:','शिक्षण:'),('जात :','जात :'),('व्यवसाय :','व्यवसाय :'))) post2 = forms.ChoiceField(choices=((None,None),('bar','bar'),('horizontalBar','horizontalBar'),('line','line'))) I have arrays of choices ready for each variable How can I pass one variable and then assign the choice field of next variable according to it? -
Django: Is there a way to specify key_name of MySql index in migrate?
There is the following model, and you are trying to set index_together. class Event(models.Model): class Meta: ordering = ["-id"] index_together = ["user", "action"] action = models.IntegerField(db_index=True) user = models.ForeignKey("users.User", on_delete=models.CASCADE) post = models.ForeignKey("posts.Post", null=True, on_delete=models.CASCADE) When python manage.py makemigrations is executed, the following migration file is generated class Migration(migrations.Migration): dependencies = [ ('users', '00xx_auto_yyyymmdd_hhmm'), ('events', '00xx_auto_yyyymmdd_hhmm'), ] operations = [ migrations.AlterIndexTogether( name='event', index_together=set([('user', 'action')]), ), ] SHOW INDEX FROM tbl_name; in MySQL, index is assigned. Is it possible to specify Key_name? I want to use ignore_index anduse_index from Python code, so I want to specify the index Key_name by myself. Is there any way? -
Django: Read child objects from parent object effectively
I am fairly new to django and want to know the most effective way to go about my requirement here. I am creating a project tracking app, where a single project can have many team members and clientteam members and also multiple feedbacks. I have a table for team members and clientteam individually, but I also want to track the role of each team member within a project. I tried the following model structure using a mapping table, but now I am struggling to fetch data from it to django template. from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Project(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=300) primary_contact1 = models.CharField(max_length=100) primary_contact2 = models.CharField(max_length=100) start_date = models.DateField() end_date = models.DateField() owner = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) date_last_modified = models.DateTimeField(auto_now=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('project-detail', kwargs={'pk': self.pk}) class Teammember(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.CharField(max_length=50) def __str__(self): return self.first_name + " " + self.last_name def get_absolute_url(self): return reverse('teammember-detail', kwargs={'pk': self.pk}) class ProjectTeam(models.Model): project_team_member = models.ForeignKey(Teammember, related_name="project_team_member", on_delete=models.SET_NULL, null=True) project = models.ForeignKey(Project, related_name="project_team_project", on_delete=models.CASCADE) project_role = models.CharField(max_length=50) def __str__(self): return self.project.title + " - " + self.project_team_member.first_name + … -
ModuleNotFoundError: No module named 'wsgi'
I was going to host it using Heroku. But it does not work because of the problem with the profile. This my Procfile -> web: gunicorn wsgi:app I tried these things. ->web : gunicorn wsgi.py ->web : gunicorn .wsgi --log-file- my wsgi.py code """ WSGI config for config project. It exposes the WSGI callable as a module-level variable named application. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') application = get_wsgi_application() from whitenoise.django import DjangoWhiteNoise application = DjangoWhiteNoise(application) this is my heroku log Starting process with command gunicorn wsgi:app 2019-09-13T06:06:27.409894+00:00 heroku[web.1]: State changed from starting to crashed 2019-09-13T06:06:27.388714+00:00 heroku[web.1]: Process exited with status 3 2019-09-13T06:06:27.176179+00:00 app[web.1]: [2019-09-13 06:06:27 +0000] [4] [INFO] Starting gunicorn 19.9.0 2019-09-13T06:06:27.177866+00:00 app[web.1]: [2019-09-13 06:06:27 +0000] [4] [INFO] Listening at: http://0.0.0.0:56276 (4) 2019-09-13T06:06:27.177959+00:00 app[web.1]: [2019-09-13 06:06:27 +0000] [4] [INFO] Using worker: sync 2019-09-13T06:06:27.181907+00:00 app[web.1]: [2019-09-13 06:06:27 +0000] [10] [INFO] Booting worker with pid: 10 2019-09-13T06:06:27.187052+00:00 app[web.1]: [2019-09-13 06:06:27 +0000] [11] [INFO] Booting worker with pid: 11 2019-09-13T06:06:27.187674+00:00 app[web.1]: [2019-09-13 06:06:27 +0000] [10] [ERROR] Exception in worker process 2019-09-13T06:06:27.187678+00:00 app[web.1]: Traceback (most recent call last): 2019-09-13T06:06:27.187680+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2019-09-13T06:06:27.187682+00:00 app[web.1]: worker.init_process() 2019-09-13T06:06:27.187684+00:00 app[web.1]: File … -
Django: TemplateView with selenium
I use djangos TemplateView. One of the attribute is a webbrower. My question is now, how can I automatically quite/kill/exite/close the webbrower if the server is restartet? I alreay tried to use "try and exception" class Heatmap(TemplateView): template_name = "map.html" options = Options() if platform.system() == "Windows": options.headless = False else: def post(self, *args, **kwargs): """ @description: -
django html file is not showing
It keeps showing index.html file instead of register.html file which is supposed to display register form. Please help this newbie.. I will provide more info if needed. i checked with all the files i have been working on and googled similar issues but i cant find a solution. sdjflasjfsfjdsjdkdkdkdkdkdkslal dsfas dafsfds dafdsafdas dsfsafsavsavsavswgweg '''my views.py''' # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.views.generic.edit import FormView from django.shortcuts import render from seany_user.forms import registerform # Create your views here. def index(request): return render(request, 'index.html') class registerview(FormView): template_name = 'register.html' form_class = registerform '''my forms.py''' from django import forms class registerform(forms.Form): email = forms.EmailField( error_messages={ 'required': 'enter your goddamn email' }, max_length=64, label='email' ) password = forms.CharField( error_messages={ 'required': 'enter your password' }, widget=forms.PasswordInput, label='password' ) re_password = forms.CharField( error_messages={ 'required': 'enter your password' }, widget=forms.PasswordInput, label='confirm password' ) ''' my register.html''' {% extends "base.html" %} {% block contents %} <div class="row mt-5"> <div class="col-12 text-center"> <h1>register</h1> </div> </div> <div class="row mt-5"> <div class="col-12"> {{ error }} </div> </div> <div class="row mt-5"> <div class="col-12"> <form method="POST" action="."> {% csrf_token %} {% for field in form %} <div class="form-group"> <label for="{{ field.id_for_label }}">{{ field.label }}</label> <input type="{{ field.field.widget.input_type }}" class="form-control" … -
How to call a view class from another view class in django rest framework?
I have a project structre as following, .. ├── project │ ├── app1 │ ├── manage.py │ ├── project │ └── app2 │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── tests.py │ └── views.py ├── app2_views── project │ ├── main_view.py │ ├── view1.py │ ├── view2.py i want to call classes defined in view1.py in my main.py I have tried the following code, main.py from rest_framework import viewsets from app2.app2_views.view1.py import class1 class mainclass(viewsets.ModelViewSet): class1.view1_data() view1.py from app2.models.py import table1 from rest_framework import viewsets from app2.serializers.py import seri1 from django.db.models import Sum class class1(viewsets.ModelViewSet): def view1_data(): queryset = table1.objects.values('column') serializer_class = seri1 but i am getting an error saying should either include a `serializer_class` attribute, or override the `get_serializer_class()` method i am new to python, what am i doing wrong here? Thank you for your suggestions -
Cannot import s3
i am trying to import s3 so i can use the code `conn = S3.AWSAuthConnection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) as used here but i get this error import s3 File "C:\Users\abcedfghijk\Envs\myblog\lib\site-packages\s3__init__.py", line 1, in from .s3 import * File "C:\Users\abcedfghijk\Envs\myblog\lib\site-packages\s3\s3.py", line 253 except Exception, e: ^ SyntaxError: invalid syntax please help out.. thanks -
Serving static files in django with Nginx and gunicorn
Hi guys im trying to run my project on nginx with gunicorn. I have successfully access it but i have a problem on serving static files. I totally understand how manage.py collect static works but i think i am missing something on my configuration file in nginx or in my settings.py. Hoping you can help me. -
Pymongo Mongoclient connection issue
I have enabled the authentication of MongoDB from its config file and added one user with readWriteAnyDatabase role. Below is the query: db.createUser( { user: "username", pwd: "password", roles: [ { role: "readWriteAnyDatabase", db: "admin" } ] } ) I am trying to authenticate to MongoDB with pymongo on my local system but getting the below error: I am using the below configurations: pymongo==3.5. python 3.6.8 Django==1.11.7 MongoDB version v4.2.0 Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fb6c2b776a8> Traceback (most recent call last): File "/home/akash/Documents/Python/project/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/akash/Documents/Python/project/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 147, in inner_run handler = self.get_handler(*args, **options) File "/home/akash/Documents/Python/project/env/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 28, in get_handler handler = super(Command, self).get_handler(*args, **options) File "/home/akash/Documents/Python/project/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 68, in get_handler return get_internal_wsgi_application() File "/home/akash/Documents/Python/project/env/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 47, in get_internal_wsgi_application return import_string(app_path) File "/home/akash/Documents/Python/project/env/lib/python3.6/site-packages/django/utils/module_loading.py", line 20, in import_string module = import_module(module_path) File "/home/akash/Documents/Python/project/env/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/akash/Documents/Python/project/Web/project/project/wsgi.py", line 16, in <module> application = get_wsgi_application() … -
i found this error 'NoneType' object is not iterable
similarity_score = [] for sentence1 in text: for sentence2 in text: if sentence1!=sentence2: sim_score = [] temp2 = [] sim = [[wn.word_similarity(word1,word2,'jcn') for word1 in sentence1] for word2 in sentence2] # s_sim = sum([sum(i) for i in zip(*sim)]) s_sim = sum(sum_similarity(sim)) sim_score.append(s_sim) # C_sim = content_sim(sentence1,sentence2) # sim_score.append(C_sim) # t_sim = sum([e/max(sim_score) for e in sim_score]) t_sim = sum(sim_score)/len(sim_score) temp2.append(sentence1) temp2.extend((sentence2,t_sim)) similarity_score.append(temp2) return similarity_score File "C:\Users\Waqar Ahmad\projects\website\website\pages\Sentence_similarity.py", line 83, in similarity s_sim = sum(sum_similarity(sim)) TypeError: 'NoneType' object is not iterable [12/Sep/2019 22:02:51] "POST /genericbased_similaritymatrix HTTP/1.1" 500 371830 -
Django/DRF filtering
I filter my list of Product models by title field. For example, I want to find this title = 'Happy cake'. And if I type Case 1. 'happy cake', Case 2. 'hapy cake', happi kake' it should return me 'Happy cake'.As I know icontains helps me with case 1. How can I get that?May be some sort of technologies should be added or django itself has appropriate solution? -
django Same Host multi app Nginx Gunicorn
Run multiple django applications on one server environment python3 nginx django2 I cannot run. always Bad Request (400) django app1 settings nginx settings /etc/nginx/conf.d/abc.conf server { listen 80; server_name .abc.co; rewrite ^ https: // $ server_name $ request_uri? permanent; } server { listen 443 ssl; server_name .abc.co; ssl_certificate /etc/letsencrypt/live/abc.co/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/abc.co/privkey.pem; ssl_protocols TLSv1; ssl_ciphers HIGH:! ADH:! MD5; ssl_prefer_server_ciphers on; location / static { alias /home/abc.co/static; } location / media { alias /home/abc.co/media; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header X-Forwarded-For $ proxy_add_x_forwarded_for; proxy_set_header Host $ http_host; proxy_redirect off; proxy_set_header X-Forwarded-Proto $ scheme; } } gunicorn settings /etc/systemd/system/abc.service [Unit] Description = gunicorn After = network.target [Service] WorkingDirectory = / home / abc.co ExecStart = / usr / bin / gunicorn --bind 127.0.0.1:8000 config.wsgi: application [Install] WantedBy = multi-user.target django settings /home/123.co/config/settings.py ALLOWED_HOSTS = ['abc.co'] Check the access to the main domain with the above settings, and confirm that the code is working properly. From here, trying to build another django app on the same server and IP address failed. django app1 Setting 2 ↓ nginx settings /etc/nginx/conf.d/123.conf server { listen 80; server_name .123.jp; rewrite ^ https: // $ server_name $ request_uri? permanent; } server { listen 443 ssl; server_name. 123.jp; ssl_certificate … -
Django Template extends remote url
I have moved my email templating (.html) to an S3 bucket. I want to send an email using a base.html and the body so I can reuse all my template. However when trying it django can't find the template. Note: I am not using django-storage as for now but manually getting the template using Template class (see below codes). I tried two methods already: Using the full remote url https://s3-ap-southeast-1.amazonaws.com/xxxx in the extends tags Got an error message: TemplateDoesNotExist (even if it does exist) Using relative path: ../../assets/base.html in the extends tags Got an error message: do_extends 'NoneType' object has no attribute 'lstrip' # To get my template def _get_remote_template(self, email_template): url = "%s/%s" % (self.email_host, email_template) response = requests.get(url) assert response.status_code == 200 return Template(response.content.decode("utf-8")) base.html <div class="body-section"> <!-- import here the content body --> {% block body %} {% endblock %} </div> template_1.html (First method) {% extends "https://s3-ap-southeast-1.amazonaws.com/xxxx/assets/templates/base.html" %} template_1.html (Second method) {% extends "../../assets/templates/base.html" %} Do you have any ideas on how to achieve that, my main goal is to remove all emails templates from my django project. Appreciate your help! -
Django 1.11.7 --> 2.0 --> 2.2 migration - errors on runserver and Wall check
I am doing migration from Django 1.11.7 --> 2.0 --> 2.2 I am running though some errors and needs some help on how to solve this. Here are the error output https://gist.github.com/axilaris/2088f3dfc281a2be6f9461d6577ca8dd here are some excerpts of the error outout $python -Wall manage.py check --settings=railercom.settings.local .... /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/_bootstrap.py:219: ImportWarning: can't resolve package from __spec__ or __package__, falling back on __name__ and __path__ return f(*args, **kwds) System check identified no issues (0 silenced). and $python manage.py runserver --settings=unrealpower.settings.local ..... File "/Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/unrealpowerenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 103, in iter_all_python_module_files return iter_modules_and_files(modules, frozenset(_error_files)) File "/Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/unrealpowerenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 124, in iter_modules_and_files if getattr(module, '__spec__', None) is None: SystemError: <built-in function getattr> returned a result with an error set -
How to get foreign object with minimal price
I have two classes Product and Offer class Product: ... name = models.CharField(max_length=255) ... class Offer: ... price = models.IntegerField() product = models.ForeignKey(Product, on_delete=models.CASCADE) ... And I have to get the offer of a product with minimal price in single queryset. I know that I can get price like this: Product.objects.filter(...).annotate(minimal_price=Min('offer__price').values('minimal_price', ...) or product.offer_set.all().order_by('price').first() But I have to get offer in single query with product like this: Product.objects.filter(...).annotate(offer_with_minimal_price=Min('offer__price__but_return_offer_not_price').values('offer_with_minimal_price', ...) -
Image cropping with pillow and cropper and django isn't saving the cropped image?
So I followed this link to add cropping feature to the app I tried their approach by overriding the save method and it caused some errors in the view so I decided to make the cropping process happen in the view but the problem I don't get the cropped image even after providing the values of the crop function manually. if request.method == 'POST': form = forms.ImageForm(request.POST,request.FILES) if form.is_valid(): image = form.save(commit=False) x = form.cleaned_data['x'] y = form.cleaned_data['y'] w = form.cleaned_data['width'] h = form.cleaned_data['height'] im = Image.open(image.pre_analysed) cropped = im.crop((x, y, w+x, h+y)) resized_image = cropped.resize((300, 300), Image.ANTIALIAS) resized_image.save(image.pre_analysed.path) image.patient = patient messages.success(request,"Image added successfully!") image.save() and here's the form class ImageForm(ModelForm): x = forms.FloatField(widget=forms.HiddenInput()) y = forms.FloatField(widget=forms.HiddenInput()) width = forms.FloatField(widget=forms.HiddenInput()) height = forms.FloatField(widget=forms.HiddenInput()) class Meta: model = UploadedImages fields = ('pre_analysed', 'x', 'y', 'width', 'height', ) here's the problem I think the save function of Pillow isn't being called right so how can I call it or how can overwrite the original image with the new one? Is there an easier way to crop images? I took a look at Django-image-cropping and I think it has more than I ask I just want to crop the image and save … -
Dynamic content on page is not showing
I am trying to generate dynamic content on page with the onclick event of js but there is error in console "Uncaught SyntaxError: Unexpected identifier" html {% load static %} <head> <script type="text/javascript"> function myFunction() { // document.getElementById("demo").innerHTML = "Paragraph changed."; document.getElementById("demo").innerHTML = "{{ Malegender }}"; } </script> </head> <body> <div class="container mt-5"> <h1>Gender</h1> <hr> <h5>{{ mygender.as_p }}</h5> <h1 id="demo">Hello</h1> <div class="container"> <button type="submit" name="gender_submit" class="btn btn-success" onclick="myFunction()">Confirm</button> </div> </div> </body> views.py def Gender(request): gender_selection = GenderForm() male_detail = MaleForm() Male = False print("Value of male",Male) if 'gender_submit' in request.POST: male_detail = MaleForm(data=request.POST) Male = True print("Value of male d",Male) print("Value of male a",Male) return render(request, 'Gender.html',{"mygender":gender_selection,"Malegender":male_detail}) forms.py class MaleForm(forms.ModelForm): class Meta: model = GenderModel fields = ('genderMale','genderMale1','genderMale2','genderMale3','genderMale4') models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class GenderModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) gender_choice=(('Male','Male'),('Female','Female'),) gender = models.CharField(max_length=6,choices=gender_choice,null=True,) genderMale = models.BooleanField(default=False) genderMale1 = models.BooleanField(default=False) genderMale2 = models.BooleanField(default=False) genderMale3 = models.BooleanField(default=False) genderMale4 = models.BooleanField(default=False) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: GenderModel.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.gendermodel.save() when I click on button the error on the console is showing. I am trying to display that … -
Is it possible to use the built-in LogEntry to track actions of every users not only in admin page? If so, how can I implement it?
I just recently knew about the built in LogEntry model in django, and I've tried to registered it in my admin page. What I want to happen is, for example, the admin added new User not using the django admin page but through the add page I made using some model forms in my site, how can i add data to LogEntry regarding that add action on my site? Thanks for your help! -
How to set initial value in the form
Hey guys how can i set initial value in my form field, let say the user click "BidForm" in the search form, i want the BidForm value will be the value of ProjectName in the other form... here's my code in my search views def search_views(request): project_list = ProjectNameInviToBid.objects.all() query = request.GET.get('query') if query: project_list = project_list.filter(ProjectName__icontains=query) context = { 'project_list': project_list } return render(request, 'content/search_views.html', context) and my other views def project_name_details(request, sid): majordetails = ProjectNameInviToBid.objects.get(id=sid) if request.method == 'POST': form = invitoBidForm(request.POST, request.FILES) form.fields['ProjectName'].initial = majordetails if form.is_valid(): form.save() messages.success(request, 'File has been Uploaded') else: form = invitoBidForm() args = { 'majordetails': majordetails, 'form': form } return render(request,'content/invitoBid/bacadmininvitoBid.html', args) my form.py class invitoBidForm(ModelForm): class Meta: model = InviToBid fields = ('ProjectName','NameOfFile', 'Contract_No', 'Bid_Opening', 'Pre_Bid_Conference', 'Non_Refundable_Bidder_Fee', 'Delivery_Period', 'Pdf_fileinvi',) and my models.py class ProjectNameInviToBid(models.Model): ProjectName = models.CharField(max_length=255, verbose_name='Project Name', null=True) DateCreated = models.DateField(auto_now=True) def __str__(self): return self.ProjectName class InviToBid(models.Model): today = date.today() ProjectName = models.ForeignKey('ProjectNameInviToBid', on_delete=models.CASCADE) NameOfFile = models.CharField(max_length=255, verbose_name='Name of File') Contract_No = models.IntegerField(verbose_name='Contract No') def __str__(self): return self.NameOfFile -
Loading "Search Page" produces "404 Page Not Found" page when querying data
I have a page ".com/listings" that loads well, but when I run a query through the form, it produces this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/listings/search?keywords=&city=Corpus+Christi Raised by: listings.views.listing It should render a ".com/listings/search" page. Previously I had it working beautifully, but after I successfully changed the url path of single listings page - "listings/listing" to a string from an integer, it caused this problem for my search page. Could be a coincidence, but I believe it could be connected. urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='listings'), path('<str:listing_title>', views.listing, name='listing'), path('search', views.search, name='search'), ] views.py from django.shortcuts import get_object_or_404, render from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from .choices import price_choices, city_choices, bed_choices, bath_choices from .models import Listing from agents.models import Agent from contacts.models import Contact def index(request): listings = Listing.objects.order_by('-list_date').filter(is_published=True) paginator = Paginator(listings, 6) page = request.GET.get('page') paged_listings = paginator.get_page(page) context = { 'listings': paged_listings, 'price_choices': price_choices, 'city_choices': city_choices, 'bed_choices': bed_choices, 'bath_choices': bath_choices } return render(request, 'listings/listings.html', context) def listing(request, listing_title): listing = get_object_or_404(Listing, title=listing_title) context = { 'listing': listing, } return render(request, 'listings/listing.html', context) def search(request): queryset_list = Listing.objects.order_by('list_date') if 'keywords' in request.GET: keywords = request.GET['keywords'] … -
Django Rest Framework - How to Create a model with related objects
I would like to be able to POST to a Model with an array of related objects, but I can't figure it out how. Now I am able to retrieve information from these relations, but don't know how to POST. Django==2.2.4 django-rest-framework==3.10.3 models.py from django.db import models import datetime from django.utils.html import format_html_join from collections import Counter class Cliente(models.Model): def __str__(self): return self.nome nome = models.CharField(max_length=200) class Meta: ordering = ['id'] class Produto(models.Model): def __str__(self): return self.nome + ", Preço unitário: " + str(self.preco_unitario) nome = models.CharField(max_length=200) preco_unitario = models.DecimalField(max_digits=14, decimal_places=2, default=0.00) multiplo = models.IntegerField(blank=True, null=True) class Pedido(models.Model): cliente = models.ForeignKey(Cliente, models.DO_NOTHING, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s' % (self.pedido_id) def total(self): itens = ItensPedido.objects.filter(pedido=self.pk) valor = sum(Counter(item.preco * item.quantidade for item in itens)) return str(valor) class ItensPedido(models.Model): pedido = models.ForeignKey(Pedido, on_delete=models.CASCADE,related_name='itemspedido', null=True) produto = models.ForeignKey(Produto, on_delete=models.CASCADE, null=True) preco = models.DecimalField(max_digits=14, decimal_places=2, default=0.00) quantidade = models.IntegerField(default=1, null=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.pedido.pedido_id + ": " + self.produto.nome + ", preço: " + str(self.preco) + ", quantidade: " + str(self.quantidade) Then I have my serializers.py from .models import Produto, Cliente, Pedido, ItensPedido from rest_framework import serializers class ProdutoSerializer(serializers.Serializer): id = serializers.IntegerField() nome = serializers.CharField() preco_unitario = … -
How create form for comments with used django and ajax
I'm trying to make it possible to edit comments using DRF, my idea is that after clicking on the button a form pops up in which there are all the same fields for creating DRF, namely the field with the name of the comment and the comment context itself. But I get an error in the answer that my fields are empty. As far as I understand, editing the API is called immediately, thereby skipping the values in the filled fields. How can I fix this, with high probability I am sure that the error is somewhere in JS. Here is the browser response: post: ["This field is required."] text: ["This field is required."]. <p class="comment_text"> {{ comment.text|linebreaks }} </p> <div> <form id="edit" method="post" action="/api/albums/{{comment.id}}/edit/"> <input type="hidden" name="csrfmiddlewaretoken"> <input type="text" class="input_Text_post"></br> <input type="text" class="input_Text_text"></br> <button class="button_edit" value="{{ comment.id }}"> Send </button> </form> </div> $(document).ready(function() { $(".button_edit").click(function(){ var comment_id = ($(this).attr('value')); var $this = $(this); $this.toggleClass('button_edit'); if ($this.hasClass('button_edit')){ $this.text('Send comment'); } else { $this.text('Change comment'); } $('.input_Text_text').show(); $('.input_Text_post').show(); $('.comment_text').text($('.input_Text_post').val()); $('.comment_text').text($('.input_Text_text').val()); $('#edit').on('submit', function(event){ event.preventDefault(); $.ajax({ type: 'PUT', url: 'http://localhost:8000/api/albums/' + comment_id + '/edit/', headers: {"X-CSRFToken": $csrf_token}, data: { 'post': $('#input_Text_post').val(), 'text': $('#input_Text_text').val(), }, success: function(data){ console.log(data); } }); }) }); }); class … -
Issue getting django celery worker started on elastic-beanstalk
I am trying to get my celery worker running on elastic-beanstalk. It works fine locally but when I deploy to EB I get the error "Activity execution failed, because: /usr/bin/env: bash": No such file or directory". I am pretty novice at celery and EB so I haven't been able to find a solution so far. I am working on a windows machine and I have seen other people face this issue with windows and fix it by converting "celery_configuration.txt" file to UNIX EOL, however I am using celery-worker.sh instead but I converted it to a UNIX EOL which still didn't work. .ebextensions/celery.config packages: yum: libcurl-devel: [] container_commands: 01_mkdir_for_log_and_pid: command: "mkdir -p /var/log/celery/ /var/run/celery/" 02_celery_configure: command: "cp .ebextensions/celery-worker.sh /opt/elasticbeanstalk/hooks/appdeploy/post/ && chmod 744 /opt/elasticbeanstalk/hooks/appdeploy/post/celery-worker.sh" cwd: "/opt/python/ondeck/app" 03_celery_run: command: "/opt/elasticbeanstalk/hooks/appdeploy/post/celery-worker.sh" .ebextensions/celery-worker.sh #!/usr/bin/env bash # Get django environment variables celeryenv=`cat /opt/python/current/env | tr '\n' ',' | sed 's/export //g' | sed 's/$PATH/%(ENV_PATH)s/g' | sed 's/$PYTHONPATH//g' | sed 's/$LD_LIBRARY_PATH//g'` celeryenv=${celeryenv%?} # Create celery configuraiton script celeryconf="[program:celeryd-worker] ; Set full path to celery program if using virtualenv command=/opt/python/run/venv/bin/celery worker -A backend -P solo --loglevel=INFO -n worker.%%h directory=/opt/python/current/app/enq_web user=nobody numprocs=1 stdout_logfile=/var/log/celery/worker.log stderr_logfile=/var/log/celery/worker.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. …