Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am trying to make django app but this script error keeps coming
from django.contrib import admin from django.urls import path from buttonpython2 import views app_name = "buttonpython2" urlpatterns = [ path('admin/', admin.site.urls), path('', views.button) path('', views.output, name="script") ] this is my url.py this image shows the error enter image description here -
Django WizardForm save model using multiple forms
I have a model Customer: class Customer(models.Model): name = models.CharField( verbose_name='Bedrijfsnaam', max_length=100, unique=True ) street = models.CharField( verbose_name='Bezoek straat', null=True, max_length=150 ) house_number = models.IntegerField( verbose_name='Huisnummer', null=True ) zipcode = models.CharField( verbose_name='Postcode', max_length=6 ) city = models.CharField( verbose_name='Plaats', max_length=100 ) phone = models.CharField( verbose_name='Telefoon', max_length=100 ) mobile_phone = models.CharField( verbose_name='Mobiel Telefoon', max_length=100 ) fax = models.CharField( verbose_name='Fax', max_length=100, null=True, blank=True ) email = models.EmailField( verbose_name='E-mail' ) website = models.CharField( verbose_name='Website', max_length=100, null=True, blank=True ) kvk = models.CharField( verbose_name='KvK-nummer', max_length=20, help_text='s.v.p. uittreksel toevoegen, niet ouder dan 6 maanden' ) kvk_file = models.FileField( verbose_name='Uittreksel', max_length=2000, upload_to=kvk_directory_path, null=True, ) activities = models.TextField( verbose_name='Hoofdactiviteiten', null=True, blank=True ) total_employees = models.IntegerField( verbose_name='Aantal medewerkers', null=True, blank=True ) yearly_transactions = models.IntegerField( verbose_name='Verwachte jaarafname', null=True, blank=True ) order_confirmation = models.BooleanField( verbose_name='Opdrachtbevestiging altijd per email?', default=False ) confirmation_email = models.EmailField( verbose_name='E-mail opdrachtbevestigingen', null=True ) delivery_address = models.CharField( verbose_name='Afleveradres', max_length=100 ) delivery_zip = models.CharField( verbose_name='Postcode', max_length=6 ) delivery_city = models.CharField( verbose_name='Plaats', max_length=100 ) delivery_instructions = models.TextField( verbose_name='Instructies', null=True ) mail_address = models.CharField( verbose_name='Postadres', max_length=100, null=True, blank=True ) mail_zip = models.CharField( verbose_name='Postcode', max_length=6, null=True, blank=True ) mail_city = models.CharField( verbose_name='Plaats', max_length=100, null=True, blank=True ) iban = models.CharField( verbose_name='IBAN-nummer', max_length=36 ) btw = models.CharField( verbose_name='BTW-nummer', max_length=50 ) cash_pin = models.BooleanField( verbose_name='Contant/Pin', help_text='(alleen … -
How do you add a link in an f string?
I am trying to add a link in the f string below: d += f'<li> {event.time} {event.teacher} {event.student} {event.status} </li>' Basically, I want it to look something like below: f'<li> <a href="{% url 'somewhere' event.pk %}"> {event.time} {event.teacher} {event.student} {event.status} </a> </li>' However, I get the following error when I do this: SyntaxError: f-string: expecting '}' Do you guys know how to input a link in an f string? Please ask me any questions you have. -
query that must exclude me from the whole list
hi i have a problem with this filter. group_to_add takes some values which should filter out the problem that I don't want those values but I want the others without those. I would like to find a way to take those values and subtract them from others. group_to_add = DatiGruppi.objects.filter(gruppi_scheda = scheda.id) GruppiForm.base_fields['dati_gruppo'] = forms.ModelChoiceField(queryset = group_to_add) I asked a similar question I leave the link select filtering and removal if they are already present in the db -
Return Empty Page if There's No Filtering Provided in DRF and Django Filters
I have a ViewSet as below: class EntryViewSet(viewsets.ModelViewSet): queryset = Entry.objects.all() serializer_class = EntrySerializer filter_backends = [DjangoFilterBackend, OrderingFilter] filterset_class = EntryFilterSet ordering_fields = ["created_at", "last_update"] ordering = "created_at" ...and a FilterSet defining several fields that I can filter against: class EntryFilterSet(django_filters.FilterSet): class Meta: model = models.Entry fields = [ "content", # and other fields ] I have connected my EntryViewSet to /api/entries/ with DefaultRouter of DRF, list view is automatically named as api:entry-list. So, /api/entries/ returns: { "count": 100, "next": "http://localhost:8000/api/entries/?format=json&p=2", "previous": null, "results": [ { "pk": "6Kqpyak", "created_at": "2021-10-13T13:28:17.410883Z", "last_update": "2021-10-13T13:28:17.410898Z", "content": "Start investment begin nice feeling. Travel sea mind teacher could. Within act series effort crime.", "content_html": "<p>Start investment begin nice feeling. Travel sea mind teacher could. Within act series effort crime.</p>", "author": 1, "title": { "pk": "6Kqpyak", "created_at": "2021-10-13T13:28:17.408026Z", "label": "republican attack computer recently though guy.", "redirects_to": null, "recent_count": 0, "last_update": "2021-10-13T13:28:17.416822Z" } }, { "pk": "1ozyMzx", "created_at": "2021-10-13T13:28:17.532635Z", "last_update": "2021-10-13T13:28:17.532649Z", "content": "School establish partner. Establish possible who let. Impact health exactly particular note.", "content_html": "<p>School establish partner. Establish possible who let. Impact health exactly particular note.</p>", "author": 2, "title": { "pk": "1ozyMzx", "created_at": "2021-10-13T13:28:17.531007Z", "label": "produce six while act.", "redirects_to": null, "recent_count": 0, "last_update": "2021-10-13T13:28:17.535188Z" } … -
django-puppeteer-pdf creates empty pdf
I'm trying to generate a pdf of Django class based detail view by using django-puppeteer-pdf. PDF file gets generated but when I open it, it contains only a word None and the rest of the page is blank. Here's the code: View I want to turn into pdf class CalculationDetailView(UserPassesTestMixin, LoginRequiredMixin, generic.DetailView): model = Calculation def test_func(self): return self.request.user.is_authenticated def get_queryset(self): qs = super().get_queryset() if not self.request.user.is_staff: qs = qs.filter(userid=self.request.user.pk) return qs View that generates pdf set up by following django-puppeteer-pdf docs class GenerateCalcDetailPdf(PDFTemplateView): filename = 'details.pdf' template_name = 'cycle\calculation_detail.html' header_template = 'base_generic.html' cmd_options = { 'margin-top': 3, } urls.py url(r'generate-pdf/$', views.GenerateCalcDetailPdf.as_view(), name='generate-pdf') The template content is dynamically rendered from the database and styled with Bootstrap. It contains static files and here are the static settings: PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.append(os.path.join(PROJECT_ROOT, 'orc2')) STATIC_ROOT = os.path.join(BASE_DIR, '/static/') STATIC_URL = 'static/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, 'static'), ] Any advice or help is welcome since, according to docs I'm doing everything properly but for some reason it doesn't work properly. -
'QuerySet' object has no attribute 'META' 500(internal server erro)
I'm trying to practice ajax in django but I got this error 'QuerySet' object has no attribute 'META'. But it's showing the data in the traceback but not in the template because of the error.How to fix this? models.py from django.db import models # Create your models here. class Profile(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=100) bio = models.CharField(max_length=100) def __str__(self): return self.name I think it has something to do with the views but I cant figure it out. views.py from django.shortcuts import render from .models import Profile from django.http import JsonResponse # Create your views here. def list(request): return render(request, 'livedata/list.html') def getProfiles(request): profiles = Profile.objects.all() # print(JsonResponse({"profiles": list(profiles.values())})) return JsonResponse({"profiles": list(profiles.values())}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.list, name='list'), path('getProfiles', views.getProfiles, name='getProfiles') ] index.html {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> {% comment %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> {% endcomment %} <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script> <script src="{% static 'js/main.js' %}" defer></script> <title>Hello, world!</title> </head> <body> {% block contents %}{% endblock contents %} {% block scripts %}{% endblock scripts %} <!-- … -
How to display error message with Django forms?
I would like to customize the Django login authentication form. The original form looks like this and it works perfectly: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4 ">Log In</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Login</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Need An Account? <a class="ml-2" href="{% url 'register' %}">Sign Up Now</a> </small> </div> </div> {% endblock content %} My goal is to modify the form style so that I can place the objects wherever I want. I was able to achieve this for the username and password fields, however I cannot display the error message just like in the original format. This is what I tried: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4 ">Log In</legend> {% if formset.non_form_errors %} <div class="alert alert-block alert-danger"> {% if formset_error_title %}<h4 class="alert-heading">{{ formset_error_title }}</h4>{% endif %} <ul class="m-0"> {{ formset.non_form_errors|unordered_list }} </ul> </div> {% endif %} <div class="row"> <div class="col-md-4 col-sm-12 register-field"> {{ form.username|as_crispy_field }} </div> <div class="col-sm-12 register-field"> {{ form.password|as_crispy_field }} </div> </div> … -
Djagno start server, scan Network and write data to DB
My idea Store network devices data threw a Django Model (Device Model) to my Database. Host configuration needs to be setup by User inside a View (Host Model) When the Host configuration is finished the Network should be scanned for devices (Device Model) The Data should be stored inside the DB The fuction create_devices() gets called before a host was setup, with migrate and makemigrations. How can i fix this? Is it even right to store this data via View to my Database? Bestcase would be storing data to the DB Async to my Application, is there a way? Thank you very much for your help!!! Host Model: class Host(models.Model): hostname = models.CharField(default="noads", max_length=6) ipv4_address = models.GenericIPAddressField('IPv4') ipv4_subnet = models.GenericIPAddressField('IPv4') gateway = models.GenericIPAddressField('IPv4') Device Model: class Device(models.Model): hostname = models.CharField(max_length=64) mac_address = models.CharField(max_length=64) ipv4_address = models.GenericIPAddressField('IPv4') My View: def get_arp_table_linux(): """ Parse the host ARP table on a Linux machine :return: Machine readable ARP table :rtype: dict {'ip_address': 'mac_address'} """ with open('/proc/net/arp') as proc_net_arp: arp_data_raw = proc_net_arp.read(-1).split("\n")[1:-1] parsed_arp_table = (dict(zip(('ip_address', 'type', 'flags', 'hw_address', 'mask', 'device'), v)) for v in (re.split('\s+', i) for i in arp_data_raw)) return {d['ip_address']: d['hw_address'] for d in parsed_arp_table} def get_devices_in_list(): """ Gets every device inside the … -
Can I use two urls for the same view in django?
So basically, can I have two urls(or paths) for the same view in django? I searched online for this question, but somehow I couldn't find a clear answer(in other word, please don't downvote me because it is a seemingly easy question). Thank you, and please let me know if you have any questions. -
Css is correctly working on Local but not on server Django?
CSS is Loading perfectly on local but not on the server. Also, I am trying using static_root and collectstatic method but that way the CSS is loading totally. -
How do you access the primary key from a generic list view?
I am trying to access the primary key of the url from a generic list view. Let me explain. So, I currently have a simple page with a list of student instances from the model student. Each row is dedicated to one student, such as the name, age, email, etc. Now, I want to add a link to each row so that I can view each student's calendar once I clicked it. Right now, the calendar view is a generic ListView like below. class CalendarView(LoginRequiredMixin, generic.ListView): model = Class template_name = 'leads/calendar.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # use today's date for the calendar d = get_date(self.request.GET.get('month', None)) # Instantiate our calendar class with today's year and date cal = Calendar(d.year, d.month) # Call the formatmonth method, which returns our calendar as a table html_cal = cal.formatmonth(withyear=True) context['calendar'] = mark_safe(html_cal) context['prev_month'] = prev_month(d) context['next_month'] = next_month(d) return context However, I want the calendar to show only information related to the student I clicked on. In order to do this, I need to be able to use the primary key(or ID) of the student in my calendar view. Of course, I can embed the primary key in the url, but … -
Django possible circular import
I'm setting up a new "Game" website. I have started a new app Games, set up the games/models.py with the code (below). After makemigrations game and migrate, I was able to log into Admin and add entries. Then I set to create the URLs, views, one template. After creating them, when I runserver, I get the following error: url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'games.urls' from '/home/mackley/PycharmProjects/alphabet/games/urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. The first thing I noticed is that the top line (from django.conf import settings) of games/models.py (using PyCharm) is greyed out. I don't know if that has anything to do with the error: Can anyone spot where I have made a mistake? Here is the relevant code. # games/models.py from django.conf import settings from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse class Game(models.Model): title = models.CharField(max_length=255) date_create = models.DateTimeField(auto_now_add=True) date_start = models.DateTimeField(auto_now_add=False) body = models.TextField() author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) answer_one = models.CharField(max_length=1) answer_two = models.CharField(max_length=1) answer_three = models.CharField(max_length=1) answer_four = models.CharField(max_length=1) answer_five = models.CharField(max_length=1) answer_six = … -
m2m_changed signal not firing when an instance is in an m2m relationship is deleted? How can I trigger updates in other models when this happens
I have an app that has a 'real-time data' frontend by using django signals and webhooks. It works when a relationship is removed, or added, but if a relationship instance is deleted, m2m_changed isn't fired so the frontend isn't updated. Is m2m_changed meant to be fired in this situation though? The parent model has an m2m field which stores 'subscribed to' child models. I also have a property function that shows all possible child models to subscribe to (I have both subscribed and unsubscribed fields so i can have an on/off switch on the frontend): class Parent(models.model): subscribed_to = m2mField(Child) @property def potential_subscriptions(self): return Child.objects.all() # not sure if this is bad practice My signal looks like this: @receiver(m2m_changed, sender=Parent.subscribed_to.through) def signal(sender, instance, action, reverse, **kwargs): from .api.serializers import ParentSerializer if action == "post_add" or action == "post_remove" or action == "post_clear": serializer = ParentSerializer(instance) websocket.send(f"parent_{instance.id}", "parent_update", serializer.data) So it works when child instances are added or removed, but if a child instance is deleted it doesn't fire, so my websocket doesnt update the frontend. As a work around I tried to create a pre_delete signal for the Child object, and within the signal I clear it's relationship before it … -
Hello! I have a model with DateField that contains null = True, blanck = True and when I use it somewhere, i got errors below:
begin_date= models.DateField(verbose_name=_("Begin date"),null=True, blank=True) errors: [{loc: ["begin_date"], msg: "none is not an allowed value", type: "type_error.none.not_allowed"}] 0: {loc: ["begin_date"], msg: "none is not an allowed value", type: "type_error.none.not_allowed"} I use ValidationError from Pydantic, it also triggers because of that I know that there's a way like set allow_none to True but I have no clue how to write it correctly. I'm completely new to programming and English is not my native so sorry for mistakes. -
django display message issue after POST form submit?
Whenever I am using messages function, I get an error File "D:\Django Project\ta2\practice\views.py", line 60, in changepassword messages.SUCCESS(request,'your password has been updated') TypeError: 'int' object is not callable Here is my views.py def register(request): if request.method == 'POST': fm = new_registration_form(request.POST) if fm.is_valid(): fm.save() messages.add_message(request, messages.SUCCESS, 'Thanks for the registration') else: fm = new_registration_form() return render(request,'register.html',{'form':fm}) Here is my register.html part containing messages information div class="alert-info">{% if messages %} {% for message in messages %} {{message}} {% endfor %} {% endif %}</div> -
How to change the order of the form field when it is sorted in Django?
I am trying to change the order of the form field in the table when the user sorts it in the dropdown menu. Basically, it will be in the uppermost left of the table when the user sorted it the original table: the table will look like this when the user sorted it in name field: in my forms.py i have the field in order of: class myForm(forms.ModelForm): class Meta: model = myModel fields = [ "email", "name", "order", ] and in my models.py: class myModel(models.Model): name = models.CharField(max_length=100, null=True) email = models.CharField(max_length=100, null=True) role = models.CharField(max_length=100, null=True) in my views.py i tried: qs = myModel.objects.all().order_by("name") but it is just sorting the items inside the name field. how can I make it so that the name field will appear at the uppermost left part of the table? -
Run django on background for action
I'm trying to test my react app with yarn using Github Actions, I need to have Django running for some tests, however Django has the Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). October 15, 2021 - 03:32:25 Django version 3.2.6, using settings 'controller.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. message which locks bash, any ideas how I can start Django inside the action so that the action continues to run? This is currently my action name: CI on: push: branches: [ main ] pull_request: branches: [ main ] workflow_dispatch: jobs: tests: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Installing dependecies run: ./install.sh shell: bash - name: Testing backend run: ./backend-test.sh shell: bash - name: Starting backend run: ./backend.sh > /dev/null 2>&1 shell: bash - name: Testing frontend run: ./frontend-test.sh shell: bash And backend.sh does this # Backend test script cd backend/ && \ sudo service postgresql start && \ source .venv/bin/activate && \ python3 manage.py test -
Using same database table with two different projects Django
I'm a beginner in Django. I would like to know how to configure two different projects to share the same database table in Django. The database I'm using is MySQL. Let's say there's two projects, project A and project B. In project A, I already created a custom user model in it. And in project B, I want to use the custom user table from database created in project A just for the login. Means that in project A, there's registration and login for the custom user model. In project B, there's login only that will be using the same custom user data in the database. Do I have to redefine the same custom user model from project A in project B? What are the configuration settings that need to be done? Thanks in advance. -
Implementing Django user roles and group with Django REST framework
I have been following a django REST api and reactjs tutorial online on building a website. But the tutorial didn't cover the part for user roles and group for creating new users, admin or other roles which I wanted to implement it to extend the project. So far the django REST api can authenticate a user with the simplejwt, but I wanted it to authenticate different types of users. So anyone can enlighten me what and how should I do next? I am quite confuse when looking at other tutorials explaining this topic. -
How do I submit a Django form and print the result without redirecting the page?
Hello how are you? Hope someone can help me! I read a bunch of answers here on stack overflow, but none of them worked. I have an application that is a "social network". In the Divs of the logged user's own posts, there is an "Edit" button, which replaces the post content with a Djago form for the user to edit the content. The logic works, but I want that when the user saves the changes, the div itself is changed, without refreshing the page, how can I do that? My views.py: @login_required def edit_post(request, id): # Query the post try: post = Post.objects.get(id=id) except Post.DoesNotExist: return HttpResponse("Error: The post does not exist.") # Check if the user is the post's author. if request.user.id != post.author.id: return HttpResponse("Error: You can't edit this post.") # If request method is POST, modify the post if request.method == "POST": form = editPostForm(request.POST, instance=post) if form.is_valid(): form.save() return render(request, "network/postDiv.html", {"post": functions.getPost(id)}, content_type='application/xml') # If request method is GET: return the form form = editPostForm(instance=post) return render(request, "network/editPostForm.html", {"form": form, "id": id}) My urls.py: urlpatterns = [ path("", views.index, name="index"), path("following", views.following, name="following"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("u/<str:username>",views.profile, name="profile"), … -
Save users cookies langauge code in model field, When user login
I am using i18n in my django app. I give users the ability to change the language before and after login. When user changes their language without login then that language takes effect only for that session. if the user login and changes language after login it will be saved in the user model's lang field. If the user changes language without login and login after that then the language changed before login should be saved in the user model's lang field. If the user doesn't change their language before login we should continue with their profile language. thank you. -
How to make users automatically connected to specific rooms they chose even after they leave the site
I'm using Django and python-socket.io for the server side. I'm pretty new to socket.io, and I am wondering how to keep track of who is in which rooms even after the client is disconnected (closed tab of my site) so that the client automatically connect to the rooms they have decided to belong before leaving my site. I'm trying to do something like this: socketio.enter_room(django_user_object, "room1") # Instead of sid, I want to add the user. Thank you. -
How to pass user information to utils.py in django
I am trying to pass in user information to utils.py, but don't know how. Here is a part of the utils.py I am having trouble with: class Calendar(HTMLCalendar): def formatmonth(self, withyear=True): events = Class.objects.filter(date__year=self.year, date__month=self.month).exclude(student=None) cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week, events)}\n' return cal The problem is the queryset events. I want to do something like below for it: if self.request.user.is_student: events = Class.objects.filter(date__year=self.year, date__month=self.month).exclude(student=None) if self.request.user.is_teacher: events = Class.objects.exclude(student=None) Basically, I want to change the queryset depending on what user is using the website. That is why I need to use something like self.request.user in the utils.py. I tried to do def get_queryset(self) in the views.py, but it doesn't seem to work. I hope you could help, and give me any questions that you have. -
Django - Create multiple different objects with relations in single Django endpoint
Is there a way to create a endpoint that creates multiple objects? what I've been doing instead is taking in request data and creating the objects one at a time and if one fails then delete the previously created entities, this seems really really hacky and there has to be a better way to create multiple objects. So essentially all Post need to be associated with a Goal so when a request comes it it'll be accompanied with post related data and goal related data in request.data. So it should create the Goal first then the Post associated with it. Is there a way to do this in one go? My assumption is creating a custom serializer to handle this, but not sure how to eloquently handle the case of when if Post fails to create I should delete Goal. model.py class Goal(AbstractBaseModel): creator_uuid = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name="goal_creator_uuid") goal_category = models.ForeignKey(GoalCategory, on_delete=models.CASCADE) description = models.CharField(max_length=150, validators=[MinLengthValidator(5)]) class Post(AbstractBaseModel): creator_uuid = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator_uuid") goal_uuid = models.ForeignKey(Goal, on_delete=models.CASCADE) body = post_body view.py def post(request): """ POST endpoint for current user creating a goal update post """ goal_serializer = GoalSerializer(data=request.data) if goal_serializer.is_valid(): goal_obj = goal_serializer.save() else: # return Error …