Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 }) -
How to add a function that creates a link to os.path.join(BASE_DIR, 'media/') in settings.py django?
I use froala editor to add text to the model and I want to change the folder where the images will be loaded from the form field. My function to create a path looks like this: #utilities.py def article_img_directory_path(instance, filename): article_title = slugify(instance.title, allow_unicode=True) return 'images/{0}/{1}'.format(article_title, filename) I don't know how to add this function to the editor's path correctly: #settings.py from articles.utilities import article_img_directory_path FROALA_UPLOAD_PATH = os.path.join(BASE_DIR, 'media/')+str(article_img_directory_path) Images are loaded and displayed, but as a result, the loading path is wrong -
Django - Dynamically populate the choices of a CharField with the fields of some other models: Models aren't loaded yet RegistryError
Good day everyone, hope you're doing really well. Straight to the point, let's say we have anpp w models: from django.apps import apps from django.db import models class A(models.Model): # A lot of fields go here class B(models.Model): # A lot of fields go here # And some more models ... class ModelChoices(models.TextChoices): A = 'A' B = 'B' ... class Filterset(models.Model): model = models.CharField(max_length=32, choices=ModelChoices.choices) attribute = models.CharField(max_length=32, choices=auto_generate_attributes().choices) def auto_generate_attributes(): all_attributes = set() for model_name in ModelChoices.values: ModelClass = apps.get_model(model_name) model_fields = ModelClass._meta.get_fields() model_attributes = [(attr.name, attr.name) for attr in model_fields] all_attributes.update(model_attributes), Attributes = models.TextChoices( 'Attributes', list(all_attributes), ) return Attributes Now you're probably wondering what's the point of this table. In short, I'll use it in a M2M relationship with another model so that an User can filter on values of different models at once and return a list of FK objects that all models share (Sounds abstract, but trust me). But the other models are still a work in progress and will edit/create new fields as time goes, that's why I have to generate them dynamically instead of hard-coding them. The issue is trying to get the models classes at initilization time to popuplate the choices of … -
django - how to use current user that loged in model (in the way that he cant choose another user)
i want to make a blog with django that any user can create posts and post owned by just that user .the author of the post most be the current user that loged in and never change. i have a problem to get current user in post model !! how i store current that wrote the post with post model ? from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.utils import timezone from ckeditor.fields import RichTextField class Post(models.Model): STATUS_CHOICES = { } TECHNOLOGY_CHOICES = { } title = models.CharField(max_length=250) slug = models.SlugField(max_length=250,unique_for_date='publish') author = models.ForeignKey(User,on_delete=models.CASCADE,) body = RichTextField(config_name='default',blank=True, null=True) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') category = models.CharField(max_length=250,default='other') def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('index') -
copy models instance in django not working well
I want to copy blogpost model, i have consider foreign key relationship but still fail in test of blog_copy and blog_author_copy. Could anyone help me? class Author(models.Model): name = models.CharField(max_length=50) class BlogPost(models.Model): title = models.CharField(max_length=250) body = models.TextField() author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='blog_posts') date_created = models.DateTimeField(auto_now_add=True) def copy(self): new = BlogPost.objects.get(pk=self.pk) new.pk = None new.id = None new.date_created = datetime.now() # new.author.blog_posts.add(new) authors = Author.objects.all() for author in authors: if self.author == author: author.blog_posts.add(new) new.save() old = BlogPost.objects.get(pk=self.pk) for comment in old.comments.all(): comment.pk = None comment.blog_post = new comment.save() new.comments.add(comment) new.save() class Comment(models.Model): blog_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE, related_name='comments') text = models.CharField(max_length=500) -
Django - Can't access variable defined with template tag outside for loop
In a Django template, I have to signal that the if conditional was entered and for this I created a template tag: @register.simple_tag def setvar(val=None): return val And in my template I have: <div> {% for item in items %} {% if <!-- condition --> %} {% setvalor '1' as has_favorites %} {% endif %} {% endfor %} <div>{{ has_favorites }}</div> <!-- testing --> </div> The variable has_favorites is not rendered in the browser. It seems that the variable is only available in the for loop scope. Is there a way to workaround that? -
ValueError while logging out user from the page dynamically created by passing pk
I have a page search.html that has a link associated with a pk that when clicked redirects to page doc.html which outputs the contents related to that pk This doc.html extends a page consult_home.html. This page contains the logout button. In all the other pages that extends this consult_home.html the logout button works perfectly. But in the doc file I get the following error and the logout link does not work: ValueError at /consultancy/doc/logout Field 'id' expected a number but got 'logout'. Below are the codes of the view functions and the url patterns and also the template codes: consult_home.html* <button type="button" class="button log_out" onclick="location.href='logout';">LOGOUT</button> view function for logout def logoutUser(request): logout(request) return redirect('/') search.html <a class="judge-ttle" href="{% url 'doc' searches.pk %}">{{searches.title}} &nbsp <i class="fas fa-external-link-alt"></i></a> views for doc.html class DocDetailView(DetailView): model= Laws template_name = 'doc.html' urls.py urlpatterns=[ path('logout', views.logoutUser, name='logout'), path('doc/<str:pk>', DocDetailView.as_view(), name='doc' ), ] As I described above the user is unable to log out when he is in doc.html. How can I remove this Value Error. -
How to install Django+Postgres on Docker using base image Alpine:3.14
Following are the initial three files that you will need to create in your project folder Dockerfile # syntax=docker/dockerfile:1 FROM alpine:3.14 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN apk update RUN apk add postgresql-dev RUN apk add gcc RUN apk add python3-dev RUN apk add musl-dev RUN apk add py3-pip RUN pip install psycopg2 RUN pip install -r requirements.txt COPY . /code/ docker-compose.yml version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db requirements.txt Django>=3.0,<4.0 psycopg2-binary>=2.8 After creating the above 3 files run the following command: docker-compose run web django-admin startproject example_project . Next you will have to modify the settings for database in the newly created settings.py file in your django project folder. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432, } } Run: docker-compose up As the server is running go to the Terminal of your container and do migrations (Docker Desktop > Container/Apps > Expand docker > Docker_web CLI) python3 manage.py migrate -
why my django signals not sending for create user profile objects?
I have three model Subscriber, MyAuthors and MyCustomer. When an object creates any of my three models, I send a signal to my user profile model to create a profile object. Signals sending properly from MyCustomer model but I am not understanding why signals not sending for Subscriber and MyAuthors models. here is my code: class UserManagement(AbstractUser): is_blog_author = models.BooleanField(default=False) is_editor = models.BooleanField(default=False) is_subscriber = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) class MyAuthors(models.Model): user = models.OneToOneField(UserManagement, on_delete=models.CASCADE, primary_key=True) email = models.EmailField(max_length=1000) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) class Subscriber(models.Model): user = models.OneToOneField(UserManagement, on_delete=models.CASCADE, primary_key=True) email = models.EmailField(max_length=1000) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) class MyCustomer(models.Model): user = models.OneToOneField(UserManagement, on_delete=models.CASCADE, primary_key=True) email = models.EmailField(max_length=1000) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) class UserProfile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile") ....my others fields #my customer_signals working properly @receiver(post_save, sender=MyCustomer) def user_is_created_or_save(sender,instance,created,**kwargs): user = instance.user password = instance.user.password username= instance.user.username email = instance.email first_name = instance.first_name last_name = instance.last_name user_id = instance.user.id is_customer = instance.user.is_customer um = UserManagement(id=user_id,email=email,username=username,password=password,first_name=first_name,last_name=last_name,is_customer=is_customer) um.save() if created: UserProfile.objects.create(user=user) #subscriber_signals @receiver(post_save, sender=Subscriber) def user_is_created_or_save(sender,instance,created,**kwargs): user = instance.user password = instance.user.password username= instance.user.username first_name = instance.first_name last_name = instance.last_name email = instance.email user_id = instance.user.id is_subscriber = instance.user.is_subscriber um = UserManagement(id=user_id,email=email,username=username,password=password,first_name=first_name,last_name=last_name,is_subscriber=is_subscriber ) um.save() if created: UserProfile.objects.create(user=user) #author_signals … -
Django: How to display success data from requests ajax one by one in table
in my page i send input value to another page by request ajax, that page give me form django generated for instance value like this but not give me the same in this expample 👇 How I can send request ajax and get success data like this for each request -
Missing feedback from Django migrate command
When running python manage.py migrate in a ruge database and the migrate process is taking forever to end, however no feedback is provided on the process. I'm worried that some deadlock or conflict can be happening, and the --verbosity argument can't help enough to discover the real problem. Any ideas? The command output that are during forever: Operations to perform: Apply all migrations: admin, atendimento, auth, authtoken, contenttypes, imoveis, sessions Running pre-migrate handlers for application admin Running pre-migrate handlers for application auth Running pre-migrate handlers for application contenttypes Running pre-migrate handlers for application sessions Running pre-migrate handlers for application imagekit Running pre-migrate handlers for application appone Running pre-migrate handlers for application apptwo Running pre-migrate handlers for application django_crontab Running pre-migrate handlers for application django_user_agents Running pre-migrate handlers for application rest_framework Running pre-migrate handlers for application authtoken Running pre-migrate handlers for application simple_history Running migrations: -
Invalid Syntax: ImportError,e
I am trying to make migrations for my Django project, it was working and building fine before I installed and implemented the Django registration-redux module. These are the errors I currently get and I don't understand why or how to fix it. File "/Users/user/Documents/django-projects/tango_with_django_project/manage.py", line 22, in <module> main() File "/Users/user/Documents/django-projects/tango_with_django_project/manage.py", line 11, in main from django.core.management import execute_from_command_line File "/opt/homebrew/lib/python3.9/site-packages/django/core/management/__init__.py", line 54 except ImportError,e: ^ SyntaxError: invalid syntax