Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Reset model field value at start of certain time (e.g., End of Day, Start of month, etc.)
Let's say I have a model Person who has some amount of money (starting with 0): #myapp/models.py from decimal import Decimal class Person(models.Model): name = models.CharField(max_length=255) money = models.DecimalField(max_num=6, decimal_places=2, default=Decimal('0.00')) And throughout the day the user can collect money: person = Person.objects.create(name="Jeff") person.money += 100 print(person.money) # 100.00 But at the end of the day, the number should automatically go back to zero: # At 12:00 AM the next day >>> person = Person.objects.get(name="Jeff") >>> person.money = 0.00 Or say at the start of the month the person is automatically given $100 (instead of resetting). # At 12:00 AM on first day of month >>> person = Person.objects.get(name="Jeff") >>> person.money # 200.00 How would you do this on a Django model? -
Django, download static fiels
I'm new to Django and trying to create a simple button to download some files from a database. I have a simple schema class DataSets(models.Model): name = models.CharField(max_length=120) csv_blob = models.FileField(upload_to='uploads/') json_blob = models.FileField(upload_to='uploads/') And an index.html which uses data from the database {% for document in file_list %} <a href="{{ document.csv_blob.url }}" download class="btn">{{ document.name }}_CSV</a> <a href="{{ document.json_blob.url }}" download class="btn">{{ document.name }}_JSON</a> {% endfor %} I uploaded a sample entry but when I click the button to download it I get Not Found: /uploads/test_csv.txt [17/Nov/2020 19:22:11] "GET /uploads/test_csv.txt HTTP/1.1" 404 2113 What am I missing? -
"NoReverseMatch" Reverse for 'by_rubric' with arguments '('',)' not found
I'm extremely new to Python and Django. I tried to make a code from exercise work, and it was fine for a while, but since I tried to implement templates inheritance I've got this error on my homepage. Rest are working fine...for now. I tried to find solution in similar topics and django docs.,but it didn't help me. Please give me a hand on this one, cause having error at line 0 when I have only 1,2,3.. is really frustrating. Due to my lack of knowledge it's hard to understand even which file is responsible for this error. Error: NoReverseMatch at /bboard/ Reverse for 'by_rubric' with arguments '('',)' not found. 1 pattern(s) tried: ['bboard/(?P<rubric_id>[0-9]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/bboard/ Django Version: 3.1.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'by_rubric' with arguments '('',)' not found. 1 pattern(s) tried: ['bboard/(?P<rubric_id>[0-9]+)/$'] Exception Location: D:\django\venv_1\lib\site-packages\django\urls\resolvers.py, line 685, in _reverse_with_prefix Python Executable: D:\django\venv_1\Scripts\python.exe Python Version: 3.8.5 My views.py: from django.shortcuts import render from django.views.generic.edit import CreateView from django.urls import reverse_lazy from .models import Rubric from .models import Bb from .forms import BbForm def index(request): bbs = Bb.objects.all() rubrics = Rubric.objects.all() context = {'bbs': bbs, 'rubrics': rubrics} return render(request, 'bboard/index.html', context) def by_rubric(request, rubric_id): … -
Django Cannot Assign Database Relation Error
I have read many entries but couldn't find the answer. Here are my models: class Branches(models.Model): branch_name = models.CharField(max_length=200) def __str__(self): return self.branch_name class Agents(models.Model): branch_name = models.ForeignKey(Branches, null=True, on_delete=models.SET_NULL) agent_name = models.CharField(max_length=200) def __str__(self): return self.agent_name class Policies(models.Model): policy_n = models.CharField(max_length=100) account = models.CharField(max_length=100) agent_name = models.ForeignKey(Agents, null=True, on_delete=models.SET_NULL) branch_name = models.ForeignKey(Branches, null=True, on_delete=models.SET_NULL) And the code that inserts data into related tables in my view.py file: policies = pd.read('policies.xlsx') for i in policies.branches.unique(): branch = Branches() branch.branch_name = i branch.save() for j in policies.agents.unique(): agent = Agents() agent.agent_name = j agent.save() for i in range(len(policies)): policy = Policies() policy.policy_n = policies.policy_num[i] policy.account = policies.account[i] policy.branch_name = Branches.objects.get(branch_name=policies.branch[i]) policy.agent_name = Agents.objects.get(agent_name=policies.agent_name[i]) I am getting the error: ValueError: Cannot assign "(<Branches: Copenhagen>,)": "Policies.branch_name" must be a "Branches" instance. Can anybody help please. -
django 3.1 model based menu three line treemenu
1 What I want to do is menu (if menu.parentId == Null) |_menu (if menu.parentId != Null and menu.parentId == menu.Id) |_ menu (if menu.parentId == menu.Id) model view result -
Django Open rendered HTML file
Guys i want to open rendered HTML file when i am clicking a image on my HTML page. How i should use it? HTML code fragment <header> <nav class="headlist"> <a href='{% url **Link to home_view** %}'><img id = "img1" src="{% static 'css/logo.png' %}" alt="logo"></a> <ul> <li><a href="{% url **Link to about_view** %}">O nas</a></li> <li><a href="{% url **Link to contact_view** %}">Kontakt</a></li> <li><a>Zajęcia</a></li> </ul> </nav> </header> main app urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), ] pages app urls.py from django.urls import path from . import views urlpatterns = [ path('kontakt/', views.contact_view), path('o_nas/', views.about_view), path('', views.home_view), ] pages app views.py from django.shortcuts import render def home_view(reqest): return render(reqest, "index.html") def about_view(reqest): return render(reqest, "about.html") def contact_view(reqest): return render(reqest, "contact.html") -
How can i set domain name in absolute url for imagefield drf?
Now if i get some data via swagger, ImageField looks like http://api.some.com/media/picture.jpg. How can i change http://api.some.com to https://api2.some.com for all ImageField's i can get from my API? -
Is there a way to filter the form views in django to show only the ones available?
How do i span through some form fields if they are not filled in and only show the filled ones alone?? I could have used a for loop but that's a long process. Which is the easy way?? When the user fills in some of the i.feature i need to only display the filled in ones alone My html file {% for i in psts %} <div class="card p-3"> <img class="card-img-top" src="{{ i.image_p.url }}" alt=""> <div class="card-body"> <h5 class="card-title">{{ i.post_title }}</h5> <p class="card-text"> {{ i.some_info }} </p> <ul> <li> <i class="fa fa-check"></i> {{ i.feature1 }} </li> <li> <i class="fa fa-check"></i> {{ i.feature2 }} </li> <li> <i class="fa fa-check"></i> {{ i.feature3 }} </li> <li> <i class="fa fa-check"></i> {{ i.feature4 }} </li> <li> <i class="fa fa-check"></i> {{ i.feature5 }} </li> </ul> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> </div> {% endfor %} My models.py from django.db import models class posts(models.Model): post_title = models.CharField(max_length=50) image_p = models.ImageField(default='default.jpg', upload_to='post_images') some_info = models.CharField(max_length=200, blank=True) feature1 = models.CharField(max_length=100, blank=True) feature2 = models.CharField(max_length=100, blank=True) feature3 = models.CharField(max_length=100, blank=True) feature4 = models.CharField(max_length=100, blank=True) feature5 = models.CharField(max_length=100, blank=True) def __str__(self): return self.post_title -
Not able to run the coverage with pytest
Facing issues in running the pytest with coverage, I have gone through the SO posts and not able to fix this, I believe I'm missing something here.. !! Getting the following errors where users is an app of my project ModuleNotFoundError: No module named 'users' django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. My pytest.ini file contents [pytest] DJANGO_SETTINGS_MODULE = cloudstack.settings python_files = tests.py test_*.py *_test.py addopts = -v --ignore=venv --cov=. --cov-report=html I have tried adding DJANGO_SETTINGS_MODULE as environment variable too then I'm getting different error saying that cloudstack module is not found. I'm in the activated environment while performing these tests. -
urls not overlapping -- How to fix
I am trying to filter products either by brand or category but the url path will only execute path('<slug:brand_slug>/', views.product_list,name='product_list_by_brand'), since it appears first and would not execute the second. Is there a way I can probably merge both paths or cause both paths to work independently without taking order into consideration. from . import views app_name = 'shop' urlpatterns = [ path('', views.product_list, name='product_list'), path('<slug:brand_slug>/', views.product_list,name='product_list_by_brand'), path('<slug:category_slug>/', views.product_list,name='product_list_by_category'), ] Thank you in advance for your response. -
Django Tutorial Add/Remove Polls Questions
I am working through the Django tutorial of creating an app, found at: https://docs.djangoproject.com/en/3.1/intro/tutorial01/ I have completed the tutorial just as the link has instructed and I have a site that takes the polls. It runs well, however I would like to make the polls more interactive to the user by allowing users to add and remove questions on the polls page, without having to go through the admin page. How can I go about this? Thank you! -
Display & Update in same Django form
[A newbie Question] I have a form that shows the student details (query filtered by learner_code). I have an edit button that removes the "disabled" tag from fields & let user edit the form details. I have a Save button as well. I want to save the update back to the same entry in Student model. My views.py : query = None if 'learner_code' in request.GET: query = request.GET['learner_code'] try: student_details = Student.objects.get(learner_code=query) except: messages.error(request, f'Student Not Found !') return redirect('viewstudent') else: context = { 'student_details' : student_details} return render(request, 'students/viewstudent.html', context) elif 'learner_code' in request.POST : # Save the data back to the table else: return render(request, 'students/createstudent.html') My model looks like : class Student(models.Model): pay = (('FULL', 'FULL'),('EMI', 'EMI')) learner_code = models.CharField(max_length=15, null=False, primary_key=True) certificate_name = models.CharField(max_length=150, null=False) contact1 = models.CharField(max_length=10, null=False) contact2 = models.CharField(max_length=10) batch = models.CharField(max_length=10) doj = models.DateField(null=False, default=localtime(now()).date()) payment_method = models.CharField(choices=pay, max_length=4, default='FULL') total_paid = models.IntegerField(default=0) def __str__(self): return self.learner_code My forms.py is : class StudentCreationForm(forms.ModelForm): class Meta: model = Student fields = '__all__' My Template looks like : {% block content %} <div class="container mx-auto mt-3"> {% block form %} <form class="form-row mr-auto" action="" method="get"> <input type="text" class="form-control" name="learner_code" id="search" placeholder="Learner Code" style="width: … -
Django FileField uploads a "None" File to the directory?
I have a Classworks Model and in it I have added FileField to upload files in the media root, and I have tried to add a classwork using the admin, but when I checked the directory it said None!!! can someone explain why did this happen?? How can I upload it correctly and if it is uploaded correctly how can it be retrieved ?? here is the model : def classwork_add_file(instance, *args, **kwargs): return f'uploads/{instance.Type}/{instance.Teacher}/{instance.Class}/{instance.questionNumber}/' class ClassWorks(models.Model): Type = models.CharField(max_length=20, default="ClassWorks") Class = models.ForeignKey(Classes, on_delete=models.CASCADE, null=True) Teacher = models.CharField(max_length=100, null=True, blank=True) questionNumber = models.AutoField(primary_key=True) Title = models.CharField(max_length=100) Definition = models.CharField(max_length=200) File1 = models.FileField(upload_to=classwork_add_file, null=True, blank=True) File2 = models.FileField(upload_to=classwork_add_file, null=True, blank=True) File3 = models.FileField(upload_to=classwork_add_file, null=True, blank=True) File4 = models.FileField(upload_to=classwork_add_file, null=True, blank=True) File5 = models.FileField(upload_to=classwork_add_file, null=True, blank=True) DateAdded = models.DateTimeField(auto_now_add=True) DateOfSubmission = models.DateTimeField() def clean(self): if self.Teacher is None: self.Teacher = self.Class.Teacher -
Django pagination. How can I improve performance in order to load a subset of 100 from 150k rows?
I am trying to paginate over 150k records with a subset of 100 items per page, however since I am using mongo + Redis. my query handler uses .limit() to speed up the data display. so it will be 100, 200, 300 in a subset of that items per page . eg. page=1 , 100 , page=2, another 100, but the user will only see page?={page_number}. I want to make the use of from django.core.paginator import InvalidPage, Paginator or a global paginator in DRF or as last option make a custom overwrite of the class to paginate over limit, and let the user paginate in a friendly format class UserViewSet(viewsets.GenericViewSet): queryset = [] http_method_names = ['get'] def list(self, request): start_time = time.time() limit = 100 * (1-1) # this makes 0 , and freeze the database , to it needs to start from 2 cves = getCVEs(limit=1) # return a big json of data see below elapsed_time = time.time() - start_time print(elapsed_time) return Response(cves) def getCVEs(limit=False, query=[], skip=0, , cve=None, collection=None): [..] cve = col.find().sort("Modified", pymongo.DESCENDING).limit(limit).skip(skip).allow_disk_use(True) [..] return {"results": sanitize(cve), "total": cve.count()} json obj from getCVES { "results":[ { "id":"xxxxxxxx", "assigner":"xxxxxx", "Published":"2020-02-20T20:15:00", "Modified":"2020-11-17T00:15:00", "last-modified":"2020-11-17T00:15:00", "summary":"", "access":{ "authentication":"xxxxxxxx", "complexity":"xxxxxxxx", "vector":"xxxxxxxx" }, … -
'NoneType' object has no attribute 'is_staff'
I have created a login page and the related code in views.py and the associated code in views.py and the html login page is as follows: views.py: def Login_User(request): error = "" if request.method == "POST": u = request.POST['uname'] p = request.POST['pwd'] user = authenticate(username=u, password=p) sign = "" if not user.is_staff: try: sign = Customer.objects.get(user=user) except: pass if sign: login(request, user) error = "pat1" else: error = "not" elif user.is_staff: login(request,user) error="admin" else: error="not" d = {'error': error} return render(request, 'login.html', d) login.html: {% ifequal error "pat1" %} <script> alert('logged in successfully'); window.location=('{% url 'home' %}'); </script> {% endifequal %} {% ifequal error "admin" %} <script> alert('logged in successfully'); window.location=('{% url 'admin_home' %}'); </script> {% endifequal %} {% ifequal error "not" %} <script> alert('Invalid username or password'); </script> {% endifequal %} On entering a wrong username or password, it should return an alert message saying 'Invalid Username or password'. Instead it's showing an error like this: AttributeError at /login 'NoneType' object has no attribute 'is_staff' -
Django - How to properly localize a datetime based on the user timezone?
In my Django project, I'd like the date to be stored in UTC time, but then allow the users to set their own timezones. I have the timezone field in the users, and is stored correctly. The issue I'm having now is to properly transform the date to the user timezone to display it to them in notifications I send them. For example, if the datetime is stored as 22:35 20/10/2020, I'd like to display it as 01:35 21/10/2020 for a user in Qatar, since that timezone is UCT+3. This seems very simple, but I haven't managed to do it. I did this property to convert here the datetime I then send to the view: @property def full_datetime(self): import datetime dt_original = datetime.datetime(second=self.hora.second, minute=self.hora.minute, hour=self.hora.hour, day=self.fecha.day, month=self.fecha.month, year=self.fecha.year) print('Original: {}:{}, {}/{}/{}'.format(str(dt_original.hour), str(dt_original.minute), str(dt_original.day), str(dt_original.month), str(dt_original.year))) dt_localized = pytz.timezone(str(self.usuario.timezone)).localize(dt_original) print('Localized: {}:{}, {}/{}/{}'.format(str(dt_localized.hour), str(dt_localized.minute), str(dt_localized.day), str(dt_localized.month), str(dt_localized.year))) return dt_localized This particular user has a timezone of "Asia/Qatar", so it should display the original datetime +3 hours, but it displays the exact same datetime: Original: 11:33, 27/10/2020 Localized: 11:33, 27/10/2020 What is the proper way to convert a datetime to a specific timezone, or why may this not be working? -
Configuring Gunicorn and Nginx to serve Django and Vuejs
I have a project made with Django and Vuejs which works perfectly on my local computer. But when it comes to deploy it on a test EC2 (AWS) instance with gunicorn and nginx, I'm completely lost. I've tried to follow pretty much every tutorial I could find about this, and I didn't manage to display anything. First of all, I don't know if it is better to serve the static files directly (the index.html of my SPA with its css and js files) or the django application since up to now I'm using this : ... path('', TemplateView.as_view(template_name='index.html')), re_path(r'^.*$', TemplateView.as_view(template_name='index.html')) ] in my django URLs to serve index.html whatever the URL. I don't ask for something really complicated, just something minimal to make it work and then I'll be able to customize it (i guess). I'm using this script to start the app (inspired by a tutorial) : NAME="<name_of_my_app" USER="<my_user>" GROUP="<my_group>" SOCK_FILE=/<some_path>/gunicorn.sock NUM_WORKERS=3 DJANGO_DIR=/<some_path>/app_name DJANGO_SETTINGS_MODULE=<my_production_settings> DJANGO_WSGI_MODULE=<my_wsgi_module> echo "Starting" cd $DJANGO_DIR source /<path_to_virtualenv>/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE exec /<path_to_virtualenv>/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCK_FILE \ --log-level=debug \ --log-file=- PS: I don't even know what gunicorn.sock is supposed to be? I've read it is supposed to be … -
Параметры класса Meta verbose_name и verbose_name_plural
Django версия 3.1.3 пытаюсь задать параметры, для изменения отображения на админ страничке, но ничего не выходит код модели: from django.db import models class Bb(models.Model): title = models.CharField(null=True, blank=True, max_length=50, verbose_name='Описание') price = models.FloatField(null=True, blank=True, verbose_name='Цена') published = models.DateField(auto_now_add=True, db_index=True, verbose_name='Опубликовано') class Meta(): verbose_name = 'Объявление' verbose_name_plural = 'Объявления' ordering = ['-published'] На админ страничке ничего не изменяется, подскажите как исправить. Поиск не помог. -
How do you create a gitignore file in pycharm? (windows)
What i could find relating to git settings on pycharm -
Is it possible to create a unique Django path for each row in a pandas dataframe?
I have a Django project that takes information in each row of a pandas dataframe and displays the contents on the page. I'd like to separate each row of the dataframe into its own page with its own unique path. There are too many rows in the dataframe to hard code each row in the context of the views.py file. How would I go about creating a unique url path for each row? Is this even possible? -
Filter Form with regular forms,or crispy form
I have this form made with HTML(well with bootstrap) in a template, and I want to make it filter the jobs list under the form by title and by job type (full-time, freelance, etc) I tried with Django-filter and django-bootstrap-form library but I can make it look like the form in the image. please help!! -
Django: add a form into a modal (bootstrap)
i'm trying to add a button that open a modal(bootstrap) where i can add a new object car, but when i press the buttom open the service form in the modal i have a working form where i can add new car (name=create-car), how can i open the CarForm inside of the modal? The idea is that if there is no car in the select dropdown, you can add a new one in from the modal. Any help it's apriciated Car Model class Car(models.Model): brand = models.charfield(...) is_active= models.BooleanField(default=True) Service Model class Service(models.Model): car = models.ForeingKey('Car'....) name = models.Charfield() CreateView class ServiceCreateView(CreateView): model = Service form = ServiceForm ... Service HTML Template Service_form.html {% extends 'generic_base.html' %} {% load crispy_forms_tags %} <body> <script type="text/javascript"> $(document).ready(function() { $("#exampleModal").modalForm({ formURL: "{% url 'create-car' %}" }); }); </script> {%block content %} <div class="container"> <form method="POST"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-3 mb-0"> {{ form.car|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0"> <button id ="botonmodal" type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">Add New Car</button> </div> </div> <input type="submit" value="Save" class="btn btn-success" /> </form> </div> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Car</h5> <button type="button" … -
Update django from 1 to 3 in a docker container: ModuleNotFoundError: No module named 'secret_key' when building the image
I have inherited a project in Django 1 and I am trying to convert to Django 3.1.3. To complicate things a bit I am running it in a docker container I have the following code: def generate_secret_key(file_name): chars = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)" key = get_random_string(50, chars) with open(file_name, "w") as f: f.write('SECRET_KEY = "%s"' % key) try: from secret_key import * except ImportError: SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__)) generate_secret_key(os.path.join(SETTINGS_DIR, "secret_key.py")) from secret_key import * when I try building the image the following error occurs: Traceback (most recent call last): File "/mcvitty/mcvitty/settings.py", line 234, in <module> from secret_key import * ModuleNotFoundError: No module named 'secret_key' Line 234 is from secret_key import * The code was working in Django 1. If no secret key module is found, the function generate_secret_key should run generating the module secret_key.py and the program should procede smoothly but i get an error instead. What is different in Django 3.1.3? -
How can I get a user that is not the request.user in django m2m field when there's only 2 users inside the template?
I need to get a user for private message chat title from many2many field in Chat model containing 2 users: request.user and message receiver. How can I do that inside of the template? models.py class Chat(models.Model): title = models.TextField('Title', max_length=250) is_private = models.BooleanField(default=False) users = models.ManyToManyField(User, related_name='chat_users') If chat.is_private it can only have 2 users and I need to display the name of the other one for my chat heading. Currently it looks like this: {% for user in chat.users.all %} {% if user != request.user %} <a href="{% url 'chat' chat.pk %}">{{ user.name }}</a><br> {% endif %} {% endfor %} I was wondering if maybe there is a better way. -
How to send a post request via postman to nested writable serializer in django-rest-framework?
I'm really struggling with sending my data with postman in correct form to my Django backend. I followed the approach in the Django documentation for a writeable nested Seralizer and adapted it to my case. If I pass the data to my serializer via the shell, everything works and I can create the two object instances Story and File. But if I try to do the same with post man, it is not successful and receive the following error Message: Got AttributeError when attempting to get a value for field 'file' on serializer 'StoryCreateUpdateSerializer'. The serializer field might be named incorrectly and not match any attribute or key on the 'Story' instance. Original exception text was: 'Story' object has no attribute 'file'. Successfull Request via Shell: >>> data = { 'title': 'HALLLO', 'file': [ {'content': 'Public Service Announcement'}, {'content': 'Public Service Announcement'}, {'content': 'Public Service Announcement'}, ], } >>> serializer = StoryCreateUpdateSerializer(data=data) >>> serializer.is_valid() True >>> serializer.save() Not Successfull Request via Postman. Header: Content-Type: application/json. Body: Raw { "title": "Test", "file": [ { "content": "Hallo" } ] } My models and Serializers #MODELS class Story (models.Model): title = models.CharField(max_length=100,blank=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) class File(models.Model): story = models.ForeignKey(Story,on_delete=models.CASCADE, null=True) …