Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I use select_related in an over-ridden model save method in Django?
Lets say I have the following model: class Movie(models.Model): number_of_reviews = models.IntegerField() class Review(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE) def save(self, *args, **kwargs): super(Review, self).save(*args, **kwargs) self.movie.number_of_reviews += 1 self.movie.save() Every time I save a review, another database lookup is done to get the movie. Can this be done using select_related, so the number of database lookups is reduced? Note: Please no answers telling me how I should aggregate the number of reviews only when required, instead of storing it in the database, because that is not the point of this question. This is a made-up scenario. -
How can I delete or update an object that has TypeError?
My application created an object with an error, the user inserted a string (I believe) but the field was Decimal. I know forms would have prevented it but the insertion happened on a post_save decorator and now I can't access the object, update or delete it. comandas_antecipadas = ComandaAntecipado.objects.all() comandas_antecipadas Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\projetos\barzim\venv\lib\site-packages\django\db\models\query.py", line 244, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "C:\projetos\barzim\venv\lib\site-packages\django\db\models\query.py", line 268, in __iter__ self._fetch_all() File "C:\projetos\barzim\venv\lib\site-packages\django\db\models\query.py", line 1186, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\projetos\barzim\venv\lib\site-packages\django\db\models\query.py", line 63, in __iter__ for row in compiler.results_iter(results): File "C:\projetos\barzim\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1009, in apply_converters value = converter(value, expression, connection) File "C:\projetos\barzim\venv\lib\site-packages\django\db\backends\sqlite3\operations.py", line 254, in converter return create_decimal(value).quantize(quantize_value, context=expression.output_field.context) TypeError: argument must be int or float comandas_antecipadas.count() 11 comandas_antecipadas[9] <ComandaAntecipado: ComandaAntecipado object (120)> comandas_antecipadas[10] Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\projetos\barzim\venv\lib\site-packages\django\db\models\query.py", line 302, in __getitem__ qs._fetch_all() File "C:\projetos\barzim\venv\lib\site-packages\django\db\models\query.py", line 1186, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\projetos\barzim\venv\lib\site-packages\django\db\models\query.py", line 63, in __iter__ for row in compiler.results_iter(results): File "C:\projetos\barzim\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1009, in apply_converters value = converter(value, expression, connection) File "C:\projetos\barzim\venv\lib\site-packages\django\db\backends\sqlite3\operations.py", line 254, in converter return create_decimal(value).quantize(quantize_value, context=expression.output_field.context) TypeError: argument must be int or float -
source env/bin/activate 'source' is not recognized as an internal or external command, operable program or batch file
venv) C:\Users\Sunil\PycharmProjects\project>source env/bin/activate 'source' is not recognized as an internal or external command, operable program or batch file. venv) C:\Users\Sunil\PycharmProjects\project>source env/bin/activate -
Remove first part of xml file, cannot be serialized
I have an xml file it start like: '''some non ascii character''' <b:FatturaElettronica xmlns:b="#"> <FatturaElettronicaHeader> <DatiTrasmissione> <IdTrasmittente> <IdPaese>IT</IdPaese> i need to remove all until <FatturaElettronicaHeader> now the code is: import xml.etree.ElementTree as ET import xml.etree.ElementTree as ETree from lxml import etree parser = etree.XMLParser(encoding='utf-8', recover=True, remove_comments=True, resolve_entities=False) tree = ETree.parse('test.xml', parser) root = tree.getroot() print etree.tostring(root) and give me: Traceback (most recent call last): File "xml2.py", line 14, in <module> print etree.tostring(root) File "src/lxml/etree.pyx", line 3350, in lxml.etree.tostring TypeError: Type 'NoneType' cannot be serialized. whitout the first part of xml file it work. TY -
Python/Django escape list of strings for JSON parsing by Javascript
Know these questions are annoying but I'm really stuck so would appreciate help. I'm trying to send a list of strings to the frontend and load into a javascript object. Relevant parts of the Django application: In views.py in the handler function: import json def home(request): test_list = ["(hello world\")"] return render(request, 'app/home.html', {"test_list": json.dumps(test_list)}) In home.html: let parsed = JSON.parse('{{test_list|safe}}'); I get the error: Uncaught SyntaxError: Unexpected token ) in JSON at position 15 Things I have tried: - running json.dumps directly on each (str) element of the list, not just on the whole list. - Manually adding a backslash to each of (", ', (, ), [, ] ) - Manually adding two backslashes to each of (", ', (, ), [, ] ) - Not using |safe in the template What has worked is just removing each of (", ', (, ), [, ] ). But I can't have them removed. I need them escaped. Here is what Google Chrome tells me the template resolves to at the line that fails: let parsed = JSON.parse('["(hello world\")"]'); Help much appreciated. -
How to change view of ManyToManyField in template?
It's ugly What can I do to see there the body of this field? There must be a values of Size object, but not "Size object (id)" I have Models: from django.db import models class Good(models.Model): Name = models.CharField(max_length = 150) Size = models.ManyToManyField('Size') def _str_(self): return self.Name class Size(models.Model): size = models.CharField(max_length = 150) def _str_(self): return self.size This is my forms.py class GoodGet(forms.ModelForm): class Meta: model = Good_Get Size = forms.ModelChoiceField(queryset = Good.objects.all()) fields = '__all__' def __init__(self, *args, good_id1=None, **kwargs): super(forms.ModelForm, self).__init__(*args, **kwargs) if good_id1 is not None: obj = Good.objects.filter(id = good_id1) for good in obj: good_sizes = good.Size.all() self.fields['Size'].queryset = good_sizes So, I want the user to choose the size from the list of Good's sizes, but he can't see what size does he choose. I think I need to do something with my database, needn't I? -
Django Docker Nginx File Upload Problem with Size
I use Django with Docker, Nginx and Gunicorn. I can upload files up to 1MB with no problem. Files 1MB up to 2.5MB gives [413 Entity too large], and files above 2.5MB gives [502 Bad gateway]. I have tried to change my gunicorn workers to gevent and increase timeout to 300s, as well as timeout for nginx. I changed FILE_UPLOAD_MAX_MEMORY_SIZE up to 10MB. In docker-compose, I have the following: command: bash -c "python manage.py collectstatic --no-input && python manage.py makemigrations && python manage.py migrate && gunicorn --timeout 300 --workers=3 --worker-class=gevent my_project.wsgi -b 0.0.0.0:8000" In settings.py I have this: FILE_UPLOAD_MAX_MEMORY_SIZE = 9621440 Again in docker-compose regarding nginx I have this: nginx: image: nginx:latest container_name: ng01 ports: - "8000:8000" volumes: - ./src:/src - ./config/nginx:/etc/nginx/conf.d - /static:/static - ./src/media:/media depends_on: - web restart: always And my nginx.conf is: upstream web { ip_hash; server web:8000; } server { location /static/ { autoindex on; alias /static/; } location /media/ { autoindex on; alias /media/; } location / { proxy_pass http://web/; proxy_connect_timeout 75s; proxy_read_timeout 300s; } listen 8000; server_name mydomain; } I expect to be able to upload PDF's that are up to 10MB or so. -
Unable to save data from a form to a database table in django
I'm trying to set up a form in Django and save the data to my database I am stuck on is how to process the form data and save it within the view. How can I save the form data in database and display the data from database using same form to store and update data? Please help me.Any help will be appreciated. Here is my urls.py url(r'^design-data/(?P<tech_regid>\d+)/$', views.GetDesignDataPage.as_view(), name="design-data"), url(r'^bylaw/(?P<tech_regid>\d+)/$', views.ByLawDataPage.as_view(), name="bylaw"), Here is my views.py class GetDesignDataPage(TemplateView): template_name = 'design_data.html' def get_context_data(self, **kwargs): context = super(GetDesignDataPage, self).get_context_data(**kwargs) context['tech_regid'] = self.kwargs.get('tech_regid') registration = get_object_or_404(NewRegistration, technicalregistration=self.kwargs.get('tech_regid'), technicalregistration__checked=False) context['registration'] = registration try: _bd = registration.application_set.get() context['building_length_ft'] = _bd.building_length_ft + _bd.building_length_in / float(12) context['building_breadth_ft'] = _bd.building_breadth_ft + _bd.building_breadth_in / float(12) context['building_height_ft'] = _bd.building_height_ft + _bd.building_height_in / float(12) context['building_storey'] = _bd.building_storey context['gc_ft'] = _bd.building_area except: pass context['bylaws_questions_groups'] = system_settings.models.ByLawsQuestionGroup.objects.all() context['bylaws_answered_questions'] = serializers.serialize('json', ByLawsInformation.objects.filter(reg=registration), fields=('question', 'answer', 'remarks')) return context class SaveByLawsQuestion(View): def post(self, request, regid): remarks= request.POST.getlist('remarks[]') question=request.POST.getlist('question[]') for i in range(len(question)): reg = get_object_or_404(NewRegistration, id=i['reg']) question = get_object_or_404(system_settings.models.ByLawsQuestion, id=i['question']) rated = ByLawsInformation.objects.create( reg = reg, question = question[i], remarks = remarks[i] ) return redirect(to=reverse_lazy('design-data', kwargs={'tech_regid': self.kwargs.get('regid')})) bylaw.html <form method="post" action="{% url 'savebylaws' regid=tech_regid %}"> {% csrf_token %} {% for question_group in bylaws_questions_groups %} … -
Not able to connect to postgres from python docker image to postgres docker image in bitbucket pipelines for my django project
I'm setting up bitbucket pipelines for my Django project to be able to have some automatic tests running. I'm using default python Docker image with postgres docker image as service but Django can't connect to PostgreSQL server. Whatever I tried I always get the error : psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? I tried to set localhost/posgres image name with or without port 5432 in my Django settings files. Also thought maybe the image didn't exposed the port. my bitbucket pipeline file # This is a sample build configuration for Python. # Check our guides at https://confluence.atlassian.com/x/x4UWN for more examples. # Only use spaces to indent your .yml configuration. # ----- # You can specify a custom docker image from Docker Hub as your build environment. image: python:3.7.3 definitions: services: postgres: image: postgres environment: POSTGRES_DB : 'my_db' POSTGRES_USER : 'my_user' POSTGRES_PASSWORD: 'my_pwd' expose: - "5432" ports: - "5432:5432" pipelines: default: - step: caches: - pip script: # Modify the … -
ModuleNotFoundError: No module named 'django' on IIS windows server 2008 r2
Trying to make a django application run on IIS on windows server 2008 r2 After adding all the handlers and adding those variables on the env: DJANGO_SETTINGS_MODULE : erp.settings PYTHONPATH: "C:\inetpub\wwwroot\new_stars" WSGI_HANDLER: django.core.wsgi.get_wsgi_application Error occurred while reading WSGI handler: Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\wfastcgi.py", line 616, in get_wsgi_handler raise ValueError('"%s" could not be imported%s' % (handler_name, last_tb)) ValueError: "django.core.wsgi.get_wsgi_application()" could not be imported: Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\wfastcgi.py", line 600, in get_wsgi_handler handler = __import__(module_name, fromlist=[name_list[0][0]]) ModuleNotFoundError: No module named 'django' StdOut: StdErr: ** I know it is not recommended to run Django On IIS but I have no other choice** -
Time values off slightly when adding to database
I am attempting to create a add appointment slots to my database programmatically, but I noticed my values for date_start and date_end are slightly off. What I've done is store weekday and weekend time slots in arrays of pairs of tuples. The tuples contain an hour and a minute value, which are passed as a parameter to the internal appointments function where they're unpacked and passed to the datetime constructor. managers.py The function in question is create_appointments (specifically appointments) which has the time slots hard-coded and calls on create_appointment for each pair. import pytz from django.db import models from datetime import date, datetime from project.settings import TIME_ZONE # 'America/Chicago' class AppointmentManager(models.Manager): def create_appointment(self, date_start, date_end): from booking.models import Appointment try: appt = Appointment.objects.create( profile=None, date_start=date_start, date_end=date_end, ) except Exception as e: return (False, e) return (True, appt) def create_appointments(self, date=date.today(), tzinfo=pytz.timezone(TIME_ZONE), verbose=False): from booking.models import Appointment def appointments(times): for pair in times: hour_start, minute_start = pair[0] hour_end, minute_end = pair[1] date_start = datetime( date.year, date.month, date.day, hour_start, minute_start, tzinfo=tzinfo, ) date_end = datetime( date.year, date.month, date.day, hour_end, minute_end, tzinfo=tzinfo, ) valid, response = self.create_appointment(date_start, date_end) if not valid: raise response if verbose: print('%s %s' % (response.date_start, response.date_end)) def weekend(): appointments([ … -
How to properly install virtualenvwrapper to my Mac?
I'm trying to follow the Mozilla Django guide: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/development_environment Following the steps in the guide, I've successfully installed Python3.7.3 and pip3. When I enter python3 -V and pip3 list I get the expected responses. Step 1 The next step is to install virtualenvwrapper. I did this with the recommended command: sudo pip3 install virtualenvwrapper However when I hit enter I got the following warnings: The directory '/Users/myusername/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/myusername/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Collecting virtualenvwrapper Downloading https://files.pythonhosted.org/packages/c1/6b/2f05d73b2d2f2410b48b90d3783a0034c26afa534a4a95ad5f1178d61191/virtualenvwrapper-4.8.4.tar.gz (334kB) 100% |████████████████████████████████| 337kB 9.9MB/s Collecting virtualenv (from virtualenvwrapper) Downloading https://files.pythonhosted.org/packages/ca/ee/8375c01412abe6ff462ec80970e6bb1c4308724d4366d7519627c98691ab/virtualenv-16.6.0-py2.py3-none-any.whl (2.0MB) 100% |████████████████████████████████| 2.0MB 14.1MB/s Collecting virtualenv-clone (from virtualenvwrapper) Downloading https://files.pythonhosted.org/packages/ba/f8/50c2b7dbc99e05fce5e5b9d9a31f37c988c99acd4e8dedd720b7b8d4011d/virtualenv_clone-0.5.3-py2.py3-none-any.whl Collecting stevedore (from virtualenvwrapper) Downloading https://files.pythonhosted.org/packages/c6/dc/6ee92bccfe3c0448786b30b693e6060d62ec8c4a3ec9a287bac1c1a8d8c9/stevedore-1.30.1-py2.py3-none-any.whl (42kB) 100% |████████████████████████████████| 51kB 28.3MB/s Collecting pbr!=2.1.0,>=2.0.0 (from stevedore->virtualenvwrapper) Downloading https://files.pythonhosted.org/packages/e0/27/a913b227c9053472ea7dda33e409a1e748e50cdd208a955f3d6a20e9a875/pbr-5.3.0-py2.py3-none-any.whl (108kB) 100% |████████████████████████████████| 112kB 27.2MB/s Collecting six>=1.10.0 (from stevedore->virtualenvwrapper) Downloading https://files.pythonhosted.org/packages/73/fb/00a976f728d0d1fecfe898238ce23f502a721c0ac0ecfedb80e0d88c64e9/six-1.12.0-py2.py3-none-any.whl Installing collected packages: … -
literal for int() with base 10: 'testuser' even tho the argument passed is a string
I have to make a project blog for my college assignment and am trying to make a page to display all the posts by a particular user but I keep getting this error Traceback: File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/Grayocean/grayocean.co/blog/views.py" in user_blog_list 121. blogs=get_object_or_404(Blog, author=username) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/shortcuts.py" in get_object_or_404 93. return queryset.get(*args, **kwargs) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/db/models/query.py" in get 399. clone = self.filter(*args, **kwargs) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/db/models/query.py" in filter 892. return self._filter_or_exclude(False, *args, **kwargs) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/db/models/query.py" in _filter_or_exclude 910. clone.query.add_q(Q(*args, **kwargs)) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/db/models/sql/query.py" in add_q 1290. clause, _ = self._add_q(q_object, self.used_aliases) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/db/models/sql/query.py" in _add_q 1318. split_subq=split_subq, simple_col=simple_col, File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/db/models/sql/query.py" in build_filter 1251. condition = self.build_lookup(lookups, col, value) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/db/models/sql/query.py" in build_lookup 1116. lookup = lookup_class(lhs, rhs) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/db/models/lookups.py" in init 20. self.rhs = self.get_prep_lookup() File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/db/models/fields/related_lookups.py" in get_prep_lookup 115. self.rhs = target_field.get_prep_value(self.rhs) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/db/models/fields/init.py" in get_prep_value 966. return int(value) Exception Type: ValueError at /user/rheazes Exception Value: invalid literal for int() with base 10: 'testuser' views.py def user_blog_list(self, username): blogs=get_object_or_404(Blog, author=username) context={ 'posts':blogs } return render(request,'blog/user_posts.html',context) models.py class Blog(models.Model): title=models.CharField(max_length=100) content=models.TextField(blank=True) image = models.ImageField(upload_to='blog_images', blank=True) image1= models.ImageField(upload_to='blog_images', blank=True,verbose_name='second image') image2= … -
User profile info(table) with this Cpf cnpj(field (unique)) already exists
My View code is this: @login_required def DadosUserView(request): template_name = 'users_c2p/dados.html' usercpf = request.user.username profile = UserProfileInfo.objects.filter(cpf_cnpj=usercpf) contrato_dividas = Contrato.objects.filter(cpf_cnpj=usercpf) empresa = Empresa.objects.all() if profile: person = get_object_or_404(UserProfileInfo, cpf_cnpj=usercpf) profile_form = UserProfileInfoForm(request.POST or None, instance=person) flag = 1 else: profile_form = UserProfileInfoForm(initial={"cpf_cnpj": usercpf, }) flag = 0 if request.method == 'POST': profile_form = UserProfileInfoForm(data=request.POST) print(request.method) print(profile_form.errors) if profile_form.is_valid(): # Create new profile if flag == 0: profile_form_cpf = profile_form.cleaned_data['cpf_cnpj'] print(profile_form_cpf) if usercpf == profile_form_cpf: profile_form.save() log = LogUsuario.objects.create(cpf_cnpj=profile_form_cpf, movimentacao="FIRST UPDATE") return redirect(reverse_lazy('users_c2p:dadosuser')) else: return profile_form.errors #Update profile elif flag == 1: profile_form_cpf = profile_form.cleaned_data['cpf_cnpj'] if usercpf == profile_form_cpf: profile_form.save() log = LogUsuario.objects.create(cpf_cnpj=profile_form_cpf, movimentacao="UPDATE") return redirect(reverse_lazy('users_c2p:sucesso_cadastro')) else: return profile_form.errors else: return redirect(reverse_lazy('users_c2p:dadosuser')) context = { "UserData" : profile, "profile_form": profile_form, "Contrato": contrato_dividas, "Empresa": empresa, #'media_url': settings.MEDIA_URL, } return render(request, template_name, context) I want to user the #Update profile part.. The #Create profile is working well, but when I try to update it, it says that user already exists and do nothing. What should I do, so it recognizes this is the idea and then update the info that I desire? -
Rendering same view and preventing Form resubmission confirmation
I have a simple index page with the form to get some feedback from people and after submitting this form my view just loads the same page. This occurs "Form resubmission" confirmation in Chrome Browser (probably in other browsers too). I don't want to create the second page with confirmation I do confirmation just with small alert on the top of my page after form submitting. So could I solve this problem? Most of the answers I saw until says that there must be redirect function, but redirect takes not a context in my case I need the context to know that the form was submitted and show the alert to inform the users. My view: def index(request): if request.POST: showAlert = True # Collect form data name = request.POST.get('name') to_email = 'example@email.com' message = 'message: {}\nname: {}\nemail: {}'.format( request.POST.get('message'), name, request.POST.get('email') ) subject = 'feedback' try: email = EmailMessage( subject, message, django_settings.EMAIL_HOST_USER, [to_email] ) email.send(fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found.') return render(request, 'project/index.html', {'showAlert': showAlert}) else: return render(request, 'project/index.html') And here is the form: <form id="frm_feedback" role="form" method="POST"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control" placeholder="Your name" name="name"> </div> <div class="form-group"> <input type="email" class="form-control" placeholder="Your email" name="email"> … -
I'm trying to use django cities light library but I get a ValueError, how can I solve this?
My application idea is to show doctors' information to clients, I'm using cities-light library to get cities but when I try to use it I get a ValueError. Here is my models.py: from django.db import models from django.urls import reverse from phonenumber_field.modelfields import PhoneNumberField from cities_light.models import City # Create your models here. class Doctor(models.Model): name = models.CharField(max_length=100) specialty = models.TextField() address = models.CharField(max_length=250, blank=True) phone_number = PhoneNumberField(blank=True) email = models.EmailField(blank=True) city = models.ForeignKey(City, on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('home') and this is the HTML code: {% extends "base.html" %} {% load static %} {% block content %} {% for doctor in object_list %} <h1>{{ doctor.name }}</h1> <p>{{ doctor.specialty }}</p> <p>{{ doctor.address }}</p> <p>{{ doctor.phone_number }}</p> <p>{{ doctor.email }}</p> <p>{{ doctor.city }}</p> {% endfor %} {% endblock content %} -
How to get all the objects from one model's field (with filter)
I try to get choices for my form from model Good. def __init__(self, *args, good_id1=None, **kwargs): super(forms.ModelForm, self).__init__(*args, **kwargs) if good_id1 is not None: self.fields['Size'].queryset = Good.objects.filter( id=good_id1 ) Now I am getting a full Good object with its all fields, but I need only all the objects from one field (it's ManyToManyField) -
Django site is too slow with local DNS
I have a Django site hosted within the company at 192.168.1.20:80 using apache and mod_wsgi The site is very slow when I access it with a DNS given(192.168.1.5), else the site is pretty fast Tried a lot of combinations to solve the same, but unable to do it. A little help 'd be greatly appreciated. my httpd.conf LoadModule wsgi_module "c:/python/python37-32/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win32.pyd" WSGIScriptAlias / "D:/bfshello/bfshello/wsgi.py" WSGIPythonPath "D:/bfshello" WSGIPythonHome "c:/python/python37-32" Alias /media/ D:/bfshello/media/ Alias /static/ D:/bfshello/static/ <Directory D:/bfshello/media> Require all granted </Directory> <Directory D:/bfshello/static> Require all granted </Directory> <Directory D:/bfshello> <Files wsgi.py> Require all granted </Files> </Directory> -
"Cannot use None as a query value" in django search filter showing this error
I'm trying to implement search bar in django, if search item present in Database i'm displaying in web page. But its showing query returns None value. I'm new to django.Please help me in this views.py def search(request): if request.method == 'GET': form = LocForm(request.POST) if form.is_valid(): search_query = request.GET.get('search_box', None) print(search_query) FirstLoc_list_obj = FirstLoc_List.objects.filter(address__icontains=search_query) SecondLoc_list_obj= SecondLoc_list.objects.filter(address__icontains=search_query) if (len(FirstLoc_list_obj) or len(SecondLoc_list_obj)) > 0: print("Locaton Found") return render(request, 'location_test.html', {'FirstLoc_list_obj': FirstLoc_list_obj, 'SecondLoc_list_obj': SecondLoc_list_obj}) else: print("Location Not Found") return render(request, 'location_test.html', {}) return render(request, 'location_test.html', {}) return render(request, 'location_test.html', {}) urls.py urlpatterns = [ path('search/', views.search, name="search"), ] location_test.html <form type="get" action="#" style="margin: 0"> {% csrf_token %} <label>Locations:-</label> <input id="search_box" type="text" name="search_box" placeholder="Search..." > <button id="search_submit" type="submit" >Submit</button> </form> -
How to Add Selection from Selectbox To Database On Submission
I have a form which I am submitting and all of the data saves to the "Orders" model. One of the fields is an html selectbox, so when I submit the form, it does not save to the model. I am looking to figure out how I can make that dropdown selection save like the rest of the data. Forms.py class CreateOrderForm(forms.ModelForm): class Meta: model = Orders fields = ('reference', 'ultimate_consignee', 'ship_to') ADD_ORDER.HTML <div class="column_order"> <label for="form.reference">Reference ID: </label> {{ form.reference }} <br> <label> Ultimate Consignee: <br> <select class="select-css"> {% for element in objectlist %} <option value="{{ element.c_name }}">{{ element.c_name }}</option> {% endfor %} </select> </label> <br> <label for="form.ship_to">Ship To: </label> <br> {{ form.ship_to }} </div> Views.py (to illustrate how I am filling the selectbox above) def add_order(request): if request.method == "POST": form = CreateOrderForm(request.POST) objectlist = Customers.objects.all() if form.is_valid(): reference_id = form.cleaned_data.get('reference') form.save() return redirect('add_manifest') else: form = CreateOrderForm() objectlist = Customers.objects.all() context = { 'form': form, 'objectlist': objectlist, } return render(request, 'add_order.html', context) As you can see, the selectbox which I create in the .html file is not really related to the form. And so no data from the selection is being saved to the Orders model which … -
Model object is not being saved
I changed the structure of my model and I had to delete and reset the database to apply the migrations. In doing so, the way in which I was saving my object before stopped working. I have tried changing my approach by using form.instance instead of self.object but nothing happened. I am not sure if this depends on the method I'm using or if I changed something in the database. I am new to Django and I'd really appreciate some advice. views.py class SearchCreate(CreateView): model = Search form_class = SearchForm template_name = 'home.html' def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.uuid = self.object.depPlace1 + '&' + self.object.depPlace2 + '&' + str(self.object.depDate) + '&' + str(self.object.retDate) if not Search.objects.filter(uuid=self.object.uuid, user=self.object.user).exists(): self.object.save() return super(SearchCreate, self).form_valid(form) def get_success_url(self): uuid = self.object.uuid return reverse('results', kwargs={'uuid': uuid}) models.py class Search(models.Model): depPlace1 = models.CharField(max_length=10) depPlace2 = models.CharField(max_length=10) depDate = models.DateField() retDate = models.DateField() user = models.ForeignKey(User, on_delete = models.CASCADE) uuid = models.CharField(primary_key=True, max_length=200, default="SEARCH") range1 = models.IntegerField(blank=True, null=True) range2 = models.IntegerField(blank=True, null=True) def __str__(self): return self.uuid class SearchForm(forms.ModelForm): def clean(self): cleaned_data = super(SearchForm, self).clean() range1 = cleaned_data.get('range1' or None) range2 = cleaned_data.get('range2' or None) val.clean_integer(self, range1, 'range1') val.clean_integer(self, range2, 'range2') class Meta: model = … -
Django Admin javascript loads to move to bottom
I took this file from https://jsfiddle.net/emkey08/zgvtjc51 try with my admin. the code is if (!$) { $ = django.jQuery; } $(function($) { $.fn.inputFilter = function(inputFilter) { return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() { if (inputFilter(this.value)) { this.oldValue = this.value; this.oldSelectionStart = this.selectionStart; this.oldSelectionEnd = this.selectionEnd; } else if (this.hasOwnProperty("oldValue")) { this.value = this.oldValue; this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd); } }); }; }(django.jQuery)); $("#id_fin").inputFilter(function(value) { return /^\d*$/.test(value); }); Now this code loads but does not work, but works from console. There were others who faced the same issue and as the suggested answers were to move the script to end of DOM. change_form.htmlwas extended as below. {% extends "admin/change_form.html" %} {% load static %} {% block admin_change_form_document_ready %}{{ block.super }} <script type="text/javascript" src="{% static 'prop/js/number_validate.js' %}"></script> {% endblock %} Still the end result is the same. Can someone suggest something. Thanks in Advance... -
NoReverseMatch - Resetting password in Django
I have found many similar questions to this issue. This question was one of them, but it didn't solve my problem, so I will ask my own question. I'm making a password reset page on my website. But when I go to http://localhost:8000/users/reset-password and enter my email and clicks on 'Reset my password', then Django throws a NoReverseMatch error at me. The error is: NoReverseMatch at /users/reset-password/ Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. I believe there's something wrong with how I write my urlpatterns. I've tried: Making my own views and templates. Rewriting all my urlpatterns. My Code urls.py: """Defines URL Patterns for users.""" from django.urls import re_path from django.contrib.auth.views import ( LoginView, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView ) from . import views urlpatterns = [ # Login Page. re_path(r'^login/$', LoginView.as_view(template_name='users/login.html'), name='login'), # Logout Page. re_path(r'^logout/$', views.logout_view, name='logout'), # Registration Page. re_path(r'^register/$', views.register, name='register'), # Reset password page. re_path(r'^reset-password/$', PasswordResetView.as_view(), name='reset_password'), # Password reset done page. re_path(r'^reset-password/done/$', PasswordResetDoneView.as_view(), name='password_reset_done'), # Password reset confirm page. re_path(r'^reset-password/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), ] -
How to fix 'No such coulomn'?
I created a human class in the models, migrated and an error appears "No such coloumn" GIT: https://github.com/YouDontDie/tododjango1 class Human(models.Model): name = models.CharField(max_length=50, verbose_name="Имя") surname = models.CharField(max_length=50, verbose_name="Фамилия") birth = models.DateField(auto_now_add=False, auto_now=False) salary = models.IntegerField() class TodoList(models.Model): #Todolist able name that inherits models.Model title = models.CharField(max_length=250) # a varchar content = models.TextField(blank=True) # a text field human = models.ForeignKey(Human, default="general", on_delete=models.CASCADE,) created = models.DateField(default=timezone.now().strftime("%Y-%m-%d")) # a date due_date = models.DateField(default=timezone.now().strftime("%Y-%m-%d")) # a date category = models.ForeignKey(Category, default="general", on_delete=models.CASCADE,) # a foreignkey in view def index(request): #the index view todos = TodoList.objects.all() #quering all todos with the object manager categories = Category.objects.all() #getting all categories with object manager humans = Human.objects.all() if request.method == "POST": #checking if the request method is a POS if "taskAdd" in request.POST: #checking if there is a request to add a tod title = request.POST["description"] #title date = str(request.POST["date"]) #date category = request.POST["category_select"] #category human = request.POST["human_select"] #category content = title + " -- " + date + " " + category + " " + human #content Todo = TodoList(title=title, content=content, due_date=date, category=Category.objects.get(name=category), human=Human.objects.get(name=human)) Todo.save() #saving the tod return redirect("/") #reloading the page if "taskDelete" in request.POST: #checking if there is a request to delete … -
How to deploy Django application using Django-background-tasks on AWS beanstalk?
I am using Django-background-tasks in my application, it worked fine for me on my local machine, I am trying to deploy the website to AWS elastic-beanstalk. I wanted to know how to mimic the 2 cmd prompt situation in windows( one with "python manage.py runserver" and the other with "python manage.py process_tasks") in AWS. This will be a kind of parallel situation where both commands need to run simultaneously.