Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show django logging and error log in Cloud Run's log?
I'm using Django, uwsgi and nginx in Cloud Run. A Cloud Run service can't show django logging and error log. That's why Error Report can't use ,too. Cloud Run log is like this. This is my settings. Django settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'local': { 'format': "[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s" }, 'verbose': { 'format': '{message}', 'style': '{', }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'local', }, }, 'root': { 'handlers': ['console'], 'level': 'WARNING', }, 'loggers': { 'users': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, }, 'django': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, }, 'django.db.backends': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, }, 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } } } uwsgi.ini [uwsgi] # this config will be loaded if nothing specific is specified # load base config from below ini = :base # %d is the dir this configuration file is in socket = %dapp.sock master = true processes = 4 [dev] ini = :base # socket (uwsgi) is not the same as http, nor http-socket socket = :8001 [local] ini = :base http = :8000 # set the virtual env … -
django display objects on all url
MyViews: MyHTMLCode: MyUrl: [The Proablem is do not filter by category name][4] -
why django is using email host user as (from email)
The problem is that (from email) is being used as default email host user. So how to solve this problem? Django version 2.2 contact html template views.py for contact settings.py in Django My contact page The email -
“” value has an invalid format. It must be in the format of YYYY MM DD HH:MM
models.py from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now class recommend(models.Model): sno = models.AutoField(primary_key=True) comment= models.TextField() user = models.ForeignKey(User,on_delete=models.CASCADE) timestamp= models.DateTimeField(default=now) def __str__(self): return self.recommend[0:20] + "..." + "by" + self.user.username error importing signals Operations to perform: Apply all migrations: admin, apps, auth, blog, contenttypes, home, sessions, verify_email, videos Running migrations: Applying home.0004_alter_contactme_timestamp...Traceback (most recent call last): File "/storage/emulated/0/imaginecode/manage.py", line 22, in <module> main() File "/storage/emulated/0/imaginecode/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/db/migrations/migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 244, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/db/backends/sqlite3/schema.py", line 140, in alter_field super().alter_field(model, old_field, new_field, strict=strict) File "/data/data/com.termux/files/usr/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 608, in alter_field self._alter_field(model, old_field, new_field, old_type, … -
Filter nested serializers in Django Rest Framework
I have several nested serializers for an institution examination module. I began with term -> class -> student ->classes -> subjects -> exam_categories ->exam_subcategories -> marks. I want to filter the marks in the exam_subcategories inorder to be the marks of an indivual student. Currently each student is returning all the marks list. I have been going through several solutions online but it has not provided me with a way of solving it. Here is the sample models and serializers and output. I want to be able to filter the marks_exam_type to return only that student's marks in that term in that subject in that class in that exam subcategory (Only one object in marks_exam_type) The models user are class Classes(models.Model): year = models.ForeignKey(AcademicYear,on_delete=models.CASCADE) current_term = models.ForeignKey(YearTerm,related_name='current_term',on_delete=models.CASCADE,null=True) terms = models.ManyToManyField(YearTerm,related_name="class_terms",through='YearTermClasses') course = models.ForeignKey(Course,on_delete=models.CASCADE) course_year = models.ForeignKey(CourseYear,on_delete=models.CASCADE,null=True) class_name = models.CharField(max_length=255) class_code = models.CharField(max_length=255) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) school = models.ForeignKey(School,on_delete=models.CASCADE) active = models.BooleanField(default=False) def __str__(self): return self.class_name class Meta: ordering = ['-year__start_date'] unique_together=['year','current_term','course','course_year','class_name'] Marks model class Marks(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) subject = models.ForeignKey(CourseSubject,related_name='subject_marks', on_delete=models.CASCADE) term = models.ForeignKey(YearTerm,related_name="terms_marks",on_delete=models.CASCADE) student = models.ForeignKey(Student,related_name='marks',on_delete=models.CASCADE) exam = models.ForeignKey(ExamSubCategory,related_name='marks_exam_type',on_delete=models.CASCADE) exam_category = models.ForeignKey(ExamCategory,on_delete=models.CASCADE,related_name="marks_exam_category",null=True) classes = models.ForeignKey(Classes,on_delete=models.CASCADE) marks = models.IntegerField() created_by = models.ForeignKey(Profile, on_delete=models.CASCADE) created_date = … -
I have problems to displaying a from of type ModelForm in Django
I'm trying a tutorial about Django forms and drop-down lists but I can't manage to show the form, maybe the tutorial is about an old version of Django, but I tried everything, I don't understand what I'm missing. First my Forms.py from django import forms from .models import Person, City class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('name', 'birthdate', 'country', 'city') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['city'].queryset = City.objects.none() The model: from django.db import models class Country(models.Model): class Meta: db_table = 'countries' name = models.CharField(max_length=30) def __str__(self): return self.name class City(models.Model): class Meta: db_table = 'cities' name = models.CharField(max_length=30) state_id = models.BigIntegerField(null=True) country = models.ForeignKey(Country, on_delete=models.CASCADE) def __str__(self): return self.name class Person(models.Model): class Meta: db_table = 'people' name = models.CharField(max_length=100) birthdate = models.DateField(null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name The template: {% block content %} <h2>{% trans "Person Form" %}</h2> <form method="post" novalidate> {% csrf_token %} <table> {{ form.as_table }} </table> <button type="submit">Save</button> <a href="{% url 'person_changelist' %}">Nevermind</a> </form> {% endblock %} And finally View.py from django.shortcuts import render from django.views.generic import ListView, CreateView, UpdateView from django.views.generic.edit import FormView from django.urls import reverse_lazy from .models import Person from … -
how to use {% url %} inside a custom filter in django for displaying a hashtag
Hi i want to display a #hashtag with url in django in the post content.for that i created a simple customer filter.but i have a problem for using the "url tag". tag_name.py: @register.filter(name='mention',is_safe=True) @stringfilter def mention(value): res = "" my_list = value.split() for i in my_list: if i[0] == '#': if len(i[1:]) > 1: <!-- my problem is here --> i = f"<a href="{% url 'recommendation_posts' %}?q={i}&submit=Search">i</a>" res = res + i + ' ' return res html: <p> {{ post.content|mention|safe }}</p> by example:when someone write "I like #python" i want to be rendered as "I like #python" my main problem is this {% url %} is not working inside the templatetags.How can i achieve it thanks. -
React Native - Sending token to Django server
So I have this react native code that sends a token in string format, yes I've checked that var token = getCurrentUser() is a string and I've console.log it to ensure it is a JWT token as well. But on the Django side when I check request.headers.get('Authorization', None) it outputs: 'Bearer [object Object]' what's going on? React Native Code const getPosts = () => { var token = getCurrentUser(); const config = { headers: { Authorization: `Bearer ` + token } }; axios .get(`${url}/posts`, config) .then(response => { console.log(response) setData(response.data); }) .catch(error => { console.log(JSON.stringify(error)); }); } -
How to join multiple model with both onetoone and one to many using select_related?
i have few models namely class Alpha(models.Model): name = models.CharField() class XXX(models.Model): owner = models.ForeignKey(Alpha) class YYY(models.Model): name = models.OneToOneField(Alpha) Now while doing select_related like this test = Alpha.objects.filter(id=pk).select_related('XXX') It gives me Invalid field name(s) given in select_related, choices are YYY I understand that YYY is at OneToOne, so its showing up - but is there a way to fetch XXX also ? or should i use "prefetch_related". But i dont wanna use prefetch as its just making slow queries and meanwhile i have 7 models which needs to be select_related :( -
Deploying Django @ Heroku - Windows Libraries
I'm using some python libraries on my Windows localhost (Django) server and I'd like to host my application online. My app is based on reading Excel files and providing this data on the screen. import win32com.client as win32 import pythoncom I suppose this are WindowsOS libraries only and I couldn't deploy @ Heroku, for being a LinuxOS server. Am I correct? If so, are there other good free Windows servers? Thank you! -
Django framework and chatbot development and integration
I have a question related to Python/Django/Chatbot/Web Development. I want to make a website (Django framework) with an integrated chatbot (using Rasa framework probably). Is that a good approach to use the above stacks? Motive : 1) Website is just for chatbot integration, a generic marketing webpage. 2) Chatbot needs to be basic to direct people to the service they need to go to and should be able to provide link for video calls to the concerned department if needed, store data of the customer and answer basic/generic questions. This is my first attempt at working in the web development/chatbot field. -
How to add multiple values to my field using ForeignKey (Django models)?
I have this models: class Video(models.Model): category = models.ForeignKey('Category', on_delete=CASCADE) class Category(models.Model): category = models.CharField(max_length=100) Rigth now my Video objects can only have 1 category selected. I 'd like to be able to have multiple categories for my category field. Is this possible using ForeignKey? i.e TABLE VIDEO: Video1.category = "drama", "terror" TABLE CATEGORY: Category1.category = "drama" Category2.category = "terror" -
Routing in Django
urls.py from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('page1/', page1.hello), ] page1.py from django.http import HttpResponse def hello(request): text = """<h1>welcome to my app !</h1>""" return HttpResponse(text) Pretty basic. The page1.py lies in the same directory as urls.py. The examples i found online, use a second urls.py file and an some includes command... do i have a typo or do i need more than that two files? -
How to pass file directly from the python file to detect macro using oletools?
I did the research for detecting the macros and I found oletools. Source code of oletools can be found in https://github.com/decalage2/oletools/tree/master/oletools. oletools uses the command line to execute the program but I am trying to modify the source code so, I can pass the file directly from the python file and get the result. Mraptor.py does the work to detect macros. How to modify the "usage" part to run directly from the python file instead of the command prompt. Here is the source code of mraptor.py Link: https://github.com/decalage2/oletools/blob/master/oletools/mraptor.py #!/usr/bin/env python """ mraptor.py - MacroRaptor MacroRaptor is a script to parse OLE and OpenXML files such as MS Office documents (e.g. Word, Excel), to detect malicious macros. Supported formats: - Word 97-2003 (.doc, .dot), Word 2007+ (.docm, .dotm) - Excel 97-2003 (.xls), Excel 2007+ (.xlsm, .xlsb) - PowerPoint 97-2003 (.ppt), PowerPoint 2007+ (.pptm, .ppsm) - Word/PowerPoint 2007+ XML (aka Flat OPC) - Word 2003 XML (.xml) - Word/Excel Single File Web Page / MHTML (.mht) - Publisher (.pub) Author: Philippe Lagadec - http://www.decalage.info License: BSD, see source code or documentation MacroRaptor is part of the python-oletools package: http://www.decalage.info/python/oletools """ # === LICENSE ================================================================== # MacroRaptor is copyright (c) 2016-2021 Philippe Lagadec … -
ADminlte3 , Django admin inline template messed up
I installed Adminlte3 for admin of Django, but when I use inline , its messed up like picture , and fields are not in column , [enter image description here][1] funny. [1]: https://i.stack.imgur.com/uZzHk.png -
APScheduler in Django - I can't connect to postgres
I have django project and I would like use persistent job store (postgres) for my APScheduler jobs Here is scheduler.py: from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore DATABASE_URL = "postgresql://localhost/auctions_site_apscheduler_jobs?sslmode=disable" jobstores = { 'default': SQLAlchemyJobStore(url=DATABASE_URL) } scheduler = BackgroundScheduler(jobstores=jobstores) When I run python manage.py runserver I get this error: django.db.utils.OperationalError: server does not support SSL, but SSL was required What I am doing wrong? -
how to combine two QuerySet obtain from loop in django
i have two QuerySet obtain from loop in django i want to combine in one QuerySet this is the code for m in [1,2]: gpu=Gpu.objects.filter(brand=m) print(gpu) and the result is <QuerySet [<Gpu: GIGABYTE AORUS GeForce RTX 3070 8GB>]> <QuerySet [<Gpu: MSI Gaming GeForce RTX 3070 8GB>, <Gpu: MSI Suprim GeForce RTX 3080 10GB>, <Gpu: MSI Non-locking Gaming GeForce RTX 3060>]> but i need to combine to be in one QuerySet like this <QuerySet [<Gpu: GIGABYTE AORUS GeForce RTX 3070 8GB>,<Gpu: MSI Gaming GeForce RTX 3070 8GB>, <Gpu: MSI Suprim GeForce RTX 3080 10GB>, <Gpu: MSI Non-locking Gaming GeForce RTX 3060>]> -
How to apply django-two-factor-auth in custom login page?
I am using Django Two-Factor Authentication for secure my admin login. I enforced OTP Required login for my every admin. Now I want to implement this for my normal users. If any user activated two factor on his account then every time he will be redirected to otp page like admin users if two factor not enabled then he will redirect to my account page. here is my login view: def login_view(request): username = None password = None if request.user.is_authenticated: return redirect('blog:my-account') else: if request.method == 'POST': username = request.POST.get('username') password =request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.add_message(request, messages.INFO,'Login Sucessfull') return redirect('members:user-profile-private') **urls.py** path('login/',views.login_view, name='login'), I also want to know how to get back Django default admin login page. After implement django-two-factor-auth my admin login page look like this is there any way to redesign custom Two-Factor Authentication login html page ??? -
CSS just won't update on CKeditor even when clearing cache
I've added CKeditor to my django website. It works, except the styling is a bit wrong. I figured I'd just grab the labels and make them white so I can see them - messing around with f12 I found that if I comment the color out here, the labels indeed turn white. Cool, no big deal, just go to editor.css and edit color: #000 to color: #fff like this: .cke_reset_all, .cke_reset_all *, .cke_reset_all a, .cke_reset_all textarea { margin: 0; padding: 0; border: 0; background: transparent; text-decoration: none; width: auto; height: auto; vertical-align: baseline; box-sizing: content-box; position: static; transition: none; border-collapse: collapse; font: normal normal normal 12px Arial, Helvetica, Tahoma, Verdana, Sans-Serif; color: #fff; text-align: left; white-space: nowrap; cursor: auto; float: none } I save, python manage.py runserver, ctrl+f5 only to find that nothing changed. I also tried collectstatic but I don't think that's relevant (0 files were modified). Inspecting the element again brings up the old css file with color: #000. Going to the network tab also reveals the same old file. What's going on here? -
Encode an encodable struct to Alamofire POST parameters - Swift
I'm trying to connect my front-end iOS app (Swift) to my Django backend. I have this struct: struct APIAccountID: Codable { let username: String let password: String enum CodingKeys: String, CodingKey { case username = "username" case password = "password" } } Which is codable. I'm trying to pass the data of this struct in an Alamofire POST request. So I'm trying to get encode the object like this: if let data = try? JSONEncoder().encode(accountID) { return data } else { print("Error: encoding post data") return nil } And I get this error when I send the request: { "non_field_errors" = ( "Invalid data. Expected a dictionary, but got str." ); } -
Django - Multi-steps forms/split-form, how to?
quite new here. I want to create a multi-steps form. The idea is that I have a Log form that I would like to split in 4 pages(with many many skippable fields). Atm i created 1 app, with 1 model and 4 tables, 1 for each "split" and respective urls and view. My objective is to have a starting listview from where i can A)create a new log(CreateView) at page1 then, keeping the pk of the session move to page 2,3,4 and save (or save at the end of each page). At the same time i need to be able to modify it(updateView)in the same format(4 pages). How do I keep th pk to pass on? I tried to use 1 listview, with combined createview and updateviews. I also tried with formsets but I haven't been able to make much progress. What is the best way and practice to realise this multi-step form? I've read of a possible Django-tools (Wizard). Is that a viable solution or is there a better and simpler way? Thanks in advance for the help!** -
Django Template wont show up on page although the value is correct
So in my views.py I saved values in the context field to use them as a template and if I print the value they are showing in the console so the value is correct but the tag doesnt work. @login_required(login_url='home:login') def profilesettings_view(request): packet = get_object_or_404(Account, user=request.user) prename = packet.prename surname = packet.surname company = packet.company context= { 'prename': prename, 'surname': surname, 'company': company } print((prename)) print((surname)) return render(request, 'home/profilesettings.html') <DOCTYPE html> <h1>Das ist die Profil Settings Seite</h1> <body> <span><p>Prename: {{ prename }}</p><a href="{% url 'home:ps_prename' %}">EDIT</a></span> <span><p>Surname: {{ surname }}</p><a href="{% url 'home:ps_surname' %}">EDIT</a></span> <span><p>Company: {{ company }}</p><a href="{% url 'home:ps_company' %}">EDIT</a></span> </body> -
Duplicate records being created in Django Command
I'm having trouble with this function that is creating duplicate records. I have a couple pages with documents that contain a response with document as a list of records. Each page contains a different number of document in this this list. When all the records are created in the database, it starts to duplicate them because the amount of pages exceeds the number of pages that have documents in them. Here is what the response for each page looks like: { "page": 3, "limit": 10, "count": 2, "machines": [ { "document_id": "1234", "location": "123 Random address", "location_name": "Scraton", "location_coordinates": { "latitude": 54.443454, "longitude": -124.9137471 }, { "document_id": "1235", "location": "124 Random address", "location_name": "New York", "location_coordinates": { "latitude": 233.385037, "longitude": -40.1823481 }, ] } Here is the function that is creating duplicates. def sync_all_documents(limit=1000, page_start=0,page_end=10): for page in range(page_start, page_end): try: response_data = get_documents(limit=limit, page=page) logger.info(f"Page Count: {response_data['count']}") if(response_data['count'] == 0): return except RequestError as ex: return # loop short circuits here try: documents = response_data[“documents”] for document in documents: # STEP 1 - Location try: serialized_location = serialize_location_information(document) location, l_created = Location.objects.get_or_create( latitude=serialized_location["latitude"], longitude=serialized_location["longitude"], defaults={ "country": serialized_location["country"], "state": serialized_location["state"], "city": serialized_location["city"], "street_address": serialized_location["street_address"], "postal_code": serialized_location["postal_code"], "name": serialized_location["name"], "status": serialized_location["status"], … -
How prevent creating a base model in django-polymorphic
I want to only be able to create new objects on sub-classes and not on base class. class Product(PolymorphicModel): # fields class ProductType1(Product): # fields class ProductType2(Product): # fields For example in above code creating new objects should only be possible on ProductType1 and ProductType2 and NOT on Product it self. -
Why does the intial value of a form field not display in one field?
I am trying to display this form with initial values. However, only the initial value for the field 'title' shows up and not the 'content' field. Moreover, if I change the initial value of the 'title' field to entryPage the required value will display in that field but this does not work in my 'content' field. form class NewPageForm(forms.Form): title = forms.CharField(label="Title:", max_length=100, widget=forms.TextInput(attrs={'class': 'formpgtitle', 'placeholder': 'Type in the title of your page'})) content = forms.CharField(label="Content:", widget=forms.Textarea(attrs={'class': 'formpgcont', 'placeholder': 'Type content in markdown form starting with page heading - ## heading.'})) edit = forms.BooleanField(initial=False, widget=forms.HiddenInput(), required=False) views.py def edit(request, entry): entryPage = util.get_entry(entry) if entryPage is None: return render(request, "encyclopedia/error.html", { "entryTitle": entry }) else: form = NewPageForm() form.fields["title"].initial = entry form.fields["title"].widget.attrs['readonly'] = True form.fields["content"].intial = entryPage form.fields["edit"].intial = True return render(request, "encyclopedia/newpage.html", { "form": form, "edit": True, "entryName": entry })