Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
sqlite3 works well in centos7 and python shell,but can't work in Uwsgi
I have a question need your help~ I have a django program run in a vps(centos7,django2.2),it works well with Nginx+Uwsgi. I edit three files(like a.py b.py c.py),and upload to the vps by winscp.exe,the program can't work now. I found these logs in the uwsgi.log file. File "/mnt/datasource/<privacy_hidden>/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 68, in <module> check_sqlite_version() File "/mnt/datasource/<privacy_hidden>/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 65, in check_sqlite_version raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). unable to load app 0 (mountpoint='') (callable not found or import error) I wrote "sqlite3 --version" in centos7 shell, it show version = 3.30.1 I wrote "python >>> import sqlite3 >>>print sqlite3.sqlite_version" it show version=3.30.1 I wrote "python manage.py runserver --noreload 0.0.0.0:80",it works well, no info show sqlite error. But the program can't work in uwsgi,I think the uwsgi.ini is correct. What can I do ? Thank you! -
How to save null value to date field
I have a model class League(models.Model): league = models.IntegerField(primary_key=True) season_start = models.DateField(null=True) I create objects from League model from json data which I extract from external API and save them to database. response = requests.get(leagues_url, headers = header) leagues_json = response.json() data_json = leagues_json["api"]["leagues"] for item in data_json: league_id = item["league_id"] season_start = item["season_start"] b = League.objects.update_or_create(league = league_id,season_start = season_start) Sometimes json data for season_start field have not value that is none and this none field cause error while I create league objects and save them to database. How I can solve problems caused by none values while saving them to date field -
Command failed on instance. An unexpected error has occurred [ErrorCode: 0000000001]. AWS Elastic Beanstalk
I tried following this tutorial https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html but after I execute eb create django-env I get this error: Command failed on instance. An unexpected error has occurred [ErrorCode: 0000000001]. AWS Elastic Beanstalk I found similar questions about the same issue but none of them solved the problem. I can't figure out what is wrong. I would greatly appreciate any insights. 🙂 -
How to get value from class Car to class Order
I'm need to get "Make" from class Car to "Make" in Order Class: class Car(models.Model): Make = models.CharField(max_length=64, null=True) #that i need to get in Order class Model = models.CharField(max_length=64, null=True) def __str__(self): return str(self.Make) + " " + str(self.Model) class Order(models.Model): #make = Car.Make - like that, but it is not work #make1 = models.ForeignKey(Car.Make, null=True, on_delete=models.SET_NULL) # it doesn't work either car = models.ForeignKey(Car, null=True, on_delete=models.SET_NULL) # that's work but it's give me return of __str__ def __str__(self): return str(self.Order_amount) + " " + str(self.Order_status) P.S. I just started to learn django, and I can not find any information about it -
Add more button in JS not woking
I am trying to add rows in my django template using JavaScript but it is not working like it's supposed to: HTML <html> <head> <title>gffdfdf</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="/static/jquery.formset.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <form id="myForm" action="" method="post" class=""> {% csrf_token %} <h2> Team</h2> {% for field in form %} {{ field.errors }} {{ field.label_tag }} : {{ field }} {% endfor %} {{ form.player.management_form }} <h3> Product Instance(s)</h3> <table id="table-product" class="table"> <thead> <tr> <th>player name</th> <th>highest score</th> <th>age</th> </tr> </thead> {% for player in form.player %} <tbody class="player-instances"> <tr> <td>{{ player.pname }}</td> <td>{{ player.hscore }}</td> <td>{{ player.age }}</td> <td> <input id="input_add" type="button" name="add" value=" Add More " class="tr_clone_add btn data_input"> </td> </tr> </tbody> {% endfor %} </table> <button type="submit" class="btn btn-primary">save</button> </form> </div> <script> var i = 1; $("#input_add").click(function() { $("tbody tr:first").clone().find(".data_input").each(function() { if ($(this).attr('class')== 'tr_clone_add btn data_input'){ $(this).attr({ 'id': function(_, id) { return "remove_button" }, 'name': function(_, name) { return "name_remove" +i }, 'value': 'Remove' }).on("click", function(){ var a = $(this).parent(); var b= a.parent(); i=i-1 $('#id_form-TOTAL_FORMS').val(i); b.remove(); $('.player-instances tr').each(function(index, value){ $(this).find('.data_input').each(function(){ $(this).attr({ 'id': function (_, id) { var idData= id; var splitV= String(idData).split('-'); var fData= splitV[0]; var tData= splitV[2]; return … -
Django: DatePicker with "django-widget-tweaks"
Good day, I'm trying "create" a DatePicker for one of my Inputfields in Django but it's not working! In my models.py: class Customer(models.Model): ... name = models.CharField() date = models.DateField() In my views.py: def Page(request): CustomerFormSet = modelformset_factory(Customer, fields='__all__') formset = CustomerFormSet (queryset=Customer.objects.none()) ... context = {'formset': formset} return render(request, 'app/base.html', context) In my template: {% extends 'app/base.html' %} {% load widget_tweaks %} <form actions="" method="POST"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form.id }} ... {% render_field form.name class="form-control" %} ... {% render_field form.date class="form-control" %} ... Now my first Inputfield works fine! It returns a fitting Field in Bootstraps "Form-Group"-Layout. But my InputField for Dates remains a simple TextInput with no calendar apearing to choose from. My Question is: am I doing something wrong or is it still impossible to obtain such a function in this way? Thanks and a nice evening to all of you. -
Setting the static files for Gunicorn Django deployment
I am trying to deploy a Django project with Nginx and Gunicorn, but Gunicorn cannot find the static files when I run it. My File structure is like this: user@testing:~$ ls db.sqlite3 main manage.py project static templates This is the nginx file for the project server { listen 80; server_name localhost; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/static; } location / { include proxy_params; proxy_pass http://localhost:8000; } } Settings.py file STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATIC_URL = '/static/' Thanks in advance! -
Render different templates for ListView
I have a ListView with some good functionality that i want to use from another app. The way i did it was using get_template_names. def get_template_names(self): referer = self.request.META['HTTP_REFERER'] if "/mwo/order/" in referer: return ['invent/use_part.html'] return ['invent/part_list.html'] Which i access from two different apps: path('inventory/', PartListView.as_view(), name='partlist'), ... path('mwo/order/<int:pk>/add_part/', PartListView.as_view(), name='add_part'), But it causes a bug if i use a direct link to 1st url from navbar and not from another app. Now i'm new to django and i'm pretty sure there should be a better way for this. What can i use instead of request referrer to render different template for ListView when i access it from another view. -
How to reuse effectively Django models
I have 2 type of Products , 1 is Product and 1 is sub product (child of product) but it will use same attribute of product . so my product table is like class Activity(models.Model): owner = models.ForeignKey(owner, on_delete=models.CASCADE) Name = models.CharField(max_length=50 , null=False, blank=False) and now it have like 4 tables of its properties for example I will paste 2 here. class workinfDatDates(models.Model): agenda = models.ForeignKey(Activity, on_delete=models.CASCADE) Date = models.DateField() and class BlockedDates(models.Model): agenda = models.ForeignKey(Activity, on_delete=models.CASCADE) blockDate = models.DateField() Now Sub Product is child of it like class SubActivity(models.Model): activity = models.ForeignKey(Activity, on_delete=models.CASCADE) subName = models.CharField(max_length=50 , null=False, blank=False) it should have same attributes like block dates and working dates etc . Now I should create new tables for it ? or is there any good way to use by including something to already defined tables ? -
Scale page to standard letter fomat with CSS
With regards to a webpage generated using Django, I would like to just print the page as a PDF in chrome. But when I do so, the view does not fit onto a standard 8.5/11 papersize. Is there a straightforward method of using CSS/HTML to scale items so that when you select print, it will fit everything onto a standard letter size sheet? So for desktops, if I have something like: @media only screen and (min-width: 768px) { /* For desktop: */ .col-1 {width: 8.33%;} .col-2 {width: 16.66%;} .col-3 {width: 25%;} } Would it be something like this for paper sizes? @media only screen and (min-width: 8.5in) { /* For printing: */ .col-1 {width: 8.33%;} .col-2 {width: 16.66%;} .col-3 {width: 25%;} } Or is there a much better way of accomplishing this? -
django v2.2:python manage.py runserver always reload
I have a question about django,can you help me ? I has write a django program ,it works well in my pc(windows10) and the vps(centos7,django 2.2). When I changed some code in 3 files,it works well in my pc,but can't work in the vps. I write this command in vps:" python manage.py runserver 0.0.0.0:80 ",it cames this: ***\a.py changed, reloading. Watching for file changes with StatReloader ***\b.py changed, reloading. Watching for file changes with StatReloader ***\c.py changed, reloading. Watching for file changes with StatReloader ***\a.py changed, reloading. Watching for file changes with StatReloader ***\b.py changed, reloading. Watching for file changes with StatReloader In the fact,these files only changed once,not changed after the command, It continued reloading... I must input " python manage.py runserver --noreload 0.0.0.0:80 ". I think it's something error ? Thank you! -
Django foreign key on many to many field
A company can have many job categories. A job has to be related to that company's job categories. How can I do it correctly? class Company(models.Model): job_categories = models.ManyToManyField(JobCategory,blank=False) class Job(models.Model): category = models.ForeignKey(Company, on_delete=models.CASCADE) -
Django - Datetime field shown as in admin panel
I have a model where I can create objects without a problem from the admin panel, I created a form to do the same directly within the website but I cannot manage to create an object directly from the form because of the error shown in the second picture. It is the "DateTimeField". Best case scenario, someone knows which piece of code is required for the form to display a menu ( as shown in picture 1 ) where the user can click which time and date he wants to. Thank you very much Second image: -
I cant install django using pip [closed]
I tried everything i found on the internet but it keeps showing like this enter image description here -
possible to use tuple, deconstruct with request.user, django?
Normally, I know tuple can be used as (email, username) = ('hello', 'user') that email will be equal to hello But I am wondering if I can do something like (email, username) = request.user so I do not have to keep on typing request.user and instead just use email and username like how javascript works. if I did the above, I would get an error saying TypeError: object is not iterable Thanks in advance for any suggestions and advices. -
Pythonanywhere TemplateDoesNotExist at /accounts/login/
When I run my app locally it works, but when I tried uploading it to pythonanywhere I get the following error: How do I fix this? If it will help my files are positioned like this: Music (the Django project folder) |_manage.py |_Music (the folder that contains settings file) |_App (the App itself with models, views etc. and my templates is here too) |_templates |_App |_registration |_login.html If you need more information I can upload it. -
I keep getting a naive date warning even though my model default uses timezoned date
Every time I run python manage.py test I get a warning saying that my model fields recived naive datetime: (venv) C:\Users\Philip\CodeRepos\Acacia2>python manage.py test journal.tests.test_models Creating test database for alias 'default'... C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\db\models\fields\__init__.py:1365: RuntimeWarning: DateTimeField Ledger.last_spreadsheet_update received a naive datetime (1970-01-01 00:00:00) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" C:\Users\Philip\CodeRepos\Acacia2\venv\lib\site-packages\django\db\models\fields\__init__.py:1365: RuntimeWarning: DateTimeField JournalEntry.last_integrity_check received a naive datetime (1970-01-01 00:00:00) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" However my models are configured with a default datetime that includes a timezone: class Ledger(models.Model): sort = models.PositiveIntegerField(default=0, blank=False, null=False) name = models.CharField(max_length=255) coa_sub_group = models.ForeignKey(COASubGroup, on_delete=models.PROTECT) is_reconcilable = models.BooleanField(default=False) spreadsheet_row = models.IntegerField(blank=True, null=True, unique=True) last_spreadsheet_update = models.DateTimeField(blank=False, null=False, default=datetime.datetime(1970, 1, 1, 0, 0, tzinfo=timezone('UTC'))) class JournalEntry(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=False, blank=False) date = models.DateField(null=False, blank=False) # Data integrity check fields last_integrity_check = models.DateTimeField(blank=False, null=False, default=datetime.datetime(1970, 1, 1, 0, 0, tzinfo=timezone('UTC'))) integrity_check_fail = models.BooleanField(null=False, blank=False, default=0) What could I be doing wrong? -
403 CSRF verification failed Django when refresh url?
I have create a view that takes in a post request from my /login route, but after accepting the login post request and redirecting to /, when the user refresh the browser, I get a 403 CSRF failure code. How can i optimize my code so that if the user refreshes the browser it doesn't prompt the error? view def index(request): username = password = '' if request.method == 'POST': HttpReferrer = request.session.get('HttpReferrer') if HttpReferrer == '/login': username = request.POST['username'].lower().strip() password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None and user.is_active: login(request, user) return index_(request) else: err = {"err_login": {"code": 404, "message": "The username and password combination do not match our records. Please double-check and try again."}} return render(request, 'auth/auth.html', err) -
How to get details of Current User in Django Rest Framework?
I'm working on my API based on Django Rest Framework. I've managed to add current user automatically on POST request via HiddenField. Now I want to return some additional information about current user within the GET request for blog post. I've tried to access this data from CurrentUserDefault() and via source='author.username'. First one doesn't work at all, the second option breaks on Save, because author wasn't provided in request. class BlogSerializer(serializers.HyperlinkedModelSerializer): author = serializers.HiddenField(default=serializers.CurrentUserDefault()) # author_name = serializers.ReadOnlyField(source=serializers.CurrentUserDefault().name) # author_username = serializers.ReadOnlyField(source='author.username') How can I access details of Current User and append it as read-only fields? -
Not able to match field from get_user_model in django
I am working on a Books inventory project, where users can add their books and others can see them. What I'm trying on home page to show all the books, but only the owner will see the 'Edit' and 'Delete' options. Others will see 'View Details' Option. I've used get_user_model() feature of Django to get the owner of the book when the user adds new book: ... class Book(models.Model): title =models.CharField(max_length =255) author =models.CharField(max_length =255) genre =models.CharField(max_length=255) date=models.DateTimeField(auto_now_add =True) owner =models.ForeignKey(get_user_model(),on_delete =models.CASCADE,) ... Now when I'm mapping the username of the user and the owner of the book, It's not working. This id the HTML template: ... {% for book in object_list %} <div class="card"> <span class="font-weight-bold">{{book.title}}</span> <span class="font-weight-bold">by {{book.author}}</span> <span class="text-muted">Genre: {{book.genre}}</span> <span class="text-muted">Owner: {{book.owner}}</span> <span class="text-muted">User: {{user.username}}</span> <div class="card-footer text-center text-muted"> {% if user.username == book.owner %} <a href ="{% url 'book_edit' book.pk %}">Edit</a> | <a href="{% url 'book_delete' book.pk %}">Delete</a> {% else %} <a href="#">Show Details</a> {% endif %} </div> </div> <br /> {% endfor %} ... I'm bringring both the username and owner seprately too for comparison. Still I'm getting show details for all the books. For Debugging I also tried equating both 'user.username' and 'book.owner' … -
Python Django - django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS
I am trying to populate my model of django using the faker module, however i get an error everytime i try to run the file that my django settings are not configured. My project name is index_project there are 2 apps that i have created 1. first_app 2. second_app In the first_app there are 3 models in which i m trying to push the data. Model Name : 1. Topic 2. Webpage 3. AccessRecord this is my code : import random from faker import Faker from first_app.models import AccessRecord, Topic, Webpage import os import django os.environ.setdefaults('DJANGO_SETTINGS_MODULE', 'index_project.settings') django.setup() i am working in a venv 'myFirstDjangoApp' Error Image from cmd -
How can we use same generic UpdateView for 2 urls mappings (one with pk, and one without pk)
What I am trying to achieve is to call the generic UpdateView in 2 cases. One with pk when the Submit button is clicked - This case works fine. But, I am not able to figure out how to call the same UpdateView without the pk (from navigation bar in base.html), so that just the form is displayed, and i can go ahead and edit the form and submit it. url.py path(r'update/<int:id>', views.LinkUpdateView.as_view(), name='update'), views.py class LinkUpdateView(UpdateView): template_name = 'update.html' form_class = LinkUpdateForm success_url = "/" model = Links def get_object(self): return Links.objects.get(id=self.kwargs.get("id")) models.py class Links(models.Model): id = models.CharField(max_length=50, primary_key=True) a = models.CharField(max_length=50) b = models.CharField(max_length=50) c = models.CharField(max_length=50) d = models.CharField(max_length=50) e = models.IntegerField() forms.py class LinkUpdateForm(forms.ModelForm): class Meta: model = Links fields = [ 'id', 'a', ] base.html (Navigation bar, this is where the update shud be called, without pk and form should be displayed) <li class="nav-item"> <a class="nav-link" href="{% url 'update' %}">Update</a> </li> update.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h2>Update</h2> <form method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">Update Link</button> </form> {% endblock %} I do not want to create additional url mapping to achieve this. Can … -
Ajax Form Request Not Functioning With Django
I'm new to handling AJAX requests in Django, and am following this tutorial for it. However, despite doing exactly the same thing, it does not work as expected for me. My code is below. views.py def profile_card(request): h = UserProfileInfo.objects.all() w = PlayCount.objects.all() c = ArtistCount.objects.all() y = Friend.objects.all() friend_form = forms.FriendForm() friend_search_form = forms.SearchForm() # Music Profile global e e = h[0] global high high = 0 global art_high art_high = 0 global high_artist high_artist = '' global highSong highSong = '' for x in range(0, (len(h)-1)): if str(h[x]) == str(request.user.username): e = h[x] break else: pass if len(w) != 0: for i in w: if str(i.user) == str(request.user.username): if i.plays > high: highSong = i.song high = i.plays if len(c) != 0: for f in c: if str(f.user) == str(request.user.username): if f.plays > art_high: high_artist = f.artist art_high = f.plays e.most_played_artist = high_artist e.save() else: pass # Friends ''' global friendTag friendTag = '' for r in y: if str(r.user) == str(request.user.username): friendTag = r if request.method == "POST": if str(request.POST.get("friendName")) == str(friendTag.friend): print('asakura akio') ''' global term term = [] global r r = [] if request.method == "POST": friend_search_form = forms.SearchForm(request.POST) friend_form = forms.FriendForm(request.POST) if friend_search_form.is_valid(): … -
Heroku - module not found
I'm trying to deploy a Django app to Heroku and it keeps crashing. When I read the heroku logs -tail i get: 2020-04-11T11:59:59.614465+00:00 app[web.1]: ModuleNotFoundError: No module named 'ElasticSearch' 2020-04-11T11:59:59.614808+00:00 app[web.1]: [2020-04-11 11:59:59 +0000] [12] [INFO] Worker exiting (pid: 12) 2020-04-11T11:59:59.768200+00:00 app[web.1]: [2020-04-11 11:59:59 +0000] [4] [INFO] Shutting down: Master 2020-04-11T11:59:59.768448+00:00 app[web.1]: [2020-04-11 11:59:59 +0000] [4] [INFO] Reason: Worker failed to boot. 2020-04-11T12:00:15.321075+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=esprojectsam.herokuapp.com request_id=2c8510c8-14d2-4892-867a-3e3a82707fd1 fwd="86.43.201.27" dyno= connect= service= status=503 bytes= protocol=https My procfile contsains web: gunicorn ElasticSearch.wsgi --log-file - ElasticSearch is the name of the application, caps and all. I've tried different formats for the Procfile like web: gunicorn ElasticSearch:app but none of it has worked. -
How to get parent's value from ForeignKey (in django-REST)?
I have Banks model class and Branches model class as below : class Banks(models.Model): name = models.CharField(max_length=49, blank=True, null=True) id = models.BigIntegerField(primary_key=True) class Meta: managed = False db_table = 'banks' class Branches(models.Model): ifsc = models.CharField(primary_key=True, max_length=11) bank = models.ForeignKey(Banks, models.DO_NOTHING, blank=True, null=True) branch = models.CharField(max_length=74, blank=True, null=True) address = models.CharField(max_length=195, blank=True, null=True) city = models.CharField(max_length=50, blank=True, null=True) district = models.CharField(max_length=50, blank=True, null=True) state = models.CharField(max_length=26, blank=True, null=True) my querry is as follows : branch = Branches.objects.get(ifsc=IFSC) # where IFSC is passed in URL My serializers look like below : class BranchSerializer(serializers.ModelSerializer): class Meta: model = Branches fields = '__all__' class BankSerializer(serializers.ModelSerializer): class Meta: model = Banks fields = '__all__' When i run the mentioned query, i get the following output:(example) { "ifsc": "UTIB0000007", "branch": "NEW DELHI", "address": "STATESMAN HOUSE, 148, BARAKHAMBA ROAD", "city": "DELHI", "district": "NEW DELHI", "state": "DELHI", "bank": 13 } Here 13 (in this example) is ForeignKey, But i want the value of that bank(i.e parent) instead of the key. The desired output should look like : { "ifsc": "UTIB0000007", "branch": "NEW DELHI", "address": "STATESMAN HOUSE, 148, BARAKHAMBA ROAD", "city": "DELHI", "district": "NEW DELHI", "state": "DELHI", "bank": "BANK NAME" } Please help me with this, i am new …