Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JavaScript does not find id's in Django template
I'm developing an app in Django and I have this feed.html template that loads different sections: <div class="container"> <div class="row"> {% for piece in pieces %} {% include "pieces/pieces_card.html" %} {% endfor %} </div> </div> In this pieces_card.html I want to load an script that does a 3d visualization. I have done the next thing: <div class="madeleine container" id="id-{{ piece.id }}"></div> And the problem is that the JS script fails, it prints this error MADELEINE[ERR] Target must be a valid DOM Element.. I think that this is because it is loaded before the selected id is loaded, how can make this wait until this particular element is ready? -
Django How to Deploy Project pythonanywhere.com
this is the following question of this unanswered post: Django Move Project from Windows Host to Linux Host (and Deploy) I've tried to follow this How To this time: https://tutorial.djangogirls.org/de/django_installation/ and https://tutorial.djangogirls.org/de/deploy/#registriere-dich-f%C3%BCr-ein-pythonanywhere-konto So I Uploaded my Code to Github and made it Publicly available and I created a pythonanywhere project at this URL: http://mvanthiel.pythonanywhere.com/catalog/ui/ I also created a virtual environment and created the .gitignore file. On my Windows (Dev) Host the Website does work as expected. On pythonanywhere.com it does not. On Windows Dev, I pushed the Projekt content to git like explained in the how-to. On pythonanywhere.com I installed the pip module. pip3.6 install --user pythonanywhere And then I tried to autoconfigure the rest on pythonanywhere.com with: pa_autoconfigure_django.py --python=3.6 https://github.com/HigeMynx/onboarding.git after that, the Website is Online Available but exactly like described in my previous unanswered post, Django is missing the Template only on Linux Machines and i don't know why. I can give you access to my pythonanywhere.com bash if needed, and you can look in my git code if needed. Please help me with this. -
Http response 200 1033
I'm writing an application in Django. I can't find any sources where the following response codes are explained. I know that 200 stands for OK, but what about those numbers on the right? What do they mean? "GET /people HTTP/1.1" 200 1033 "GET /people HTTP/1.1" 200 946 "GET /people HTTP/1.1" 200 1031 -
SSL certificate error when starting a new Django project inside PyCharm [duplicate]
This question already has an answer here: pip install fails with “connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)” 32 answers Steps to recreate: Select new project, django, create Error message: Could not fetch URL https://pypi.org/simple/django/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/django/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1076)'))) - skipping Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1076)'))) - skipping Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1076)'))': /simple/django/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1076)'))': /simple/django/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1076)'))': /simple/django/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate … -
ValueError: Cannot assign "'1'": "mymodel.provider" must be a "Providers" instance in django ,when save the crawled data to database using scrapy
when I save the crawl the data to the database using scrapy it shows an error like, self.field.remote_field.model._meta.object_name, ValueError: Cannot assign "'1'": "mymodel.provider" must be a "Providers" instance in django spider.py class CrawlSpider(scrapy.Spider): name = 'example' start_urls = ['https://example.com/' ] def parse(self, response): items = crawlItem() all_section = response.css(' div.brief_box ') # all_sec = response.css('div._3WlLe') news_provider = '1' # for quotes in all_sec: # dec = quotes.css('._3WlLe::text').extract() for quote in all_section: title = quote.css('.posrel img').xpath("@alt").extract() details = quote.css('p a').xpath('text()').extract() image = quote.css('.posrel img').xpath("@data-src").extract() page_url = quote.css('p a').xpath("@href").extract() items['provider'] = provider items['title'] = title items['details'] = details items['image'] = image items['page_url'] = page_url yield items item.py from scrapy_djangoitem import DjangoItem from applications.news_crawl.models import Mymodel class NewscrawlItem(DjangoItem): django_model = Mymodel models.py class Mymodel(models.Model): """ model for storing news details """ id = models.AutoField(primary_key=True) provider = models.ForeignKey(Providers, related_name='provider') details = models.CharField(max_length=1000, null=True, blank=True) page_url = models.CharField(max_length=1000, null=True, blank=True) image = models.CharField(max_length=1000, null=True, blank=True) title = models.CharField(max_length=255) class Providers(models.Model): provider = models.AutoField(primary_key=True) url = models.CharField("Website URL", max_length=255, null=True, blank=True) region = models.CharField(max_length=7, choices=REGIONS, null=True, blank=True) image = ImageField(upload_to='news_provider/%Y/%m/%d/', null=True, blank=True) -
Use a preexisting PDF file that is interactible as a form
this might be a stupid question but I want to generate a webform in django from a preexisting pdf document. what i have is a 2 page long PDF that has fillable textboxes and checkboxes/radioselect. what im looking for is a way to simply present this pdf file in its entirety to the enduser and have them fill it out as they would normally and then for it to be saved. it can be saved as either a new pdf file or have the fields saved to a database. im simply wondering if this is possible somehow -
Type annotations for Django models
I'm working on a Django project. Since this is a new project, I want to have it fully annotated with python 3.6+ type annotations. I'm trying to annotate models, but I struggle to find a good method for that. Let's take the IntegerField as an example. I see two choices for annotating it: # number 1 int_field: int = models.IntegerField() # number 2 int_field: models.IntegerField = models.IntegerField() Number 1 fails in mypy: Incompatible types in assignment (expression has type "IntegerField[<nothing>, <nothing>]", variable has type "int") Number 2 is OK for mypy, but IDE's as PyCharm are not able to resolve it and are often complaining about wrong types used. Are there any best practices to correctly annotate the models, which will satisfy mypy and IDE's? -
How to get all inherited objects of a particular object of a model in django
I have these models: class User(models.Model): name = models.CharField(max_length=255) email = models.EmailField(max_length=255) class Manager(User): experience_in_field_in_years = models.DecimalField(max_digits=5, decimal_places=2) class SalesPerson(User): current_hourly_rate = models.DecimalField(max_digits=5, decimal_places=2) work_timings = models.CharField(max_length=255) class Role(models.Model): name = models.CharField(max_length=255) class UserRole(models.Model): user = models.ForeignKey("User", related_name="user_roles", on_delete = models.CASCADE) Observer that User model is inherited by Manager, SalesPerson: there is a parent_link being generated as user_ptr_id to User table. Now, whenever I create a manager/sales_person, a user is auto created. A user can be both manager and sales_person. So, How to find/group a user with its child models? If I get a user from User, I need a way to know that he is a manager cum sales_person or only manager. -
How to post the data to the database on click (i.e non form data) from HTML page using django?
I am having the cards in the 4 pages and I am having a pagination too I want for every click of card by the user the card content should store in the database using django. For storing the form data in database using django we can do using csrf_token and post method but can you people suggest how to store the cards data in the database on every click by the user?? please refer the link given https://www.modsy.com/project/room and suggest how that cards content will be stored in database on click by the user -
Error starting DJango server when installing Mysql
I just started to create a new project with DJango. I have installed MySql and Mysql client for python. sudo apt-get update sudo apt-get install mysql-server sudo apt-get install python-mysqldb But this error happens when I try to run the server. ModuleNotFoundError: No module named 'MySQLdb' ........ django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? -
Configure one django app on seperate domain and rest on other and need to share data between apps
How can i configure a separate domain for one app and another domain rest of the apps. I tried using django sites, django-host. Please share the example -
How to get week no with year Django [ every year has 52 or 53 week in year]
trying to get week no with year def validate_week_dates(week_start_date, week_end_date): today_date_week_no = date.today().isocalendar()[1] # today week no today_date_week_no = int(today_date_week_no) -
Django- Model's Primary Key Not Functioning As Expected
I'm building a todo website with Django. I use modals so users can create events. The event is a button, so when the user clicks on it, it displays a modal with the event info. I do this by passing a primary key to the url. However, nothing is displayed. The primary key also isn't functioning when I manually go to the /view/(event-pk). I think it has something to do with data-id="{% url 'view-event' event.pk %}", but everything looks fine. I'm fairly new to django, so I apologize if its a simple answer. Html that displays the events div: <div class="col-md-6 inline mb-4"> <h3 class="ml-1">Events:</h3> <div class="events-content-section ml-2"> {% for event in events %} <div class="mb-2" style="display: flex; align-items: center;"> <button type="button" class="view-event btn btn-light" style="width: 100%;" data-id="{% url 'view-event' event.pk %}"> <span> <h4 style="float: left;">{{ event.title|truncatechars:29 }}</h4> <button type="button" class="update-event btn btn-sm btn-info ml-1" data-id="{% url 'update-event' event.pk %}" style="float: right;"> <span class="fas fa-edit"></span> </button> <button type="button" class="delete-event btn btn-sm btn-danger mr-2 ml-2" data-id="{% url 'delete-event' event.pk %}" style="float: right;"> <span class="fa fa-trash"></span> </button> </span> </button> </div> {% endfor %} </div> </div> js for the modal button (if it even matters): $(document).ready(function() { $(".create-event").modalForm({ formURL: "{% url 'new-event' %}" … -
Running tasks in Django Celery at specified time?
Snippet from my tasks.py file are as follows: from celery.task.schedules import crontab from celery.decorators import periodic_task @periodic_task( run_every=crontab(minute='15, 45', hour='0, 7, 15'), ) def task1(): send_mail() I want the script in task1() to be triggered only at 00:15, 7:15 and 15:45, whereas with the current settings it's triggered at 00:15, 00:45, 7:15, 7:45, 15:15 and 15:45. How do I do this ? Also, let me know if there is a better approach! -
How to implement updating a paragraph text or an image of the index page from the admin panel in Django?
So let's assume that I have a paragraph text and an image on my index html. How can I update it from the Django Admin panel? I have a model with two fields: image = models.ImageField(blank=True) text= models.TextField(max_length=200) I enclosed an image about the admin page. How can I update the text and image on the index page after I click save? -
In my code there is a problem in 13 line but i dont fix it
import requests from django.shortcuts import render def index(request): appid = '4d486d01bd28798a04a622360fa33694' url= 'https://api.openweathermap.org/data/2.5/weather?q={}&units=metric & appid' + appid city = 'London' res = requests.get(url.format(city)).json() city_info = { 'city': city, 'temp': res["main"]["temp"], 'icon': res["weather"][0]["icon"] } context = {'info':city_info} return render(request, 'weather/index.html',context) import requests from django.shortcuts import render def index(request): appid = '4d486d01bd28798a04a622360fa33694' url= 'https://api.openweathermap.org/data/2.5/weather?q={}&units=metric & appid' + appid city = 'London' res = requests.get(url.format(city)).json() city_info = { 'city': city, 'temp': res["main"]["temp"], 'icon': res["weather"][0]["icon"] } context = {'info':city_info} return render(request, 'weather/index.html',context) -
django not able to post data
This is my index.html <html> <body> <p>Please select Team from below:</p> <form action="teamspage/" method="post">{% csrf_token %} <select name="teams"> <option value="astra">Astra</option> <option value="everest">Everest</option> <option value="pulse">Pulse</option> <option value="gravity">Gravity</option> </select> <br><br> <input type="submit"> </form> </body> </html> views.py: @csrf_exempt def index(request): template = loader.get_template('piplanner/index.html') context = { } return HttpResponse(template.render(context, request)) def teamspage(request): if request.method == "POST": return HttpResponse("Got it new team") urlpatterns = [ url(r'^index/', include('piplanner.urls')), url(r'^admin/', admin.site.urls), url(r'^teamspage/', include('piplanner.urls')), ] On submit request is not going to teamspage view. Please let me know what is wrong with code? I am trying get method which returns form of drop down and on selection value it should go to teamspage url -
Django integration with JS
I am working in a Django app that must show an interactive visualization of different .stl files. I am using Madeleine.js and the problem is that just the last one appear. I have a principal .html with this loop: <div class="container"> <div class="row"> {% for piece in pieces %} {% include "element/element_card.html" %} {% endfor %} </div> </div> And inside the element_card.html this div tag: <div id="target" class="madeleine container"></div> A js file is called from element_card.html in order to create the visualization inside this div id="target". -
validating username while creating user in django rest framework
Here I am writing serializers for registering the users and trying to validate username with validate_username function but is not working. Exception Type: TypeError Exception Value: string indices must be integers Exception Location: ...serializers.py in validate_username, line 40 serializers.py class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer(required=False) email = serializers.EmailField(validators=[UniqueValidator(queryset=get_user_model().objects.all())]) password1 = serializers.CharField(required=True, write_only=True) password2 = serializers.CharField(required=True, write_only=True) class Meta: model = get_user_model() fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2', 'profile'] def validate_password1(self, password): validators.validate_password(password=password,user=get_user_model()) def validate_password2(self, password): validators.validate_password(password=password,user=get_user_model()) def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError("The two password fields didn't match.") return data def validate_username(self, validated_data): username = validated_data['username'] if len(username) < 6 and len(username) > 15: raise ValidationError('Username must be between 6 and 15 characters long') return username def create(self, validated_data): user = get_user_model().objects.create( username=validated_data['username'], email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], ) user.set_password(validated_data['password2']) user.is_staff = True user.save() profile_data = validated_data.pop('profile') Profile.objects.create( user=user, address=profile_data['address'], contact=profile_data['contact'] ) return user -
Django Rest Framework in production to take 500 parallel requests
I have a current flask api which is running in 'development' server and doesn't take 500 concurrent requests(it hangs) I created a flask webserver using nginx and gunicorn to take multiple requests but I need to create a solution using Django REST Framework and I have heard that Django REST Framework doesn't need a web server(nginx and gunicorn) to run concurrent requests(around 500) and handles everything on its own. So I am looking for a api solution using below mentioned tools/conditions: 1. Django REST Framework 2. Docker/ECS deployment 3. can take 500 concurrent requests Any feedback will be helpful -
How can i access the text file or dynamic css file with help of django and jinja 2 syntex?
ERROR Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/static/test/mytext.txt 'test\mytext.txt' could not be found You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. my Html code is <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Jinja2 Extd</title> </head> <body> {% load static %} <link rel="stylesheet" href="{% static 'test/style.css' %}"> <a href="{% static 'test/mytext.txt' %}">click me</a> <h1>Click Above Link!!!</h1> </body> </html> ==================================================================== i'm a beginner in django. i dont undrst how to slove dis issue .. can any1 help me on this issue...mytext.txt file saved in static/test/mytext.txt path. when i clickd on click me browser shows me above error. -
Django sessionid cookie missing and session_key is None
When an anonymous user request my page the sessionid does not exist, but if i test with a loggedin user sessionid exist? What could be the problem? After someone request my page I redirect him from HTTP protocol to HTTPS. Can it cause the issue?can this delete my sessionid? def test_anonymous_user_has_session(self): self.client.login(username=self.user.username, password='pass') # without this line sessionid does not exist url = reverse('difficult-test-select', kwargs={'questionnaire_id': self.questionnaire.id}) response = self.client.get(url, follow=True) self.assertIsNotNone(self.client.session.session_key) -
Django: How to use filter() or not based on optional param?
As you can see in this url city param is optional: re_path(r'all/(?P<category>\w+)/(?P<page_num>\w+)/?/(?P<city>\d+)?', views.show_all_objects, name="show-all-objects") views.py: def show_all_objects(request, category, page_num, city=''): if category == 'restaurants': objects = Item.objects.instance_of(Restaurant) elif category == 'sportfitness': objects = Item.objects.instance_of(SportFitness) elif category == 'carservice': objects = Item.objects.instance_of(CarService) elif category == 'beautysalon': objects = Item.objects.instance_of(BeautySalon) elif category == 'fastfood': objects = Item.objects.instance_of(FastFood) elif category == 'carwash': objects = Item.objects.instance_of(CarWash) elif category == 'fun': objects = Item.objects.instance_of(Fun) elif category == 'other': objects = Item.objects.instance_of(Other) paginator = Paginator(objects, 2) objects = paginator.get_page(page_num) context = { 'objects': objects, 'category': category, 'page_num': page_num, } return render(request, 'show_all_objects.html', context) I want if city param is set to add .filter(city=city), I can do it with if/else but it doesn't follow DRY principles. -
How to check if button hclicked and act accordingly (Django)
In my first project, I am trying to do add a new line/form whenever the user presses the 'add' button. The code I have produced is the following, and it's in the 'home.html' file: {% extends 'base.html' %} {% block content %} <h1>Create Your Meal</h1> <p>here you can select your meal and ingredients</p> <form action="/action_page.php"> Select quantity: <input type="number" name="quantity" min="1" max="5" value="0"> Select meal <select name="meals"> {% for meal in meals%} <option value="{{ meal }}">{{ meal }}</option> {% endfor %} </select> <button onclick="">Add Meal</button> {% if <br><br> <input type="submit"> </form> {% endblock %} I think has something to do with the 'onclick' mouse event attribute, but I don't know how to tackle this problem. At the moment I can only think of the following options: check if the button has been clicked with an 'if' template tag inside the template (I don't know how to write this though). do the check inside the view.py file (again, I don't know how to pass the argument). Thanks for your help -
unable to install mysqlclient for django using pip3 in ubuntu
command: sudo -H pip3 install mysqlclient Error: /usr/bin/ld: cannot find -lssl /usr/bin/ld: cannot find -lcrypto collect2: error: ld returned 1 exit status error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 Command "/usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-b0rfercj /mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-lck3vdnw-record /install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-b0rfercj/mysqlclient/ I have already install python3-dev python3-dev is already the newest version (3.6.7-1~18.04).