Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReserveMatch and Error during template rendering
i am new at this thing. first, this is my urls.py urlpatterns = [ path('results/<int:id>/', views.abstract, name='abstract'), path('results/', views.result, name='result'), path('', views.index, name='index'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and my wiews def index(request): return render(request, 'online_sp/index.html') def result(request): script = Main() data = script.json_dt if 'No result' in data.keys(): no_result = True return render(request , 'online_sp/scripts.html', {'no_result':no_result}) else: return render(request , 'online_sp/scripts.html', data) def abstract(request, id): return render(request , 'online_sp/abstract.html') my goal is get page results/1/ with a button click from results/' page. (script.html) <a style="margin-left: 10%;" class="btn btn-dark" href="{% url 'abstract' 1%}" role="button">Abstratc</a> but it gives the NoReverseMatch error and says there is a error at line 0 in base.html which is a header template. NoReverseMatch at /results/ Error during template rendering In template C:\MyPythonScripts\not_a_vlog\online_sp\templates\online_sp\base.html, error at line 0 Reverse for 'abstract' with no arguments not found. 1 pattern(s) tried: ['results/(?P<id>[^/]+)/$'] 1 <!doctype html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="utf-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1, 7 shrink-to-fit=no"> 8 <title>{% block title %}Search Similar Papers{% endblock title %}</title> 9 </head> 10 but when i change path('results/<int:id>/', views.abstract, name='abstract') to path('<int:id>/', views.abstract, name='abstract') it gets the results/ page with abstract's template. however, i should go results/ page first and … -
Django legacy postgresql data migration error
While migrating legacy postgresql database I'm having following error. How to correct this? Error: timesheet.ImSearchObjectTypes.object_type: (models.E006) The field 'object_type' clashes with the field 'object_type_id' from model 'timesheet.imsearchobjecttypes'. Model: class ImSearchObjectTypes(models.Model): object_type_id = models.IntegerField(primary_key=True) object_type = models.ForeignKey(AcsObjectTypes, models.DO_NOTHING, db_column='object_type', blank=True, null=True, related_name="%(app_label)s_%(class)s_object_type", related_query_name="%(app_label)s_%(class)ss",) rel_weight = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) class Meta: managed = False db_table = 'im_search_object_types' -
How to dynamically set the queryset target model of a Django ModelForm field loaded using Ajax?
I have two dependent fields in a Django Modelform. The first 'foo_type' (radio buttons) is used to select the type of 'foos' dynamically loaded in the 'foos' field. 'foos' can be either fullfield with 'Cats', 'Dogs' or 'Horses' model objects and has to support mutiple selection. How could I define ModelMultipleChoiceField queryset "on the fly" meaning when user selects one of the 'foo_type' radio buttons, 'foos' queryset is modified accordingly to grab either 'Cats', 'Dogs' or 'Horses' model objects? Is that even possible? What approach should I go for in this case? Sidenote: that those two dependent fields ('foo_type' and 'foos') are not model fields, they are only used to compute data from selected 'foos' and will be used to populate a distinct field which won't be exposed in the UI. forms.my class AlertForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['subject'] = forms.CharField(label='Objet',widget=forms.TextInput(attrs={ 'class': 'form-control' })) self.fields['message'] = forms.CharField(label='Message',required=False,widget=forms.Textarea(attrs={ 'class': 'form-control' })) self.fields['extra_recipients'] = forms.ModelMultipleChoiceField(queryset=Contacts.objects.all(), label='Extra recipient',widget=forms.SelectMultiple(attrs={ 'class': 'form-control' })) # Radio buttons to define 'foos' content below self.fields['foo_type'] = forms.ChoiceField(choices=AlertFilterList.choices(),label='Foo type',required=True,widget=forms.RadioSelect(attrs={ 'class': 'custom-control custom-radio' })) # Content loaded using Ajax based on 'foo_type' selection above self.fields['foos'] = forms.ModelMultipleChoiceField(queryset=?????????, label='Foos',widget=forms.SelectMultiple(attrs={ 'class': 'form-control' })) class Meta(object): model = Alerts fields = … -
Sort Descending by Date created_at
I have a list of proposals that I want to sort descending by date created_at. How would I go about achieving that? <div class="display-title"> <p class="proposal-title-display"> {% if proposal.data.title %} {{ proposal.data.title }} {% else %} My proposal {% endif %} started at: {{proposal.created_at}}</p> </div> -
Changing notebook directory leads to an error in loading extensions
I'm running an IPython notebook through Django's shell_plus with the following command: sudo ./manage.py shell_plus --notebook I'm not entirel sure how it works, but ./manage.py shell_plus knows to look for additional settings in django's settings.py file, where I have the following IPython arguments: IPYTHON_ARGUMENTS = [ '--ext', 'django_extensions.management.notebook_extension', '--profile=mitchell', '--port=8889', '--notebook-dir=/home/rootadmin/server/', '--certfile=/ssl/fullchain.pem', '--keyfile=/ssl/privkey.pem', '--ip=*', '--no-browser', '--no-mathjax', ] So far this all works as intended. It runs a notebook server, that I can access and it serves any notebook file within the notebook-dir, which is the same directory from which I run the ./manage.py shell_plus --notebook command. I can execute code, and have access to my django models. However, this is my general home directory and I don't want all my notebooks in this directory. I made a new directory, from which I want to serve my notebooks. I change my notebook-dir accordingly. '--notebook-dir=/home/rootadmin/server/jupyter_directory', Then, if I run the notebook, it initially appears to work: I can access it online, and it shows me the notebooks within the jupyter_directory, however, when I try to run any code that required my django models, it no longer works, saying that these models are undefined. In the terminal, where I started the notebook I … -
How to get field value from relations model
I need to get the value of the foreignkey field not as an id but as a value of one of the fields of the linked model. models.py class RfiParticipation(models.Model): ... m = models.ForeignKey('Modules', models.DO_NOTHING, related_name='to_modules') ... class Modules(models.Model): MODULES_NAME = (.... ) mid = models.AutoField(primary_key=True) module_name = models.CharField(max_length=50, choices=MODULES_NAME, unique=True) serializer.py class VendorsManagementListSerializer(serializers.ModelSerializer): company_information = serializers.SerializerMethodField() vendor_modules = serializers.SerializerMethodField() class Meta: model = Vendors fields = ('vendor_name', ... 'vendor_modules',) def get_vendor_modules(self, obj): r = RfiParticipation.objects.filter(vendor=obj).order_by('rfi').values('m', 'rfi') return r Now this request r = RfiParticipation.objects.filter(vendor=obj).order_by('rfi').values('m', 'rfi') returns to me: "vendor_modules": [ { "m": 2, "rfi": "20R1" }, { "m": 3, "rfi": "20R1" }, { "m": 4, "rfi": "20R1" } ] How I can make m: module_name instead of m: 2? Where module_name is the field from Modules model. I try .values('m.module_name', 'rfi') but got Cannot resolve keyword 'm.module_name' into field. Choices are: active, id, m, m_id, rfi, rfi_id, timestamp, user_id, vendor, vendor_id -
Django: Is it good practice to write `classmethod` for single line query?
Is it a good practice to write classmethod or method on model for all the interactions with database even for the single line query. for eg. Example 1 # models.py class Student(models.Model): name = models.CharField(max_length=255) @classmethod def get_all_students(cls): return cls.objects.all() # views.py def foo(request): students = Student.get_all_students() Example 2 # models.py class Student(models.Model): name = models.CharField(max_length=255) # views.py def foo(request): students = Student.objects.all() Which one(Eg. 1 or Eg. 2) is better and why? -
Attempted relative import beyond top-level package
This is the structure of my app: media packsapp -migrations -templates -templatetags -views1 -__init__.py -apps.py -barcode.py -decorators.py -forms.py -models.py -urls.py -views.py pfep -migrations -templates -__init__.py -admin.py -apps.py -forms.py -models.py -pfep_views.py -tests.py -urls.py I have two apps named packsapp and pfep but when I tried to import decorators from the packsapp to the pfep like this: pfep_views.py from ..packsapp.decorators import employee_required It is giving me the following error: ValueError: attempted relative import beyond top-level package The main URLS.py is like this: urlpatterns = [ path('', include('packsapp.urls')), path('pfep/', include('pfep.urls')), path('admin/', admin.site.urls), Why am I getting the above error ? Is there something wrong with the import ? -
Django: select status, count(status) from table group_by status;
I know that there is no group_by in Django for some reason. However, I need to get the number of items in each of the possible statuses. It can be done with a very simple query: select status, count(status) from table group_by status; At the same time, in our project we try to do as much as possible in Django ORM, and so far have never used raw SQL anywhere except in some migrations. Is there a way to do this in Django ORM without getting duplicates? -
How can i send real time data to a Django application and show it on a webpage?
I'm trying to add real-time features to my Django webapp. Basically, i want to show real time data on a webpage. I have an external Python script which generates some JSON data, not big data but around 10 records per second. On the other part, i have a Django app, i would like my Django app to receive that data and show it on a HTML page in real time. I've already considered updating the data on a db and then retrieving it from Django, but i would have too many queries, since Django would query the DB 1+ times per second for every user and my external script would be writing a lot of data every second. What i'm missing is a "central" system, a way to make these two pieces communicate. I know the question is probably not specific enough, but is there some way to do this? I know something about Django Channels, but i don't know if i could do what i want with it; i've also considered updating the data on a RabbitMQ queue and then retrieve it from Django, but this is not the best use of RabbitMQ. So is there a way to … -
In Django the Image is not getting showed from Database
I am building a song listing application where users can add their favourite songs to the website and their favourite singers. And they can also give them ratings. The website will show the top 10 singers and artists on the home page. I have already developed the majority of it just stuck with one issue. The song cover image is not getting displayed I have tried but the cover image is not getting displayed in the template files. settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py from django.contrib import admin from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',views.home, name='home'), path('add.html', views.add, name = 'add'), path('art.html', views.art, name = 'art'), path('login', views.login, name = 'login'), path('signup', views.signup, name = 'signup'), path('logout', views.logout, name = 'logout'), path('rating', views.rating, name = 'rating') ] urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) models.py class Songs(models.Model): """ Fields for storing song data """ song_name = models.CharField(max_length = 30, blank = False) genre = models.CharField(max_length = 30, blank = False) artist = models.ManyToManyField(Artists) cover = models.ImageField(upload_to = 'pics', blank = False) release_date = models.DateField() def __str__(self): return self.song_name views.py def home(request): a … -
How to redirect to the same/current page in django?
Hi I'm trying to develop a website for an online store with Django. For my view, when it adds a new product to the cart, I want to give a success message, but because I have pagination, it's always redirected to my home page, which is very annoying as a User. When I'm in my page=2, I want to add a product and stay at that page and not get redirected to the home page. Can someone please help me with this? My views.py: from django.shortcuts import render, redirect, HttpResponseRedirect, Http404 from products.models import Product from .models import Cart, CartItem from django.contrib import messages from django.urls import reverse from django.utils.safestring import mark_safe def cart(request): try: the_id = request.session['cart_id'] except: the_id = None if the_id: cart = Cart.objects.get(id=the_id) context = {"cart":cart} else: empty_message = "Your cart is empty, please keep shopping." context = {"empty": True, "empty_message": empty_message} template = 'shopping_cart/cart.html' return render(request, template, context) def add_to_cart(request, slug): request.session.set_expiry(120000) try: qty = request.GET.get('qty') update_qty = True except: qty = None update_qty = False try: the_id = request.session['cart_id'] except: new_cart = Cart() new_cart.save() request.session['cart_id'] = new_cart.id the_id = new_cart.id cart = Cart.objects.get(id=the_id) try: product = Product.objects.get(slug=slug) except Product.DoesNotExist: raise Http404 except: pass cart_item, … -
sending custom error message on facing exception in django
I am trying to get proper error messages for the client .Currently , the error handling is this way . except Exception as error: return Response( {'errors': str(error) }, status=status.HTTP_400_BAD_REQUEST, ) where we just convert error into str and send but this makes life hard for client side .This is my response . { "errors": "{'total_employees': [ErrorDetail(string='Ensure this value is less than or equal to 2147483647.', code='max_value')], 'contact_phone_number': [ErrorDetail(string='Phone number must be entered in the correct format .', code='invalid'), ErrorDetail(string='Ensure this field has no more than 12 characters.', code='max_length')]}" } How do we convert our error into proper formatted messages . -
How to visualize tuple data through cytoscape.js in Django?
currently I am trying to use Cytoscape.js to visualize Individual-Individual interaction network. An example of my data is like this: source = ["a", "b"] target = ["b,c","a,d"] My strategy is to make the source and target form tuples in django, like this: bi_tuples = [("a","b"), ("a","c"), ("b","a"),("b","d")] I have succeeded in making this tuple list. But I'm not familiar with Cytoscape.js. I have no idea about how to visualize these tuples. Does anyone know how to use cytoscape.js to visualize these tuples? I'll be very appreciated if you can help me! -
Best practice on how to integrate a settings file for the init of an own python package?
I have created an own python package (let's call it OwnRep) within which I need to use config settings like database access address, credentials, etc. I want to use the own package in other projects. Now, what I want to avoid is that my credentials are hardcoded within OwnRep.Therefore, I have started to think about intialising my OwnRep package with some sort of settings setup similar to Django and SciPy, so that the package's setup are set dynamically. Any solution proposals for this? A conceptual picture is attached as a link enter image description here -
Update many-to-many field in django by fieldname
I am building an API with Django that allows an external app to send posts to my API an then it inserts the received data into my database. Here are my simplified models: class Region(models.Model): name = models.CharField(max_length=250) class Event(models.Model): name = models.CharField(max_length=250) region = models.ManyToManyField(Region) I receive from the api some new Event data like this: data = { "name": "First Event", "region": "4" # this is the ID of the region } I'm trying to create a new event like this: Event.objects.create(**data) But I get the following error: Direct assignment to the forward side of a many-to-many set is prohibited. Use region.set() instead. The problem is that I can not use new_event.region.add(4) cause region is a string and, since this is an API, the field is always retrieved as a json key. I read this question https://stackoverflow.com/questions/8360867/update-many-to-many-field-in-django-with-field-name-in-variable#= which is asking exactly the same, but the given answer is not working cause when I write: new.__getattribute__(relation_name) = my_authors as suggested there, i get the following error, which makes sense: SyntaxError: can't assign to function call So how can I add a manytoMany field value by the fieldName? -
Problems with implementing inviting feature
I am working on the social network project and want to create feature that will give me opportunity to invite users to communities with invite url(UUID).Who can explain how to do that, i have tried to do that with context processors,but it doesn't work -
Why am I getting NoReverseMatch error message?
I am putting together a website which has a photo gallery where users can add comments. When I go to the photo gallery page, I get the following error message: NoReverseMatch at /photo_feed/ Reverse for 'add_comment' with arguments '('',)' not found. 1 pattern(s) tried: ['add_comment/$'] The code for the relevant part of the HTML document is as follows: <h2>comments</h2> {% if not comments %} No comments {% endif %} {% for x in comment %} <div class="comments" style="padding: 10px;"> <p class="font-weight-bold"> <h4>Comment by</h4> {{ x.user }} <span class=" text-muted font-weight-normal"> {{ x.created_on }} </span> </p> {{ x.body | linebreaks }} </div> {% endfor %} </div> <div class="card-body"> {% if new_comment %} <h2>Your comment has been posted.</h2> {% else %} <h3>Leave a comment</h3> <form action="{% url 'nowandthen:add_comment' image.id %}" method="POST"> {{ comment_form.as_p }} {% csrf_token %} <button type="submit" class="btn btn-primary btn-lg">Submit</button> {% endif %} The URLs.py entry for add_comment is path('add_comment/<int: image_id>', views.add_comment, name='add_comment'). Removing the int: image_id doesn't fix the problem. When I go into admin, no ids appear to have been generated for the photos. Could it be that the problem is that there are missing IDs? If so, how do I fix this? The repository URL is https://github.com/EmilyQuimby/my_now_and_then. … -
CSRF Token request position Django and Nuxt
lately i'm trying to implement a login api for a website. I'm using Nuxt for the FE, Django REST Framework for the BE and Nuxt Auth Module for the JWT. Now I tryed to use the normal option for implement my api: https://auth.nuxtjs.org/schemes/local.html#options auth: { localStorage: false, redirect: { logout: '/login' }, cookie: { options: { expires: 7} },//7 minuti strategies: { local: { endpoints: { login: { url: 'http://127.0.0.1:7777/api/users/login/', method: 'post', propertyName: false}, user: { url: 'http://127.0.0.1:7777/api/users/infoUser/', method: 'get', propertyName: false}, logout: { url: 'http://127.0.0.1:7777/api/users/logout/', method: 'post'}, }, tokenRequired: false, tokenType: false } } }, but in Django I don't see the token on vscode debug mode. I need the token for retrieve the user infos. Can someone help me? Thank you. -
Django Rest Framework returns 302 on PUT and PATCH and doesn't update anything
I've coded serializer and views that should update instances of a model object. When I test the API through THe Django Rest Browsable API, the process works fine but it doesn't when I use curl. curl requests (GET, PATCH and PUT) shows 302 on the server and nothing is updated when method is patch: curl command is : curl -X PATCH -H "Content-Type: application/json" -d '{ "status": "undefined", "started_at": "2022-03-31T08:22:54"}' http://localhost:8000/wf/machineworks/b79ac69b-e9a6-410b-bfbd-a79b0163f69a and, for the curl command, the server gives : [31/Mar/2020 12:50:33] "PATCH /wf/machineworks/b79ac69b-e9a6-410b-bfbd-a79b0163f69a HTTP/1.1" 302 0 whereas the same update in the browsable api gives : [31/Mar/2020 13:20:25] "PATCH /fr/wf/machineworks/b79ac69b-e9a6-410b-bfbd-a79b0163f69a/ HTTP/1.1" 200 12588 __ here is the curl log :__ == Info: Trying 127.0.0.1... == Info: TCP_NODELAY set == Info: Connected to localhost (127.0.0.1) port 8000 (#0) => Send header, 184 bytes (0xb8) 0000: PATCH /wf/machineworks/b79ac69b-e9a6-410b-bfbd-a79b0163f69a HTTP 0040: /1.1 0046: Host: localhost:8000 005c: User-Agent: curl/7.58.0 0075: Accept: */* 0082: Content-Type: application/json 00a2: Content-Length: 61 00b6: => Send data, 61 bytes (0x3d) 0000: { "status": "undefined", "started_at": "2022-03-31T08:22:54"} == Info: upload completely sent off: 61 out of 61 bytes <= Recv header, 20 bytes (0x14) 0000: HTTP/1.1 302 Found <= Recv header, 37 bytes (0x25) 0000: Date: Tue, 31 Mar … -
how should i hack the django code to avoid this?
when i run this : 'python manage.py runserver' i get this error : Traceback (most recent call last): 'DIRS': [BASE_DIR /' templates'], TypeError: unsupported operand type(s) for /: 'str' and 'str' -
How to save data from the User form that is implemented by inbulit auth. User using UserCreationForm in Django?
Hi I am new to Django and I have created a login/logout model Django inbuilt User and UserCreationForm. It is working fine but my issue is I have define two custom inputs in my form and it is displaying on the web page when I run the server but when I check the user under the admin, I only see the details of User defined fields not my custom fields. How to save it's data to my User model? or maybe If I defined the custom fields wrong how do I change it so that I can save it's data in my model. My custom defined fields that is address and phone number is not showing in Admin User and it's data is not getting saved. Please Help!!! model.py from django.db import models from django.contrib import auth # Create your models here. class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django import forms class UserCreateform(UserCreationForm): address = forms.CharField(max_length=150, required=True) phone_number = forms.IntegerField(required=True) class Meta(UserCreationForm.Meta): model = get_user_model() fields = ('username','email','password1','password2') def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = 'Display Name' views.py from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import CreateView from . … -
Django, Docker, and Pipenv - Error adding new packages, not transfering from container to local volume
I'm following allong with the book 'Django for Professionals' but I run into what seems like the same problem the author of the book experienced in this quastion. I'm using it on windows so with Docker-toolbox and what seems to happen is that after running docker-compose exec web pipenv install psycopg2-binary==2.8.4 the Pipfile.lock has changed inside the container, but it doesn't transfer/sync this to my local files, it seems as if the 'volume' lost track of the file? I opened the Pipfile.lock inside the container to verify that it indeed added psycopg2, which it did, but when I docker-compose down it is not in my local Pipfile.lock and thus lost the next time when I use docker-compose up -d --build The only solution I have found myself so far is to copy the file over from the running docker container to my local folder with which is far from ideal docker cp web:/code/Pipfile.lock . output from docker-compose exec web pipenv install psycopg2-binary==2.8.4 E:\Documenten\websites\code\postgresql>docker-compose exec web pipenv install psycopg2-binary==2.8.4 Installing psycopg2-binary==2.8.4… Adding psycopg2-binary to Pipfile's [packages]… ✔ Installation Succeeded Installing dependencies from Pipfile.lock (a06fa0)… 🐍 ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 5/5 — 00:00:09 To activate this project's virtualenv, run pipenv shell. Alternatively, run a command … -
even after creating a superuser, can not login in Django administration
I created a superuser in Django , then went to 127.0.0.1:8000/admin. There I get a login page where it asks for username and password. After entering the username and password which I made for the superuser ,it says "this site can't be reached" or "page not found". What to do ? please help. I saw many posts but they are of no help. Thanks for helping in advance. -
how to do delay in loop in Django template
i am making a website in Django python and using loop inside django template but i want delay in loop if you know how to do that please answer {% load range %} {% for value in 5|range:200 %} {{range}} {% endfor %}