Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django. Password authentication failed for user via docker-compose up on AWS EC2
folks! I have faced very strange issue that I cannot resolve only by my own So, what's happening. I have docekrized Django + Postgresql + celery + redis image that runs on my AWS EC2. Sometimes django container randomly raises an error: django.db.utils.OperationalError: FATAL: password authentication failed for user xxx Postgres user password, name and postgres database name stored in the env file. I've looked up at database container shell to check if user is created and it's there. Also have tried to alter role password manually from shell. And yes container have data stored in environment variables Looking forward for any help! P.S. If you need any additional information (logs, etc.) - just ask, I'll update my post -
Linking to AWS S3 direct image uploads in Django templates
I'm using AWS S3 buckets for my images in my Django project through django-storages. It's pretty clear how to show an image in a template that has been uploaded through a model ImageField. Just do e.g. <img src="{{ model.image.url }}"> What if, however, I upload an image on S3 directly (e.g. for the website logo) and want to show it in a template? Any better way to just hardcoding the absolute Amazon S3 path: <img src="https://myapp.s3.amazonaws.com/home/logo.png"> ? Some way I can use just the relative "/home/logo.png" without hardcoding the amazonaws subdomain? -
save some information from form with image like state,city,image
def seller(request): if request.method == 'POST': state = request.POST['state'] city = request.POST['city'] full_address = request.POST['fulladdress'] out = request.POST['out'] each = seller(state=state,city=city,full_address=full_address,out=out) each.save() return redirect('home') else: return render(request,'all/seller_input.html') i am tried already this code but a problem is shown seller() got an unexpected keyword argument 'state' seller is my table where the all the data store -
Django Login does not work after Deploy (pythonanywhere.com)
I'm trying to deploy my Django App for a few days. I got the Index Page Working after a lot of guessing. Finally, I found the error. But now it is still not working correctly. 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. Windows Dev On Windows Dev, I pushed the Projekt content to git like explained in the how-to. After that I tried two different ways: pythonanywhere.com 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 The Website is now Online available and I create a Django Superuser in the shell. But when I try to log in (on the website oder the admin panel) or register, I constantly get this Error Page: SelfHosted Linux VM I added a Service Account and removed and installed some packages. After that, I … -
DHTMLXGantt + Django
Im using a DHTMLX Gantt to plot data from the database via an api, like this: var endpoint = '/api/chart/data/' var label = [] var start = [] var end = [] var duration = [] $.ajax({ method: 'GET', url: endpoint, success: function(data){ labels = data.label start = data.start end = data.end duration = data.duration const input = start; // 2019-02-01 const output = input.map((str) => { const [year, month, date] = str.split("-"); return `${date}-${month}-${year}`; // 01-02-2019 }); var n = 0; var arr=[]; for ( var i=0; i<labels.length; i++){ newlab = labels[i]; newid = "id" + labels[i]; newstart = output[i]; newdur = duration[i]; arr.push({ id:newid, text:newlab, start_date:newstart, duration:newdur, progress:0.6}) }; var tasks = {data:arr}; gantt.attachEvent("onBeforeTaskChanged", function(id, mode, task){ console.log("onBeforeTaskChanged"); console.log(task); return true; }); gantt.attachEvent("onAfterTaskDrag", function(id, mode, e){ console.log("onAfterTaskDrag"); var task = gantt.getTask(id); console.log(task); }); gantt.init("gantt_here"); gantt.parse (tasks); }, error:function(error_data){ console.log("error") console.log(error_data) }}); Now I want to store the new data I get from onAfterTaskDrag to the Database with an ajax call. How would I go about doing this? Thank you for any help -
How to install older Django
I am using Pycharm and want to install an older version of Django. However, PC only seems to install V2. How can I configure Pycharm to install an older version? -
Django filters, creating date range filter forms for table
I am new in Django, have problem with creating date range filter forms and search form for table, table I make by django_tables2, here code: models.py from django.db import models class Person(models.Model): name = models.CharField('full name', max_length=50) fname = models.CharField('family name', max_length=50) birthdate = models.DateField(null=True) tables.py import django_tables2 as tables from .models import Person class PersonTable(tables.Table): class Meta: model = Person attrs = {'class': 'paleblue'} views.py from django.shortcuts import render from django.views.generic import ListView from django_tables2 import RequestConfig, SingleTableMixin from .models import Person from .tables import PersonTable def people_listing(request): table = PersonTable(Person.objects.all()) RequestConfig(request).configure(table) table.paginate(page=request.GET.get("page", 1), per_page=1) return render(request, "tutorial/index.html", {"table": table}) index.html {% load render_table from django_tables2 %} {% load static %} <!doctype html> <html> <head> <link rel="stylesheet" href="{% static 'css/screen.css' %}" /> </head> <body> {% render_table table %} </body> </html> after this I install django_filters here code: filters.py import django_filters from .models import Person class ClientFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Person fields = ['id','name','fname','birthdate'] now don't know how to make search form for my table and make form date range filtering "date from and date to? -
Related Model Column Names in django-datatables-view
I'm trying to work with django-datatables-view to add some basic filtering and sorting to my ListView. I have a Result model, which has a FK relationship to a Test model. The Result model has fields status and when, and the Test has fields 'name', 'pass_percentage', and 'maintained' (these are the only fields I'm interested in displaying, both models have additional fields. I have the following code: class TestListJson(BaseDatatableView): model = Result columns = ['test__name', 'test__pass_percentage', 'test__maintained', 'status', 'when'] order_columns = ['test__name', 'test__pass_percentage', 'test__maintained', 'status', 'when'] def get_initial_queryset(self): results = ( Result.objects.filter( canonical=True, environment__config__in=['staging', 'production'] ) .select_related('test', 'environment') .order_by('test__name', '-created_at') .distinct('test__name') .exclude(test__name__startswith='e2e') ) #print (results.first()._meta.local_fields) return results But when I view the JSON endpoint, only the status and when fields have values. How should I be passing related model field names to columns? -
pyodbc.ProgrammingError: ("A TVP's rows must be Sequence objects.", 'HY000') Django ERROR
I am trying to execute a POST request in Django to execute a stored procedure which will insert values in tables. When I am running a POST request in POSTMAN, I can see the data which I am copying using: data = request.POST.copy() as: <QueryDict: {'{\r\n\t"ID":"00000000-0000-4343-89D1-000000000000",\r\n\t"key2": "0",\r\n\t"key3": "3",\r\n\t"key4": "2000-05-01 00:00:00.000",\r\n "key5": "2017-06-08 00:00:00.000",\r\n "key6":"1",\r\n "key7":"3",\r\n "key8":"99.98",\r\n "key9":"560602",\r\n "key10":"EG2-val",\r\n "key11":"7.69999980926514",\r\n "key12":"2017-06-08 00:00:00.000"\r\n}': ['']}> when I run the same request through CURL, I can see the output of data = request.POST.copy() as: <QueryDict: {'ID': ['00000000-0000-4343-89D1-000000000000'], 'key1': ['0'], 'key2': ['3'], 'key3': etc}> From POSTMAN sent request if I copy the data into variables as: ID= data.get('ID') I am seeing none in ID after printing it while with CURL command I can see the id as 00000000-0000-4343-89D1-000000000000. The final error with both the way of sending POST request I am getting error: django.db.utils.ProgrammingError: ("A TVP's rows must be Sequence objects.", 'HY000') Internal Server Error: /setMethod/ What is this error? How to resolve it? In POSTMAN I am using raw JSON data in body and Content-type=application/x-www-form-urlencoded, charset=UTF-8 in headers. -
Django redirect URL into another URL with form
I wouldlike to redirect in another URL when I submit my form. After submit, I wouldike to have another page with something like "Hello (SummonerName) and Welcome" with URL like this : interface/main/SummonerName=(SummonerName) Here my code : forms.py from django import forms class SummonerForm(forms.Form): summoner_name = form.CharField(label='SummonerName:', max_length=100) views.py from django.http import HttpresponseRedirect from django.shortcuts import render from .forms import NameForm def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/interface/name.html') # if a GET (or any other method) we'll create a blank form else: form = NameForm() return render(request, 'interface/main.html', {'form': form}) and my main.html <form action="/SummonerName={{ current_name }}" method="post"> <label for="summoner_name">SummonerName: </label> <input id="summoner_name" type="text" name="summoner_name" value="{{ current_name }}"> <input type="submit" value="Rechercher"> </form> Thank you ! -
how to access to choices in SimpleArrayFiled with a multiple choice filed using django forms
from model.blah import Ghosts I have a model has a with a filed looks like this scary_boos = ArrayField( choice_char_field(Ghosts.TYPE_SELECTION), blank=True, null=True ) and in the admin panel, I am trying to add a form to show that field with pre-determined choices. class GhostBoosForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) print(self.fields["mortgage_type"]) self.fields["scary_boos"].widget = CheckboxSelectMultiple( choices=self.fields["scary_boos"].choices ) class Meta: model = GhostBoos fields = "__all__" however choices=self.fields["scary_boos"].choices doesn't work is there any other way to access those choices of the filed? -
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!