Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not loading css and JS
As the question implies, my django doesn't seem to be loading the js and css for my theme. This is the structure of my project: -->mysiteX ---->.idea ---->mysite ------->migrations __init__ admin.py apps.py models.py test.py views.py ---->mysiteX __init__ settings urls wsgi ----->venv -------->Lib ---------->site-packages ----------->django ------------>contrib ------------->auth -------------->templates index.html --------------->static ---------------->js ---------------->css db.sqlite3 manage This is what I have in my settings.py file BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'gradientboostMVP/templates') TATIC_URL = 'gradientboostMVP/templates/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') -
DRF: Many-to-many or Foreign Key please help to create models
I have two models, Item and Content. So what I want is Item to have many Content. class Item(models.Model): title = CharField(max_length=255) content = models.ManyToManyField('Content', blank=True) class Content(models.Model): title = CharField(max_length=255) class ItemSerializer(serializers.ModelSerializer): content = ContentSerializer(many=True) class Meta: model = Item fields = ('id', 'title', 'content',) class ContentSerializer(serializers.ModelSerializer): item_id = serializer.RelatedField(read_only=True) class Meta: model = Content fields = ('id', 'title', 'item_id',) In content serializer, note that i have given extra field item_id. Because i want to return the item Id the content is related to. But I'm not getting item_id in Content List. How do I achieve this? Am I doing something wrong? -
Third party model not shown in Django custom admin site (MaterialAdmin)
Problem: I am using django-material-admin in my Django Application. I am also using another third-party package django-eventlog. The problem is I can see the models in my application. But I can't see third party models that are defined in django-eventlog. When I try to use the plain Django Admin without django-material-admin I can see third-party models defined in django-eventlog. Possible Cause: I believe this is happening because django-material-admin uses its own implementation of AdminSite. Even if it inherits from AdminSite, the package only uses material.admin.sites.site to register admin models. And the recommendation for custom admin views is to use material.admin.decorators.register, which also uses material.admin.sites.site. The problem is that third-party packages will always use django.contrib.admin.site to register their admin models. As django-material-admin is not using this main site, it does not display all their admin views. Help Needed: What could be the potential solution for the same? I don't really want to remove django-material-admin as I am already using it intensively in my application. -
how to display specific results from the dropdown in models.py in django
I want to display only employees which emp_type is 'Doctor'? ** Here is Models.py ** class Employee(models.Model): name = models.CharField(max_length=50) emp_type_choices = [ ('Nurse', 'Nurse'), ('Doctor', 'Doctor'), ('Other', 'Other'), ] emp_type = models.CharField( max_length=6, choices=emp_type_choices, default='Nurse') def __str__(self): return self.name class Ticket(models.Model): patient = models.CharField(max_length=50) doctor = models.ForeignKey(Employee, on_delete=models.CASCADE) def __str__(self): return self.patient.name -
How to add posted time and updated time feature in Django blog post?
I am using the following approach to show when I posted a post and when I updated a post in my blog, but it is not working as expected. I added created_at and updated_at fields as below which keep tracks of when a post was posted and when it was updated. class Post(models.Model): title = models.CharField(max_length=100) # deleted for brevity created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) and then in blogs.html {% if post.created_at == post.updated_at %} Posted {{ post.created_at|naturaltime }} {% else %} Updated {{ post.updated_at|naturaltime }} {% endif %} After I create a post, it shows Posted now, but as I refresh the page then after some seconds it shows updated x seconds ago. Why is this happening and how do I solve it? Thank You -
why I have to import manually in django project?
from . import views #working urlpatterns = [ path('', views.index, name='home'), ] Above code is working but it does not work when I import like: from #project_name.#app_name.views ( import by clicking Alt + Enter ) I have created views.py inside app and app is inside project. why this is happening? I'm a beginner and i like to import by clicking Alt + Enter. How can i fix this problem? -
how to use django achieve auto login in a website
I'm doing a website to collect my partners' request.And i want the web can identify who login the web once he/she open my website. For example,you open an website,and you can see the greeting'Welcome,XXX(your name)'.What I want is this,to identify automatically a username or a hostname not manual input username/pwd.Could I get these in the http request headers?or other header info send to server?My friend say to get environment variable can do this,but i don't know how to.I tried request.user or request['username'],but i can't get username.It return nothing. Purpose of the auto function isn't to get user info from a existed user DB,and also i don't have one.But hope to get client username or his/her PC's hostname. By now I don't know how to do this.Possible solution I think can work are: 1.Use cookie.I had try this but not success.I find no info in the cookie my brower send to server,i only can find is a crsftoken code and i don't know how to go on with this situation.I try to go through request.META['somefield'] to get some info,I can find many info only escape username,hostname,remote_name.Result also returns nothing. 2.Use session.I think there may have username/hostname in session.But i don't know … -
Django DateTimeField and datetime.datetime.now() giving different times
I have a model where I want the name field to be a string representation of the timestamp, and another field to be the actual time stamp. Here is my model code: from django.db import models from datetime import datetime class Image(models.Model): name = models.CharField(max_length=255, default=datetime.now().strftime("%Y%m%d-%H%M%S")) create_date = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to="images/") Then I go in the django shell and enter this: >>> import models >>> models.Image(image='images/rock.png').save() This works but the only problem is the two times do not align. For example, I get name = 20191201-143119 and create_date = 2019-12-01 14:32:11.445474. How can I get these two datetimes to be the same? -
is it dangerous to use django 3 for production
you know Django is pre-release of Django and in Django's website wrote This release is only for users who want to try the new version and help identify remaining bugs before the 3.0 release. I want to create my new shopping website with Django 3 how much dangerous is that? -
Error Message in request.POST Form not showing up
I've written a normal contact POST-form: def emailView(request): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): context = {'form': form} return redirect('success_contact') else: form = ContactForm() Then in my form this template tags: <form id="contact_form_post" method="post"> {% csrf_token %} {{ form.name }} {{ form.name.errors }} {{ form.message }} {{ form.message.errors }} <div class="form-actions"> <button type="submit">Submit</button> </div> </form> With this setup, no error message is showing up if the required fields are not filled out. When I'm changing the last line in emailView into form = ContactForm(request.POST) every error message shows up before submitting -> "This Field is required". -
Tables with editable cell in django
How can i make a table view with input boxes and after adding all rows finally save the data together in django. I am using bootstrap table in HTML and dict object is renter on request. i want to build a form with editable table having multiple rows -
New way of implementing enumeration type (choices) in Django 3.0
I've seen a new way to implement enumeration type in the upcoming Django 3.0. The given example is: class Student(models.Model): class YearInSchool(models.TextChoices): FRESHMAN = 'FR', _('Freshman') SOPHOMORE = 'SO', _('Sophomore') JUNIOR = 'JR', _('Junior') year_in_school = models.CharField( max_length=2, choices=YearInSchool.choices, default=YearInSchool.FRESHMAN, ) I used to put my enumerate list in the __init__.py to have a more readable code in models.py because the list (like status or other things can be long). So I was wondering if this new way of implementing could be safely rewritten as following: from my_app import YearInSchool class Student(models.Model): @cached_property def years_in_school_choices(): return YearInSchool Not sure here neither if cached_property is relevant. -
Got an error Django internal server error
Got this error while trying to create a view on Django: raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to h ave any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. Tried many solutions online both on deleting one of the url.py folders but none worked out -
how to auto login to a my django app with old credentials
I want to login to my django app using details from another web applications Have tried googling but no clear solution. I thought a rest api could do. -
Django search on date field with MySQL DB
I have a date field in one of my models. I want to develop a search service, which in user sends a query param as search key, for example '?search=2018' and the response would be all rows in data base that their date's year is 2018. Or if the user sent '?search=11' the response would be all rows that either their date's month is 11, or their date's day is 11. I am using django 2 and MariaDB version 10.3.18 -
When i deploy my django app to heroku the site stops working
i have done everything right following a youtube tutorial(https://www.youtube.com/watch?v=MoX36izzEWY) and it's alright but when i push my project to heroku the site stops working and when i run the heroku logs --tail command this is what it gives to me: 2019-12-01T11:40:18.921974+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 358, in import_app 2019-12-01T11:40:18.921976+00:00 app[web.1]: mod = importlib.import_module(module) 2019-12-01T11:40:18.921978+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/init.py", line 126, in import_module 2019-12-01T11:40:18.921980+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2019-12-01T11:40:18.921982+00:00 app[web.1]: File "", line 994, in _gcd_import 2019-12-01T11:40:18.921984+00:00 app[web.1]: File "", line 971, in _find_and_load 2019-12-01T11:40:18.921986+00:00 app[web.1]: File "", line 941, in _find_and_load_unlocked 2019-12-01T11:40:18.921988+00:00 app[web.1]: File "", line 219, in _call_with_frames_removed 2019-12-01T11:40:18.921990+00:00 app[web.1]: File "", line 994, in _gcd_import 2019-12-01T11:40:18.921992+00:00 app[web.1]: File "", line 971, in _find_and_load 2019-12-01T11:40:18.921994+00:00 app[web.1]: File "", line 953, in _find_and_load_unlocked 2019-12-01T11:40:18.922001+00:00 app[web.1]: ModuleNotFoundError: No module named 'BlogProject' 2019-12-01T11:40:18.922117+00:00 app[web.1]: [2019-12-01 11:40:18 +0000] [10] [INFO] Worker exiting (pid: 10) 2019-12-01T11:40:18.950480+00:00 app[web.1]: [2019-12-01 11:40:18 +0000] [4] [INFO] Shutting down: Master 2019-12-01T11:40:18.950634+00:00 app[web.1]: [2019-12-01 11:40:18 +0000] [4] [INFO] Reason: Worker failed to boot. 2019-12-01T11:40:19.030596+00:00 heroku[web.1]: Process exited with status 3 2019-12-01T11:40:21.000000+00:00 app[api]: Build succeeded 2019-12-01T11:40:24.514282+00:00 heroku[web.1]: Starting process with command gunicorn BlogProject.wsgi 2019-12-01T11:40:27.042695+00:00 heroku[web.1]: State changed from starting to crashed 2019-12-01T11:40:26.888453+00:00 app[web.1]: [2019-12-01 11:40:26 +0000] [4] [INFO] Starting gunicorn 20.0.4 … -
Get available time slots for appointment booking using Django REST framework
I am trying to develop an API for scheduling appointments for several salons. Right now I have models and serializers for the Salon and the Appointment. All appointments can have different durations. The Appointment model looks like this: class Appointment(models.Model): date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() salon = models.ForeignKey(Salon, on_delete=models.CASCADE) How can I return all salons and their available time slots (no appointment at that time) for a given date. So say if a salon is open from 10:00-16:00 and has only one appointment from 11:00-11:30 we would get something like: { "id": 3, "name": "My Salon", "city": "London", "time_slots": [ { "date": "2019-12-01", "start_time": "10:00:00", "end_time": "11:00:00", }, { "date": "2019-12-01", "start_time": "11:30:00", "end_time": "16:00:00", } ] } Right now the only way I can think of is by adding a new TimeSlot model with Salon as Foreign key and saving all time slots in the database and changing them once an appointment is made? However, this does not seem very efficient. Is there a better way of calculating and returning the time slots? -
Am working on a site using django framework and i got this AttributeError telling me 'str' object has no attribute 'get'
`AttributeError at /polls/ 'str' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:8000/polls/ Django Version: 2.0.2 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'get' Exception Location: C:\Python34\lib\site-packages\django-2.0.2-py3.4.egg\django\middleware\clickjacking.py in process_response, line 26 Python Executable: C:\Python34\python.exe Python Version: 3.4.1 Python Path: ['C:\Users\WUESE PHILIP\Desktop\vibezt', 'C:\Python34\python34.zip', 'C:\Python34\DLLs', 'C:\Python34\lib', 'C:\Python34', 'C:\Python34\lib\site-packages', 'C:\Python34\lib\site-packages\setuptools-33.1.1-py3.4.egg', 'C:\Python34\lib\site-packages\django-2.0.2-py3.4.egg', 'C:\Python34\lib\site-packages\pytz-2019.3-py3.4.egg']` polls urls.py from django.urls import path from . import views `urlpatterns = [ path('', views.index, name='index'), ]` views.py from django.shortcuts import render `from django.http import HttpResponse def index(request): return("<h2>Welcome to my First Python Django Project</h2>")` vibezt urls.py `from django.contrib import admin from django.urls import include, path` `urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ]` -
Is there a way of printing user id in uwsgi django log?
I think it would be very convenient to have a user-id in the uwsgi request/response log. I know there's logformat option available in uwsgi. And I don't think user-id could be handled by logformat since it's not something uwsgi natively knows, it's app (my case django)'s data that runs inside uwsgi (if that expression makes sense) On the other hand, there's django logger's format and I guess I could make a middleware that prints a request/response data with user-id although this would be duplication of what uwsgi itself is logging. (although uwsgi's log don't have user-id) -
Call custom function after pagination
I want to call my function when user clicked on pagination button "Next" or "Previous" on this page http://junjob.ru/ I created soulution --- overloaded paginate_queryset method in views.py How can I determine when the user clicked “Next” and when “Previous” ? views.py class HomePageView(ListView): model = Vacancy template_name = 'vacancy_list/vacancy_list.html' paginate_by = 5 page_kwarg = 'vacancy' context_object_name = 'vacancies' def paginate_queryset(self, queryset, page_size): print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx ", self.request.user) """Paginate the queryset, if needed.""" paginator = self.get_paginator( queryset, page_size, orphans=self.get_paginate_orphans(), allow_empty_first_page=self.get_allow_empty()) page_kwarg = self.page_kwarg page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1 try: page_number = int(page) except ValueError: if page == 'last': page_number = paginator.num_pages else: raise Http404(_('Page is not “last”, nor can it be converted to an int.')) try: page = paginator.page(page_number) return (paginator, page, page.object_list, page.has_other_pages()) except InvalidPage as e: raise Http404(_('Invalid page (%(page_number)s): %(message)s') % { 'page_number': page_number, 'message': str(e) }) vacancy_list.html <!-- Paginator --> <div class="container" style="font-size: 2rem;"> <div class="row justify-content-center"> <ul class="pagination"> {% if page_obj.has_previous %} <li class="page-item"><a class="page-link" href="?vacancy={{ page_obj.previous_page_number }}">Previous</a></li> {% else %} <li class="page-item disabled"> <span class="page-link">Previous</span> </li> {% endif %} <li class="page-item disabled"> <span class="page-link">Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</span> </li> {% if page_obj.has_next %} <li class="page-item"><a class="page-link" href="?vacancy={{ page_obj.next_page_number }}">Next</a></li> {% else … -
Always getting this AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200)
I'm very new in django, and currently was following a tutorial and I was trying to test users are listed on user page. So I setup test_admin.py. And i get an AssertionError 302 != 200. Below are my test_admin.py from django.test import TestCase,Client from django.contrib.auth import get_user_model from django.urls import reverse class AdminSiteTests(TestCase): def setUp(self): self.client = Client() self.admin_user = get_user_model().objects.create_superuser( email='admin@gmail.com', password='092100027h' ) self.client.force_login(self.admin_user) self.user = get_user_model().objects.create_user( email='test@gmail.com', password='092100027h', name='Test User Full Name' ) def test_users_listed(self): """ Test that users are listed on user page """ url = reverse('admin:core_user_changelist') res = self.client.get(url) self.assertContains(res, self.user.name) self.assertContains(res, self.user.email) and this is my admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from . import models class UserAdmin(BaseUserAdmin): ordering = ['id'] list_display = ['email', 'name'] admin.site.register(models.User, UserAdmin) and this is my error Creating test database for alias 'default'... System check identified no issues (0 silenced). F.... ====================================================================== FAIL: test_users_listed (core.tests.test_admin.AdminSiteTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/app/core/tests/test_admin.py", line 28, in test_users_listed self.assertContains(res, self.user.name) File "/usr/local/lib/python3.7/site-packages/django/test/testcases.py", line 446, in assertContains response, text, status_code, msg_prefix, html) File "/usr/local/lib/python3.7/site-packages/django/test/testcases.py", line 418, in _assert_contains " (expected %d)" % (response.status_code, status_code) AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected … -
How to filter foreign key item?
I am not sure if I put correct title for what I need but here is the thing. I have two model. class Device(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) device_name = models.CharField(max_length=200, null=True, blank=True ) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.device_name) class StatusActivity(models.Model): OFFLINE = 1 ONLINE = 2 STATUS = ( (OFFLINE, ('Offline')), (ONLINE, ('Online')), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) device_id = models.ForeignKey(Device, related_name='status_activity', on_delete=models.CASCADE) status = models.PositiveSmallIntegerField(choices=STATUS) modified_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.device_id) I can get a list of StatusActivity and Device seperately. But what I need is latest status for every device. Devices: Id Created_At Device_name 5b9bbd0f02f8428ca69a582a491f0751 2019-11-30 15:38:37.076440 Temperature Device 17c1ac3ed05844cd879c218effaba15e 2019-11-30 15:39:14.716443 Humidity Device a0ca21a555b246b99be965db4493276f 2019-11-30 15:39:27.822114 Motion Device StatusActivities: Id Status Modified_at Device_id_id 350fed049ba04541a7b6d81932d5824b 2 2019-11-30 15:39:39.849491 5b9bbd0f02f8428ca69a582a491f0751 e4f317b56bbb46eb9309ba77da692af0 1 2019-11-30 15:39:47.912013 5b9bbd0f02f8428ca69a582a491f0751 e0a021dd53734d3b9a15e53ad93bbb28 2 2019-11-30 15:41:04.891823 5b9bbd0f02f8428ca69a582a491f0751 1c12c64708234df6992883b377d3102f 2 2019-11-30 17:12:58.336177 17c1ac3ed05844cd879c218effaba15e 8d280d522baa449588b9a9ab67ed7bae 1 2019-11-30 17:13:05.987487 a0ca21a555b246b99be965db4493276f Example result should be this: ID device_name Status Modified_at 5b9bbd0f02f8428ca69a582a491f0751 Temperature Device 2 2019-11-30 15:39:39.849491 17c1ac3ed05844cd879c218effaba15e Humidity Device 2 2019-11-30 17:12:58.336177 a0ca21a555b246b99be965db4493276f Motion Device 1 2019-11-30 17:13:05.987487 -
How do I get an image to render in weasyprint using a Django Template in production?
I am trying to get an image to render using Weasyprint with Django in production. I can get it to work with debug=True on my local machine, but cannot get it to work on my apache server with debug=True or False or with debug=False on my local machine. It's like it can't render out the url for the image source properly. The PDF is returned properly, and if I stick the {% static 'image.png' %} in the template as text it comes back with: /static/img/image.png What exactly am I missing? My filestructure is as follows: www |__app_root | |__static | | |__img | | |__image.png | |__urls.py | |__views.py |__settings_root |__settings.py settings.py DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'app_root/static') views.py html_string = template.render(context) pdf_file = HTML(string=html_string, base_url=request.build_absolute_uri('/')).write_pdf(stylesheets=[CSS(settings.STATIC_ROOT + '/print.css')]) # have also tried request.build_absolute_uri() without the '/' template.html {% load static %} <img src="{% static 'image.png' %}"/> Apache Configuration - default-ssl.conf & 000-default.conf Alias /static /var/www/app_root/static <Directory /var/www/app_root/static> Require all granted </Directory> Error Message "GET /static/img/image.png HTTP/1.1" 404 77 -
django for python set up issues
I'm not familiar with using command prompt and having trouble at the start of the django for python set up process which i'm reading here: https://docs.djangoproject.com/en/2.2/intro/tutorial01/ My problem appears to be the 'python' command doesn't work (please see my command prompt screen shot). I tried adding it into 'System variables' in the 'Environment Variables' as shown in the other screen shot. Is there something i have done incorrectly here? Also although i can get the create the initial project the only place i can create it is in the 'c:\Python\Lib\site-packages\django\bin' folder because i have to be looking at this folder in order to run the django-admin.py file. I think the second issue is related to the first issue though i.e. if the 'python' command worked i could just run 'python django-admin.py startproject mysite' while my directory path is set to where ever i want the project to be created. I expect i could simply move the mysite folder to where i want it but i feel i need to understand why this all isn't working as expected before moving on. -
django orm: select_related, fooling reverse foreign key with a fake foreign key addition to the model, what can go wrong?
I am trying to learn how to use Django's ORM for more advanced queries, instead of using raw sql. select_related makes joins to reduce database hits, in principle it could make the joins that I would do manually. But there is a problem: It doesn't use reverse foreign key relationships to make the sql. For the schema I have this is a nuisance. I have found what looks like a surprisingly easy work around, and I'm worried that it will be incorrect in ways I don't understand. I'm using a legacy DB, and it is read-only, and therefore unmanaged by the ORM, and there are no consequences for cascade settings. I have made models for its tables via manage.py analysedb which did a very good job; I have a 6000 line model file, and only needed to spend ten minutes fixing things. One tweak I did was a hack to fool select_related by creating a foreign key relationship which is actually a reverse FK relationship. This means I have two entries in my model pointing to the same database column, which is the primary key (correct) and also now a foreign key. I exploit the "new" column in select_related. The …