Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Adding Item Mismatching
I'm currently working on To-Do App using Django. I have two models Todo and Task. I want to create a Todo and under the todo items I want to create a task items. As I was able to add todo items and task items. But the problem is If I want to add task item for Maths by default all the task Items are getting added to the first todo items. I think It's becaude In Task modal(pop up) form I have linked function url to retrieve the todo objects id when the add button clicked and also added bootstrap modal(pop up) form to the a-tag in html. It's not retrieving the corresponding todo item id instead It takes the 1st todo item id.(refer below images) models.py class Todo(models.Model): date_created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) title = models.CharField(max_length=200) user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.title class Task(models.Model): heading = models.CharField(max_length=100) todo = models.ForeignKey(Todo, on_delete=models.CASCADE, related_name='tasks') date_created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.heading views.py from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse, Http404, HttpResponseNotFound, JsonResponse, HttpResponseRedirect from .models import Todo, Task from .forms import * from django.utils import timezone from django.contrib.auth.forms … -
I don't understand why my formset is not valid
I am trying to make a registration panel in my project. When I check if the form is valid I get False in return and don't understand why When form is not valid in generally ? (I need to add some text, because I get an error) views.py @unauthorized_user def registerPage(request): form=createUserForm() if request.method == 'POST': form = createUserForm(request.POST) print (form.is_valid()) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') group = Group.objects.get(name='user') user.groups.add(group) email = form.cleaned_data.get('email') Customer.objects.create(user=user, name=username, email=email) messages.success(request, 'Account created for ' + username) print(group.user_set.all()) return redirect('login.html') context={'form':form} return render(request,'register.html',context) HTML file: <form action="" method="POST"> {% csrf_token %} <div class="container"> <div class="Username-label"> <label><b>Username</b></label> <input type="text" placeholder="Enter Username" required> </div> <div class="Password-label"> <label><b>Password</b></label> <input type="password" placeholder="Enter Password"required> </div> <div class="Email-label"> <label><b>Email</b></label> <input type="email" placeholder="Enter Email" required> </div> <button type="submit">Login</button> </div> </form> Models.py class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) -
My django's website on cpanel doesn't load my media files( images upload from admin ) but all my stacticfiles (css,etc)work when DEBUG= False
I have a django project that works very well and shows all media files uploaded from the admin when debug = True but immediately i turn change to debug = False django cannot find my media folder yet it loads my static folder. as you can see i have set up my MEDIA_ROOT and MEDIA_URL correctly. My settings.py # Static files (CSS, JavaScript, Images) import os STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') #HTTPS SETTING SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True My urls.py: urlpatterns = [ path('', include('appMain.urls',namespace='main')), path('auth/', include('appAuth.urls',namespace='auth')), path('blog/', include('blog.urls',namespace='blog')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) So i need some help to display my media files when debug= False -
Issues with saving Nested ManyToMany relationship with ModelSerializer
I have the following model: class Collection(models.Model): ... relationships = models.ManyToManyField('relationships.Relationships', related_name='collections', blank=True) ... I also have the following serializer: class CollectionSerializer(serializers.ModelSerializer): relationships = RelationshipSerializer(many=True) class Meta: model = Collection fields = [ ... 'relationships', ... ] read_only_fields = [ ... ] def create(self, validated_data): relationships = validated_data.pop('relationships') # Then we need to create an instance of the Collection object from the validated data: collection = Collection.objects.create(**validated_data) for relationship in relationships: relationship = Relationships.objects.get(uuid=relationship['uuid']) collection.relationships.add(relationship.id) return collection A sample body I am posting to the endpoint where this serializer is called is: -
(Ganache - Brownie - ERC20) Error with SendRawTransaction function
Hi guys, I'm testing an ERC20 and I have tried to connect to ganache-cli (port 8545) and Ganache-GUI (port 7545) but I get the same error when I make sendRawTransaction(signed_transaction): ValueError: {'message': 'VM Exception while processing transaction: revert', 'code': -32000, 'data': {'0x66aa9cfe2e008fcddf79541855a66c30ceb2d7cf916b2868073eeb43769c7914': {'error': 'revert', 'program_counter': 16, 'return': '0x'}, 'stack': 'c: VM Exception while processing transaction: revert\n at Function.c.fromResults (/usr/local/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:4:192416)\n at w.processBlock (/usr/local/lib/node_modules/ganache-cli/build/ganache-core.node.cli.js:42:50915)\n at processTicksAndRejections (internal/process/task_queues.js:97:5)', 'name': 'c'}} Contract deploying, contract creation, building transaction and signing transaction are ok, I also have tried to change gas price and gas but I get the same error... (I'm using brownie bake token)... Thanks! -
Django put firstname into form
I have a working form and I like to add my logged in user's first name into my form. I made is with the username, but I can't find a solutions for first name. I know the user_firsname is not working. I'm new to Django :) models.py class Stressz_teszt(models.Model): def __str__(self): return self.stressz_name user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) user_firstname = models.ForeignKey(User.firsname, on_delete=models.CASCADE, default=1) stressz_name = models.CharField(max_length=100) -
Django Rest Framework + Swagger : error { "detail": "CSRF Failed: CSRF token missing or incorrect." }
Hello I am using Django Rest Framework along with Swagger. I am getting this error upon POST request. { "detail": "CSRF Failed: CSRF token missing or incorrect." } This is quite strange considering the POST request contains "X-CSRFToken: 01658Gyfzlhz2v6zgoZjtbHSrWzrVTBrlseyp2JMfVHvh6PzfamHpgxuh4eaVXad" This is the complete request curl -X POST "http://127.0.0.1:8000/api/order-post/" -H "accept: application/json" -H "Content-Type: application/x-www-form-urlencoded" -H "X-CSRFToken: 01658Gyfzlhz2v6zgoZjtbHSrWzrVTBrlseyp2JMfVHvh6PzfamHpgxuh4eaVXad" -d "customer_name=Muhammad%20Ahsan%20Mukhtar&country=Pakistan&address=Cb%20679%20Kashmir%20Colony%20Gujranwala%20Cantt&email=ahsan44411%40gamil.com&postal_code=52250&country_code=4343&phone_number=243434&tracking_number=4343" I have even tried using csrf_exempt but that does not help either, I get the same error. @method_decorator(csrf_exempt, name="dispatch") class OrderPost(generics.ListCreateAPIView): queryset = Order.objects.all() serializer_class = OrderSerializer I am using the default settings for Django Rest Framework which is SessionAuthentication I believe. I've been stuck on this for hours without luck, any help will be appreciated. Thank you. -
How to force autocomplete to work on https site
To autocomplete the phone field in my app I use django-ajax-selects app (DAS): when an user types the numbers in the field, DAS displays the matching phone numbers. On localhost and on the site with http it works fine, but on the https site it doesn't work. The root of the problem is that the request from DAS to channel with phone numbers query via https is blocked giving the error 403 (Forbidden). An example from browser console by typing '911' in the phone field: jquery-2.2.4.min.js:4 GET https://mysite/ajax_select/ajax_lookup/clients?term=911 403 'clients' is the channel defined as: @register('clients') class ClientsLookup(LookupChannel): model = Client min_length = 4 # Minimum number of characters user types before a search is initiated. # Queryset matching the characters typed by the user def get_query(self, q, request): qs = self.model.objects.filter(phone__icontains=q)[:10] return qs Definitely, I need to tell the https server that the request from one part of my app to another part of my app is ok, but how? -
Select minimum values of records in database where a condition is satisfied with django ORM
I have the following model class Lances(models.Model): licitante = models.CharField(...) valor_prop = models.DecimalField(...) momento = models.DateTimeField(...) flag = models.CharField(...) situacao = models.CharField(...) item = models.ForeignKey(Items, on_delete=models.CASCADE) supose that my database have this state What I whant is a query with django orm that returns the minimmum value of each licitante that is ("Katálysis Comércio, Locação e Serviços em Equipamentos de Laboratório LTDA", 116000.0000,), ("AGILENT TECHNOLOGIES BRASIL LTDA", 117000.0000), ("PERKINELMER DO BRASIL LTDA.", 128500.0000) I have tried ordering by valor_prop and then select distinct licitante. queryset = Lances.objects.filter(item=355, situacao='').order_by('valor_prop').distinct('licitante').values_list('licitante', 'valor_prop') But no luck. Is there a way to return the minimum value of each licitante in a single query? -
how to change the Django password reset email style and content
So I'm using the built-in Django password reset system. It works fine, but I'm not satisfied with the email sent to the users. I want to change all of it, from styles to texts. But how am I supposed to do that? I have read some solutions here, but they are more confusing than being helpful. -
How to create a form that update several objects?
I have several customers and users in my project. I can assign a customer to a user with a form. You can look to my question that I answered from here Now, I listed countries of the customers. I want to create a form that when a user click the button next to country and select the username it will assign to selected user. Assigned operation is actually update a customer's user field. How can I do that? views.py def country_customer_list(request): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) customer_list = Customer.objects.filter(company=userP[0].company.comp_name) countries = Customer.objects.values_list('country', flat=True).distinct() context = { 'customer_list': customer_list, 'countries': countries } return render(request, 'country_customer_list.html', context) country_customer_list.html <table id="multi-filter-select" class="display table table-striped table-hover grid_" > <thead> <tr> <th>Country</th> <th>Operations</th> </tr> </thead> <tbody> {% for country in countries %} <tr> <td>{{country}}</td> <td> <div class="row"> {% if customer.user == null %} {% else %} {% endif %} <div id="demo{{ forloop.counter }}" class="collapse"> {% if customer.user == null %} {% comment %}<form method="post"> {% csrf_token %} {{ form|crispy }} <input type="hidden" name="customer_id" value="{{ customer.id }}"> <button type="submit" class="btn btn-success ">Assign</button> </form>{% endcomment %} {% else %} {# Assigned to {{ customer.user.first_name }} {{ customer.user.last_name }}#} {% endif %} </div> </div> </td> </tr> {% … -
Do data conversion after Django model object is fetched
I want to save the python dictionary inside the Django model as JSON and I want to convert that JSON back into a python dictionary when that data is fetched. I know I can do it inside view but I want to implement it in the model so it can return dictionary object when queried. is there any signal or any post_fetch method that I can use to achieve it, I couldn't find anything googling it... -
Change Heroku app's linked GitHub repository
I was working on a project on a private repository and we decided to deploy it into Heroku. Therefore we linked the Heroku app to that private repository. But now we had to move the project to a public repo and we don't know how to change the Heroku app so it deploys from the public repo instead of the old private one. Any help? -
How to start a django app with dynamic instance port in py eureka client?
here is my init file of my django app: import py_eureka_client.eureka_client as eureka registry_client, discovery_client = eureka.init(eureka_server="http://127.0.0.1:8761", app_name="django-app", instance_port=8088) I want to demonstrate dynamic scaling of application but cannot start the application on different port. Any suggestion? I'm very new to microservices. -
How do you get the next object in a parent object?
I need to create a function that returns the next object. I have a model named lectures that has a foreign key section model. How would you create a function that takes in a lecture object and finds the next lecture in the same section? I found next_by_FOO, but it doesn't appear to be able to search in a specific parent object. -
how can i load objects filtered through a form in django?
i'm using django to store photos in a server. these photos are stored through a model that has an imageField and a charField called tags. i'm looking to filter objects from my database using keywords i receive from a form. the form is in a file called navbar.html: <form class="form-inline my-2 my-lg-0" action="{% url 'filtered' searched_tags %}" method="GET"> <input class="form-control mr-sm-2" name="searched_tags" type="search" placeholder="Cerca" aria-label="Cerca"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Cerca</button> </form> i've defined a function in my views.py called filtered: def filtered(request, searched_tags): input_field = request.GET.get('searched_tags') print(input_field) filtered_photos = Photo.objects.filter(tags=input_field) context = {'photos': filtered_photos} return render(request, 'grid.html', context) (also i'm not sure why but print doesn't always work) and finally urls.py: urlpatterns = [ path('', views.home, name="home"), path('lazy_load/', views.lazy_load, name="lazy_load"), path('addPhoto/', views.addPhoto, name="addPhoto"), path('<str:searched_tags>', views.filtered, name="filtered"), ] i get the error : NoReverseMatch at / Reverse for 'filtered' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<searched_tags>[^/]+)$'] i've been looking for answers in here but i only found people using url in urls.py instead i'm using path. i also tried to understand reverse in the docs but i couldn't understand especially because all the example are using url. i know that this is not the best way to do … -
Django-Filter Form Output Error Not working
I am trying to display the search bar which when searched will display the entries of the form. However It is not happening. I am using Django Filters to filter the form so that end customer will be able to search for the query and find the required details. I am pasting the whole code below, If you think there is a better way than this to get the work done please do let me know. I am also sharing the link of the Github repository incase if you would like to try and see the error. I am stucked with this error from long time. NEED HELP VERY BADLY!!!!! filters.py import django_filters from .models import * from inventory_app.models import Form1 class ItemFilter(django_filters.FilterSet): item = django_filters.CharFilter(field_name='item', lookup_expr='icontains') class Meta: model = Form1 fields = ['item'] models.py from django.db import models #from django.utils import timezone # Create your models here. class Form1(models.Model): item = models.CharField(max_length=125) quantity = models.IntegerField(default=0) vendor = models.CharField(max_length=125) inward = models.IntegerField(default=1234) date = models.DateField() def __str__(self): return self.item # security_stamp_date = models.DateField(default=timezone.now) Form1_entries.html {% extends 'base.html' %} {% block title %} Form 1 Entries {% endblock %} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" … -
How to run a django signal only once in order to affect more than one model instance
Is it possible to run a django signal only once in order to affect more than one model instances? And when this signal will run? I don't want to use crontab library. Imagine that I have 10 instances of model A. I want to run a signal that creates an instance of model B for every instance of model A. Something like the below function but for all A instances: @receiver(signals.post_save, sender=A) def create_b(sender, instance, created, **kwargs): if created: B.objects.create() -
The script has an unsupported MIME type ('text/html'). Unable to resolve using firebase-messaging-sw.js
I am getting this error, The script has an unsupported MIME type ('text/html'). Unable to resolve using firebase-messaging-sw.js. const messaging = firebase.messaging(); messaging.requestPermission().then(function(){ console.log("have permission"); return messaging.getToken(); }).then(function(token){ console.log(token) }).catch(function(err){ console.log("Error"); }) -
How to access path url parameter in DRF serializer?
Short question: What's the appropriate way to access a url path parameter (not a url query parameter) in a Django DRF serializer? Context: A have a Django DRF api, where I have a url similar to : /api/blogposts/:blogid/comments that is handled by a generic view: class MyCommentsView(generics.ListCreateAPIView): queryset = Comment.objects.all() serializer_class = CommentSerializer (blog and comment are just example resources; i am working with different ones) This view allows via a POST call to create new comments. For legacy reasons, the request will contain the blog_id also as a request body parameter. In my Serializer I want to check if the :blogid in the url is identical to the blog_id in the body. Currently I do the following, but the path splitting and element selecting feels very fragile. So, is there a better way? class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = [..., 'blog_id', ... ] ... def validate_blog_id(self, value): blogid_in_url = int(self.context['request'].path.split('/')[-2]) # <- better way? if blogid_in_url != value: ... Note: my question is about a url path parameter, not a url query parameter. I know a url query parameter can be accessed via self.context['request'].query_params. -
ModuleNotFoundError: No module named 'ckeditor'
I installed CKEditor by pip this command: pip install django_ckeditor==6.0.0 and installed correctly because there is files in virtenv.(image added at the end) in my modules I have a class that use RichTextField: from django.db import models from ckeditor.fields import RichTextField from ckeditor_uploader.fields import RichTextUploadingField import datetime class Post(models.Model): Title = models.CharField(max_length=1000) Text = RichTextField() Date = models.DateField( default=datetime.date.today) Category = models.ForeignKey(Category,on_delete=models.PROTECT) Tags = models.ManyToManyField(Tags) Banner_Image = models.ImageField(upload_to='uploads') Short_Story = models.CharField(max_length=1000) but in the admin page when I go to the 'add post' link accord this error: Traceback (most recent call last): File "/home2/intellig/blog/passenger_wsgi.py", line 1, in <module> from blog.wsgi import application File "/home2/intellig/blog/blog/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/home2/intellig/virtualenv/blog/3.7/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/home2/intellig/virtualenv/blog/3.7/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home2/intellig/virtualenv/blog/3.7/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home2/intellig/virtualenv/blog/3.7/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/home2/intellig/virtualenv/blog/3.7/lib64/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/home2/intellig/blog/app/models.py", line 2, in <module> from ckeditor.fields import RichTextField ModuleNotFoundError: No module named 'ckeditor' 2021-03-05 11:40:29.936278 [UID:1812][18068] Child process with pid: 18089 was killed by signal: 15, core dump: 0 Traceback (most recent call last): File "/home2/intellig/blog/passenger_wsgi.py", line 1, in <module> from blog.wsgi import application File "/home2/intellig/blog/blog/wsgi.py", line … -
E-commerce stack for smaller-medium scale budget that works with django
I was asked to make an ecommerce app for somebody with a smaller-medium scale budget. Any setup suggestions that works with django like ssl, domain, payment gateway, and hosting. -
How to combine two lists into a json containing a dict inside having a key-value pair in python (for django)?
Hey guys I am trying to combine two lists, specifically tag_names and tag_slugs into this format for using it in frontend. I don't know which is the efficient way, but this is how I need. tags: { name: tag_name, slug:slug_name, name: 2nd, slug: 2nd slug, ... } This is what I have now. def get_tags(self, post): tags_name = post.tags.names() tags_slug = post.tags.slugs() print(tags_name, tags_slug) These are two querysets. <QuerySet ['one', 'two', 'One']> <QuerySet ['one', 'two', 'one_1']> Thanks. -
I am getting error MultipleObjectsReturned when trying to get an object in my database in the views
I am trying to implement some favourite function in my application. but when using the get_objects_or_404, I am getting this weird error. Error Log Exception Type: MultipleObjectsReturned at /product/ Exception Value: get() returned more than one Product -- it returned 6! vies.py def Products(request): title = "All Products" product = get_object_or_404(Product) products = Product.objects.all().order_by('-id') my_products = Product.objects.filter(user=request.user).order_by('-id') is_favourite = False if product.is_favourite.filter(id=request.user.id).exists(): is_favourite = True context = {"products":products, "my_products":my_products, "title":title, "is_favourite":is_favourite} return render(request, 'core/products.html', context) -
how to write a single view for 2 forms like signup and login in one html file
i have html file that contains both login and signup form <form method = "POST" enctype="multipart/form-data" > {{ user_form.as_p }} {% csrf_token %} <input type="text" id="firstname" placeholder="First Name" name = "first_name" required> <div class="invalid-feedback">Please enter a valid first name.</div> <input type="text" class="input-field" id="lastname" name = "last_name" placeholder="Last Name" required> <div class="invalid-feedback">Please enter a valid last name.</div> </form> and a similar login form how to write a single view for both of these forms using buttons i have already seen How can I build multiple submit buttons django form? this but i didn't found useful def user_login: if request.method == 'POST' and request.method.get['submit'] == 'name1': pass elif request.method == 'POST' and request.method.get['submit'] == 'name2': pass in this how to write else code if request.method not POST for every form