Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django - form.save() is not creating ModelForm
In my Django application users send feedback about task. I'm creating this form with ModelForm, and after form.save() my object is not creating and is not uploading to database. Here are my codes: views.py: @login_required(login_url='sign_in') def task_details(request, slug): if slug: task = get_object_or_404(Task, slug=slug) today = datetime.now().date() deadline = task.task_deadline.date() time_left = deadline - today form = CreateFeedbackForm() if request.method == 'POST': form = CreateFeedbackForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: form = CreateFeedbackForm() messages.info(request, 'Feedback sent.') context = { 'task': task, 'form': form, 'days_left': time_left.days } return render(request, 'task-details.html', context) models.py: class TaskFeedback(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE, null=True, blank=True) sender = CurrentUserField() is_solved = models.BooleanField(default=False) feedback_content = models.TextField(max_length=1000, null=True, blank=True) date_added = models.DateTimeField(auto_now_add = True) def __str__(self): return self.feedback_content forms.py: class CreateFeedbackForm(forms.ModelForm): class Meta: model = TaskFeedback fields = ['feedback_content', 'is_solved'] def __init__(self, *args, **kwargs): super(CreateFeedbackForm, self).__init__(*args, **kwargs) -
Django: BlockingIOError: [Errno 11] write could not complete without blocking
I have the following view in DJango: def index(request): try: if request.GET['format'] is None: # The variable print('It is None') except: print ("This variable is not defined") format_hare = 'XYZ' pass else: print ("It is defined and has a value") format_hare = request.GET['format'] url_get= request.GET['url'] print(url_get) print(format_hare) subprocess.Popen(['/usr/bin/zsh','/home/test.sh', url_get, format_hare]) html = "<html><body>"+url_get+"</body></html>" return HttpResponse(html) I keep getting the following error sometimes. Not all times. Traceback (most recent call last): File "/home/web_dev/django_download/.venv/lib/python3.7/site-packages/django/utils/datastructures.py", line 78, in __getitem__ list_ = super().__getitem__(key) KeyError: 'format' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/web_dev/django_download/download/download/views.py", line 7, in index if request.GET['format'] is None: # The variable File "/home/web_dev/django_download/.venv/lib/python3.7/site-packages/django/utils/datastructures.py", line 80, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'format' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/web_dev/django_download/.venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/web_dev/django_download/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/web_dev/django_download/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/web_dev/django_download/download/download/views.py", line 10, in index print ("This variable is not defined") BlockingIOError: [Errno 11] write could not complete without blocking [11/Apr/2020 11:56:30] "GET /run-sh?url=test.com HTTP/1.1" 500 80341 How to solve this. -
What might cause Visual Studio (2019 and 2019 Preview) to have problems using crispy forms for an otherwise working simple django application?
I've a workaround for this, but flagging as I could not find any other references to this issue. I'm following the CoreyMS Django tutorials on YouTube, to get a better grip on web applications with python (I use python for some data analytics work, mostly in Jupyter notebooks nowadays, but have a hobby project which I'd like to build). Anyway, I fired up visual studio as I was aware that it has capabilities to work with python and all seemed to progress fairly well. Corey's tutorials are excellent (clear and to the point) and while there are a few nuances different from the tools used in the video's, all was going well. However, fairly early on in the series (video 6 of 17), crispy forms are introduced. install django-crispy-forms add 'crispy_forms' to the settings.py project file. {% load crispy_forms_tags %} into the relevant template update section where the form is shown to utilise cripsy as a filter: {{ form|crispy }} All straightforward and after multiple checks, no issues with typo's or similar in the code BUT: If I run from a command prompt "python manage.py runserver" the form (a new user registration page) displays without any issue with all the … -
Django display number of objects in the account model
I am currently creating a rest api. I have an account and book model. The book model has a foreign key to the account. I want to add a number_of_books field in the account model which has an int representing how many books the user has. What is the best way to implement this? Do I need to calculate from the client side? Should I create a middleware that does this? Any help is appreciated. -
How to create ViewComponent in Django?
I want to create an html containing the Menu model, and when used, only needs {% include 'menu.html'%}, no need to pass the menu variable = Menu.object.all (). It is similar to ViewComponent in ASP.NET Core