Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Management data missing or tampered with" while validation of formset of form with ArrayModelFields djongo
I am using djongo for MongoDB integration with Django. I have used two ArraymodelField inside my Model, which internally use Django's formsets. I keep getting Management data is missing or tampered with error while validating my form. I have read about the error and that it exists with formsets and including management data in template file like {{ formset.management_form }} solves it. I also read about prefix usage, which I do use for the ArrayModelFields, but I cannot understand how to explicitly specify it in my views.py file. Below is my code: models.py (Source and Destination are abstract models with ip, port, database, user, password as fields) class LobDetail(models.Model): lob_name = models.CharField(max_length=64, primary_key=True) type = models.CharField(max_length=20) source = models.ArrayModelField( model_container = Source, ) destination = models.ArrayModelField( model_container = Destination, ) def __str__(self): return self.lob_name + " "+ self.type views.py (LobDetailForm is a simple form with all fields included) def add_lobdetail(request): form = LobDetailForm if request.method == 'POST': print('Hey! I AM SUBMITTED') form = LobDetailForm(request.POST) if form.is_valid(): form.save(commit = True) return index(request) else: print('Error Form Invalid') return render(request, 'lobconf/add_lobdetail.html', {'formset': form}) add_lobdetail.html <script type="text/javascript"> $(function() { $('.nestedform_one').formset({ prefix: '{{ formset.source.prefix }}', formCssClass: 'dynamic-formset1', addText: 'Add another source', deleteText: 'Remove' }); $('.nestedform_two').formset({ … -
Is it correct use for Django ModelForm
My question; i'm used ModelForm instead of forms.Form and i want to organize form in html file instead of forms.py file (i don't want to use attr tag because my form.html file is very complicated) Is this usage correct? forms.py class CommentForm(forms.ModelForm): class Meta: model=Comment fields=[ 'name', 'email', 'comment', ] html file <form class="post-comment-form" method="POST"> {% csrf_token %} {% if form.errors %} {% for error in form.non_field_errors %} {{ error }} {% endfor %} {% endif %} <div class="form-row"> <div class="form-item half blue"> <label for="id_name" class="rl-label" >Name</label> {{ form.name}} </div> <div class="form-item half blue"> <label for="id_email" class="rl-label" >Email</label> {{ form.email}} </div> </div> <div class="form-row"> <div class="form-item blue"> <label for="id_comment" class="rl-label">Comment</label> {{ form.comment }} </div> </div> <button type="submit" class="save-button">Submit</button> -
How to run the html and jquery code in django?
I run the jquery file in html and it works but whenever I run the code within django framework within {%block content%} {%endblock%} the sliding function does not work. Why and how to resolve this issue? {% extends 'testapp/base.html' %} {%block content%} <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script> $(document).ready(function(){ $("#flip").click(function(){ $("#panel").slideToggle("slow"); }); }); </script> <style> #panel { display: none; } </style> </head> <body> <div id="flip">Click to slide the panel down or up</div> <div id="panel">Hello world!</div> </body> </html> {%endblock%} -
Using HyperlinkedModelSerializer can we make some fields(ForeignKey field) without url, only id(if doesn't have detail-view)
Im using django rest framework. In serializer I used HyperlinkedModelSerializer, but there are some foreign key fields with detail-view so it can be rendered as url, but some of them don't, it gives me the following error: 'Could not resolve URL for hyperlinked relationship using view name "unit-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.'. So how to fix it? serializers.py class MaterialSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Material fields = ('id', 'url', 'name', 'location', 'category', 'unit', 'type', 'price',) views.py class MaterialViewSet(viewsets.ModelViewSet): queryset = Material.objects.all() serializer_class = MaterialSerializer models.py class Material(models.Model): name = models.CharField(max_length=200) location = models.ForeignKey(Location, null=True, on_delete=models.CASCADE) category = models.ForeignKey(Category, null=True, on_delete=models.CASCADE) unit = models.ForeignKey(Unit, null=True, on_delete=models.CASCADE) type = models.CharField(choices=TYPE_CHOICES, default='material', max_length=200) price = models.FloatField(default=0, blank=True, null=True) So in my API I want to be my foreignkey fields 'location' and 'category' with url and 'unit' field only id -
int() argument must be a string, a bytes-like object or a number, not "list" : Django save model
I am trying to save a model but am unable to because of a TypeError I am being given. I have looked at other answers with similar errors but they are different problems. now = dateTime.now() miliTime = int(str(now.hour) + str(now.minute) timeConvert = miliTime - 1200 timeString = str(timeConvert) standard_t = timeString[:1] + ":" + timeString[1:] standardTime = standard_t + " " + p time_1 = standard_time time_2 = standard_time user = StaffMember.objects.get(id = request.session['client']['id']) userPunchCard = PunchCard.objects.get(employee = StaffMember.objects.get(name = user.name)) punch = [] try: if len(userPunchCard.time.punch) < 2: punch.append(time_2) userPunchCard.time = punch userPunchCard.save() except: punch.append(time_1) userPunchCard.time = punch userPunchCard.save() The main issue is trying to save the array. The try and except is to check for a punch is present. Heres the full error Message - TypeError: int() argument must be string, a bytes-like object or a number, not a 'list'. -
All errors result in URLconf circular import
Any error in my django app results in: The included URLconf 'appname.urls' 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. I realized when stepping through in pdb that any error that occurs in my app results in the URLconf error. The pdb will show the error that actually occurred, but if I continue the console will just print the URLconf error shown above. If I go and fix the error pdb showed such as the SyntaxError I resolved then everything works fine. It seems like any error I have just results in the URLconf error shown above and I am not sure how to resolve it so that I can see that actual error without going through pdb. -
Remove option from generic class view in Django
I just started learning Django this week and I'm trying to figure out how I can remove an option from a select menu being rendered in a class based view. The dropdown is for a Foreign Key field that links to my users table. The functionality here is that I do not want the current user logged into show up on that list (basically I don't want someone to be able to select themself). How can I go about doing this? View: class TransferCreateView(CreateView): model = Transfer template_name = 'points/transfer_form.html' fields = ['receiver', 'message', 'amount'] Model: class Transfer(models.Model): receiver = models.ForeignKey(User, null=False, on_delete=models.CASCADE, related_name='receiver') sender = models.ForeignKey(User, null=False, on_delete=models.CASCADE, related_name='sender') amount = models.IntegerField( validators=[ MinValueValidator(1), MaxValueValidator(1000)], null=False) message = models.CharField(max_length=100) date_sent = models.DateTimeField(default=timezone.now) Basically, I don't want the person who is the sender (which i was going to set in the code in a form_valid() function) to be an option for 'receiver' in the template when it renders. -
Default ModelForm Field (Foreign Key) From URL Parameter
I have a URL which contains a reference_id, this reference ID is getting passed to my HTML file to default the value of the ModelForm. My problem is that the field ModelForm field which I am defaulting is a Foreign Key to another model. The way that I am currently doing it, through the HTML file, the form does not submit due to the above. I'm wondering how I can set this form field to default to the parameter passed through the URL, make it read only, and still have it post to the Model. In the form posted below, it is the 'reference' field which I am attempting to default and in the HTML the tag is how I am currently doing it. Any thoughts or alternatives are more than welcome. MODELS.PY class Manifests(models.Model): reference = models.ForeignKey(Orders) cases = models.IntegerField() description = models.CharField(max_length=1000) count = models.IntegerField() def __str__(self): return self.cases FORMS.PY class CreateManifestForm(forms.ModelForm): class Meta: model = Manifests fields = ('reference', 'cases', 'description', 'count') VIEWS.PY def add_manifest(request, reference_id): if request.method == "POST": form = CreateManifestForm(request.POST) if form.is_valid(): form.save() return redirect('add_manifest', reference_id=reference_id) form = CreateManifestForm() manifests = Manifests.objects.all() context = { 'form': form, 'reference_id': reference_id, 'manifests' : manifests, } return … -
not finding the path
I have a problem with my code, I've tried to make a new URL file inside the app and in the main URL file put the function include but I have an error when i run the code, here's my code the error message: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/index Using the URLconf defined in f_project.urls, Django tried these URL patterns, in this order: admin/ ^$ ^first_app/ The current path, index, didn't match any of these. code for f_project.urls from django.contrib import admin from django.urls import path, include from first_app import views, urls urlpatterns = [ path('admin/', admin.site.urls), path(r'^$', views.index), path(r'^first_app/', include('first_app.urls')), ] code for first_app.urls from django.urls import path from first_app import views urlpatterns = [ path(r'^$', views.index, name='index'), ] please, someone help me to solve it -
Poor Django application degradation
I'm assigned to support an old Django application. This application used to run on gunicorn synchronous workers. However, it was getting slower. Recently, a engineer made a change to use gunicorn asynchronous workers with gevent. This week the system suffered a severe degradation when the number of HTTP requests increased. We received lots of error: can't start new thread on gevent.threadpool._add_thread. The Django view with most hits performs about 400 SQL queries before completing and renders a complex template. Could the elevated number of queries and CPU time to render the template be playing badly with this new async worker? And if so, how can I explain it to others? The connection pool is configured to not exceed the limit of postgres connections. -
How to refer to variables inside the hmtl template?
I have a beginners question. I followed a very quick tutorial on how to enter a data from a frame into database (http://www.learningaboutelectronics.com/Articles/How-to-insert-data-into-a-database-from-an-HTML-form-in-Django.php) <html> <head> <title>Create a Post </title> </head> <body> <h1>Create a Post </h1> <form action="" method="POST"> {% csrf_token %} Title: <input type="text" name="title"/><br/> Content: <br/> <textarea cols="35" rows="8" name="content"> </textarea><br/> <input type="submit" value="Post"/> </form> </body> </html> In the HTML above - I used name="title" and name="content" inside the views.py def createpost(request): if request.method == 'POST': if request.POST.get('title') and request.POST.get('content'): post=Post() post.title= request.POST.get('title') post.content= request.POST.get('content') post.save() return render(request, 'posts/create.html') else: return render(request,'posts/create.html') and that works perfectly, the data is entered into the database. Now I want to work with a free template I found on the internet. I have already edited the other parts of the HTML file, the remaining part is to work with the contact-form here below. The difference is they are using 'this.value' to pass the content of a field. Before I could distinguish between title and content, but now it's just one variable. How can I refer to that variable in my views.py ? The copy of the code of my interest is below. <div class="services_dark sj" id="signup"> <div class="container"> <h3 class="m_3"><center>Interested to join us?</center></h3> … -
FileSystemStorage doesn't work and when 2 images uploaded, SuspiciousFileOperation error is returned
I'm having a terrible issue. I want to upload 2 images and get a result after running them through a lot of code. However, when I choose the path (on the server) as to where to upload these files, I always get a "SuspiciousFileOperation" error. Thank you for your help! PS1: I'm using django as a back-end for my front-end so I need web services. PS2: This code was running fine before reinstalling Django and Python due to some tensorflow issues, but reinstalled all needed packages. Django version: 2.2.2 Python version: 3.6.7 (64-bits) #HERE IS THE VIEW import json import os from rest_framework import generics from rest_framework.response import Response from rest_framework import permissions from .ProcessData.FaceRecognition import FaceRecognition from .ProcessData.OCR import OCR from .ProcessData.Wanted import Wanted from identity.models import IdentityCheck from .serializers import IdentityCheckSerializer from rest_framework.generics import CreateAPIView from django.core.files.storage import FileSystemStorage from django.conf import settings class IdentityCheckView(CreateAPIView, generics.ListAPIView): serializer_class = IdentityCheckSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): request = self.request qs = IdentityCheck.objects.all() query = self.request.GET.get('q') if query is not None: qs = qs.filter(name__icontains=query) return qs def save_fss(self, filename, file): mediaRoot = os.path.join(settings.MEDIA_ROOT, 'media/tmp/') filename = filename + ".jpg" fs = FileSystemStorage(location=mediaRoot) if fs.exists(filename): os.remove(mediaRoot + filename) newFile = fs.save(filename, file) … -
Accessing many to many data in class-based detail view with models in different apps Django
I have two models related via ManyToMany relationship, but they are located in separate apps. I am trying to load details of one model then adding the manytomany field in the template but the conventional way is not working. Here is my code so far: models.py (listings app) from listing_admin_data.models import PropertyFeatures class Property(models.Model): .... property_features = models.ManyToManyField(PropertyFeatures) .... models.py (listing_admin_data app) class PropertyFeatures(models.Model): .... feature_name = models.CharField(max_length=50) .... views.py class PropertyDetailView(DetailView): model = Property context_object_name = 'property' Then in the template, I am trying to do this, but getting empty list, yet I have data. <h3>Property Features</h3> <ul class="amenities-list"> {% for feature in property.property_features.all %} <li>{{ feature.feature_name }}</li> {% empty %} <li>Property has no features!</li> {% endfor %} </ul> I tried this intentionally: <p>{{ property.property_features }}</p> And upon loading I get: listing_admin_data.PropertyFeatures.None on the browser. The other fields directly related to the object loaded are working fine, like {{ property.price }}, while those from ForeignKey are also working fine, i.e. {{ property.listing.listing_title }}. Is inter-apps model relationship handled the same way in Django or it has a special treatment? -
How to Unittest autocomplete.Select2QuerySetView (Django autocomplete light)
I'm Using the Django package Django Auto Complete light and here is how I use it: in the urls.py I use : path('buy-invoice-items-autocomplete/', views.ItemAutoComplete.as_view(), name='buy_invoice_items_autocomplete', ), then in the views.py : class ItemAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Item.objects.filter().order_by('id') if self.q: qs = qs.filter(Q(id__iexact=self.q) | Q(name__icontains=self.q)) return qs And finally i use it in my forms.py to let the user filter using it. Now when I try to include it in my unit tests file I do it this way : class TestItemAutoComplete(TestCase): def test_visit(self): self.client.get('/buy-invoice-items-autocomplete/') Using Coverage package it shows that my test is not covering the lines: if self.q: qs = qs.filter(Q(id__iexact=self.q) | Q(name__icontains=self.q)) How to reach this part in the class and test it ? -
Django Field is showing up in one view but not the other
I'm just starting out with Django and I have a problem where, when I added a field to my model (JobPost which inherits from models.Model) and it migrated successfully I can see and interact with the new field when I create a job post, but not when I view the JobPost (which is displayed using crispy forms using the {{ form|crispy }} tag. I have added the field name to my fields = [''] in my views.py models.py class JobPost(models.Model): #constants CLEARANCE_LEVELS=[(...),] author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) content = models.TextField() clearance_required = models.CharField(max_length=50, choices=CLEARANCE_LEVELS, default='None') date_posted = models.DateTimeField(default=timezone.now) views.py class JobDetailView(DetailView): model = JobPost class JobCreateView(LoginRequiredMixin, CreateView): model = JobPost fields = ['title', 'content', 'clearance_required'] # form_valid checks if the user is logged in def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) jobpost_form.html {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <!--Used to prevent some XSS Attacks (Cross-site request forgery) --> <fieldset class="form-group"> <legend class="border-bottom mb-4">Create Job Post</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> </div> {% endblock content %} So when I view it in my browser, I see the "clearance_required" field when I create … -
Execute alternative search in Django Rest Framework if object not found (404 error)
I'm prototyping something to learn more about fullstack development. On my website I have a search bar where users can search for podcasts. They first look into my database but if no item is found, I want to retrieve results from the iTunes API and display those (while at the same time saving those results in my database so that they are there for further searches). The frontend uses React while the backend uses Django Rest Framework. If the podcast is not in my database, a 404 is thrown. How can I catch the 404 exception before it's thrown and perform the search on iTunes? -
Job for gunicorn.socket not found
I am trying to setup gunicorn for my django website on the digitalocean but sudo systemctl start gunicorn.socket responds as "Job for gunicorn.socket failed". I have double checked for any spelling mistakes or directory path issues. I have been following this tutorial - https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 filepath = /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=myuser Group=www-data WorkingDirectory=/home/myuser/profile_website ExecStart=/home/myuser/profile_website/myenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ project2.wsgi:application [Install] WantedBy=multi-user.target filepath = /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target I have already tried restarting gunicorn.socket but it did not work. -
Query django postgres nested jsonfield
from django.contrib.postgres.fields import JSONField class Entity(Model): lang = CharField() data = JSONField() How can I query this model to find all objects that contain a given value. JSON can be nested. For example, if data is [ { 'name': 'Alfred', 'children': [{'name': 'Bob', 'children':['name': 'Melanie']}] }, { 'name': 'Harry', 'children': [{'name': 'Helen'}] } ] Then I want to return it if I search for Melanie. There can be any level of nesting. From the documentation Entity.objects.filter(data__values__contains=['Melanie']) doesn't work. -
How to share one Apscheduler Jobstore over 2 Django instances
I am running a Django App that creates 2 instances. I am using BackgroundScheduler to schedule a job and later remove it based on some conditions. Since there are 2 Django instances, the job still gets executed by the other instance. Is there a way to share a Jobstore over different instances so that I can still run 2 instances? -
Should UUIDFields be made unique and indexed in Django?
I have a model which has a UUIDField, that is not the primary key. The primary key is simply left as the default, a big integer field. import uuid class MyModel(models.Model): uuid = models.UUIDField(_('uuid'), default=uuid.uuid4, editable=False) Now my question is, should I explicitly declare the field to be unique? I realize the chance of collisions is very very small, which is probably why the Django documentation does not explicitly make the field unique. Also, should I also index the field in the database? Like so: import uuid class MyModel(models.Model): uuid = models.UUIDField(_('uuid'), default=uuid.uuid4, editable=False, unique=True, db_index=True) The field will mostly be used as an external identifier, where the id is generally not preferred. -
array don't Access in the tamplate
I want to known the number of views in each separately Playlist where I can store the view number for each one in the array and later display it in the tamplate but show me the array in the following in the tamplate: [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [1, 0, 1, … -
Auto save user in Django inline formsets with Class-based views and crispy forms
I am using Django inline formsets with Class-based views and crispy forms. Currently, I have a requirement in my project where a User can submit a request for a new Study Concept and any user in the Application can provide comments and share their opinion for a Study Concept. When a user enters her or his comments and submit the form, I want to auto save the currently logged in user to the user field. For example, User A created a new Study Concept and provided a comment (Please approve my request) while creating the new request. Then for the above comment user A should be saved. Later User B comes and edit this request and comments " Request looks good to me" and updates the form. Now user B should be auto saved for this comment. This is a new requirement for the project. I have tried various solutions available on stack-overflow, but I haven't succeeded yet. You can check in my code what currently I am trying to achieve. Please find my code below: models.py: class StudyRequestConcept(models.Model): CHOICES = ( ('Yes', 'Yes'), ('No', 'No'), ) REQUEST_STATUS = ( ('Pending', 'Pending'), ('Approved', 'Approved'), ('Denied', 'Denied'), ) APPROVER_CHOICES = ( … -
2 level of users in django
I am into development of a web based business application using django which will be used by 3 different companies. The business process is exactly same. I have stucked at user creation. I need 2 level of users. First the comany detail (higher level) and second 'n' number of users from that company itself which will be using the application. I have extended the default user model using ABSTRACTUSER to fulfill my fields requirement but I am not able to configure my requirement. I am asking for what could be the best way to achieve my goal and I would give a try to it. -
web socket with Django channels
I am writing a small prototype of e-vote where each person will vote, but the vote will be encrypted with Shamir's secret-sharing, so the result of the vote will be displayed only if all voters meet. i do not know if it's feasible but for that i would like to integrate django-channel to my existing project to create real-time communication between users and wait for all voters to log in and enter one of their passwords (to decrypt key numbers) in the database) and valid to display the results at temp reel (I never use Django-channel). so my question is: is it possible? and can i run WSS (websocket secure) in my localhost, if yes how? thanks , and sorry for my bad English . -
*** TypeError: get_value_by_attribute() missing 1 required positional argument: 'attribute'
I am using Django oscar and trying to get product attributes key and values using product.attr.get_value_by_attribute(). And I am getting above errors and I have tried to pass attribute and it still giving me an error. My testing debugger code is as follows: (Pdb) child_product <Product: Good Day 100 gm> (Pdb) child_product.__dict__ {'_state': <django.db.models.base.ModelState object at 0x7fa088e1c438>, 'id': 13, 'structure': 'child', 'upc': '', 'parent_id': 12, 'title': 'Good Day 100 gm', 'slug': 'good-day-100-gm', 'description': '', 'product_class_id': None, 'rating': None, 'date_created': datetime.datetime(2019, 6, 22, 15, 30, 24, 273252, tzinfo=<UTC>), 'date_updated': datetime.datetime(2019, 6, 22, 15, 30, 24, 273270, tzinfo=<UTC>), 'is_discountable': True, 'attr': <oscar.apps.catalogue.product_attributes.ProductAttributesContainer object at 0x7fa088e1c470>} (Pdb) child_product.attr <oscar.apps.catalogue.product_attributes.ProductAttributesContainer object at 0x7fa088e1c470> (Pdb) child_product.attr.__dict__ {'product': <Product: Good Day 100 gm>, 'initialised': False} (Pdb) child_product.attr.__dict__ {'product': <Product: Good Day 100 gm>, 'initialised': False} (Pdb) child_product.attr.get_values() <QuerySet [<ProductAttributeValue: Brand: Britania>, <ProductAttributeValue: Variant Name: 100 gm x 12>]> (Pdb) child_product.attr.get_all_attributes() <QuerySet [<ProductAttribute: Brand>, <ProductAttribute: GST Rate>, <ProductAttribute: HSN Code>, <ProductAttribute: Liquid Content>, <ProductAttribute: Parent Company>, <ProductAttribute: Promo SKU>, <ProductAttribute: Selling Lot Size>, <ProductAttribute: Sub Brand>, <ProductAttribute: Tags>, <ProductAttribute: Variant Name>, <ProductAttribute: Weight>, <ProductAttribute: Weight Unit>]> (Pdb) child_product.attr.get_value_by_attribute() *** TypeError: get_value_by_attribute() missing 1 required positional argument: 'attribute' (Pdb) child_product.attr.get_value_by_attribute(attribute="Brand") *** ValueError: invalid literal for int() with base …