Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I keep getting this error when trying to use / setup django-shop [closed]
I am beginning to work with django-shop and django rest framework so I can develop back end REST APIs for e-commerce applications and keep getting this error : aise ImproperlyConfigured(msg.format(pm[0][0].__name__, pm[0][1])) django.core.exceptions.ImproperlyConfigured: Deferred foreign key 'OrderPayment.order' has not been mapped I have tried other solutions but they are of no use and fail. do help! thanks in advance :) -
Save image files in django-oscar database using S3 bucket
I am using django-oscar in my current project and trying to save the media files in an s3 bucket. I am adding the products in default dashboard in django-oscar. I am confused about how to save product images on s3 and the how to save image url in Product model. In order to achieve this, what should I do? Do I have to modify Product model and add a new field for image urls? Or tweaking STATIC_URL and MEDIA_URL would be enough? Here is my media configuration. STATIC_URL = '/static/' MEDIA_URL = "https://s3.amazonaws.com/<bucket_name>/" STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(STATIC_URL, 'media') -
How can I download OpenCV processed video as a django httpresponse file/attachment
I'm new to OpenCV. I am trying out a use case to import video in Django, process it and download the processed video as an attachment. while the importing and processing video is straight forward, I am facing issues in downloading the video as an attachment. considering the below code as an example: import numpy as np import cv2 cap = cv2.VideoCapture('input.avi') # Define the codec and create VideoWriter object #fourcc = cv2.cv.CV_FOURCC(*'DIVX') #out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480)) out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480)) while(cap.isOpened()): ret, frame = cap.read() if ret==True: frame = cv2.flip(frame,0) # write the flipped frame out.write(frame) cv2.imshow('frame',frame) if cv2.waitKey(1) & 0xFF == ord('q'): break else: break # Release everything if job is finished cap.release() out.release() cv2.destroyAllWindows() It is clear that the output is stored in output.avi using the cv2.VideoWriter. Kindly help in getting this output as a file/attachment in django. Thanks! -
How to display Matplotlib or Seaborn graph on a webpage
I am using django for a project.How I display some graph created by Matplotlib and Seaborn on html page -
Testing - Assert Django-Notification Sent
I am using django-notifications and have a view which, upon a successful POST, sends a django-notification to the admin user. I am wanting to test that the notification is sent when the POST has been successfully submitted, but dont know how. Im unsure how to even test this. My only idea is to check that the django-notifications db field has a new entry added to it, but i have been unsuccessful. Im guessing I would check somehow similar to this: self.assertEqual(1, notify.objects.count()) test.py: from notifications.signals import notify def test_notification_sent_to_admin_on_success(self): # admin user needed to receive notification admin = User.objects.create_superuser('admin', id=1) # current user user = User.objects.create_superuser('username') self.client.force_login(user) referer = 'http://testserver{}'.format(reverse('final_question')) # POST to final_question sends the notification to admin self.client.post(reverse('final_question'), { 'final_question': 'When can I start' }, HTTP_REFERER=referer) # check that notification was sent to admin self.fail('Incomplete Test') -
creating API to do calculations in backed using DRF
This question might be simple, but I like to know the proper way of doing this. I want to create some APIs that lets end user to send a string to the backed, and backend does some calculations to extract entities, and returns Jason response containing a dictionary of these entities. So in this process, I really don't need any model, any serialization and as the result no CRUD happens in my views. I can use normal Django in my view to render Json response using: return JsonResponse(dic) Also my input is currently entered in a Django form. so my question is that: 1- what would be the correct url pattern if i don't use django form. How should I retrieve string in my view based on this pattern. 2- can I use DRF here or return JsonResponse(dic) is efficient enough, Thanks -
Django admin change form widget from integer dropdown to checkbox
I have the following model with a positive small integer field for different status: class Shops(models.Model): STATUS_CHOICES = [ (0, 'Inactive'), (1, 'Active'), (2, 'Closed'), (3, 'Transferred'), ] status = models.PositiveSmallIntegerField("Status", choices=STATUS_CHOICES, null=True, blank=True) With this on the admin site status widget will be generated as select box But i want it to be a checkbox with the checkbox value be 0 and 1 following STATUS_CHOICE, and i already handle the list page to filter by status = 0 or 1 only On the admin page status would be like so: I tried to override the admin change form like so: #Form class ShopsForm(forms.ModelForm): status = forms.CheckboxInput() def __init__(self, *args, **kwargs): super(ShopsForm, self).__init__(*args, **kwargs) self.initial['status'] = False if self.instance: if self.instance.status is not None: try: self.initial['status'] = False if self.instance.status == 1: self.initial['status'] = True except: pass self.fields['status'].label = "Active" def clean_status(self): if self.cleaned_data['status'] is not None: data = self.cleaned_data['status'] else: data = None return data class Meta: model = Shops exclude = ['status'] #ModelAdmin class ShopsAdmin(admin.ModelAdmin): list_per_page = 50 form = ShopsForm list_display = ( ... 'status' ) list_display_links = ( ... 'status' ) fields = ( ... 'status', ) readonly_fields = ( 'id', ) def save_model(self, request, obj, … -
Connecting Django to Mongo Remotely
I'm trying to connect my MongoDB which is on another local server to Django and make migrations. This are my settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'ENFORCE_SCHEMA': True, 'NAME': "DjangoDB", 'USER': "somename", 'PASSWORD': "somepass", 'HOST': '172.17.1.147', 'PORT': '27017', 'AUTH_SOURCE': 'admin', 'AUTH_MECHANISM': 'SCRAM-SHA-1' } } Where everything match, but Django trying to connect to localhost in spite of set HOST and PORT above.. pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connect ion refused why? Forgot I set something? -
ValueError: needs to have a value for field “id” before this many-to-many relationship can be used
I'm working on a project like an E-commerce website. Everything works fine so far but if there's nothing in the user cart/bag the error will occur. I have tried the save method but I think I've done something wrong. Can someone helps me with the solution views.py def your_cart(request): user = User.objects.getFromUser(request.user) order = models.Order.objects.filter(owner = user, is_ordered = False) if (len(order)==0): order = models.Order() order.owner = raiuser else: order = order[0] items = order.items.all() if request.method == 'POST': demand_date = request.POST.get('demand_date') demand_date_obj = datetime.strptime(demand_date,"%m/%d/%Y %I:%M %p") order.demand_date = localtime.localize(demand_date_obj) order.save() return render(request, "rai_smartInventory/client_inventory/checkout.html", {'items':items}) models.py class Order(models.Model): owner = models.ForeignKey('user.User', on_delete=models.SET_NULL, null=True) is_empty = models.BooleanField(default=True) is_ordered = models.BooleanField(default=False) items = models.ManyToManyField(OrderItem) date_ordered = models.DateTimeField(auto_now_add=True) pickup_date = models.DateTimeField(blank=True, null=True) pickup_place = models.CharField(max_length=100,default='') description = models.CharField(max_length=100,default='') is_approved = models.BooleanField(default=False) is_returned = models.BooleanField(default=False) demand_date = models.DateTimeField(blank=True, null=True) def get_cart_items(self): return self.items.all() def __str__(self): return '{0}'.format(self.owner) def dict(self): return { 'id':self.id, 'owner':self.owner, 'date_ordered':self.date_ordered.isoformat() if self.date_ordered != None else '', 'is_approved':'Approved' if self.is_approved == True else 'Declined', 'pickup_date':self.pickup_date.isoformat() if self.pickup_date != None else '', 'pickup_place':self.pickup_place, 'description':self.description, 'is_returned':self.is_returned, 'demand_date':self.demand_date.isoformat() if self.demand_date != None else '', } Thank you in advance. -
How to send with Sendgrid a reset password email from a Django app deployed in Heroku?
I have been struggling for a while in trying to correctly setup the settings.py to send an email for password reset.This is my current configuration: SENDGRID_API_KEY = os.environ["SENDGRID_API_KEY"] SENDGRID_PASSWORD= os.environ["SENDGRID_PASSWORD"] SENDGRID_USERNAME= os.environ["SENDGRID_USERNAME"] EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = os.environ['SENDGRID_USERNAME'] #EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = os.environ["SENDGRID_PASSWORD"] EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = os.environ["DEFAULT_FROM_EMAIL"] #SENDGRID_SANDBOX_MODE_IN_DEBUG = False EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' I have come across the following posts that are related to my problem but none of them have worked: Sending SMTP email with Django and Sendgrid on Heroku No module named 'sendgrid_backend' in django Send email with Sendgrid in Django Setting up email with Sendgrid in Heroku for a Django App When I used the EMAIL_BACKEND = "sendgrid_backend.SendgridBackend"(after I installed the django-sendgrid-v5 library) I didn't receive any error but I didn't receive any email :'( and in the previous cases I encountered the following error SMTPServerDisconnected at /password-reset/ and Connection unexpectedly closed. Any help, suggestion, comment, crazy idea is really appreciated because I have spent several hours in this problem that will be a milestone in my project. Thank you everyone :) -
Improperly Configured
I am trying to make a https://dog.ceo/dog-api/ clone with Django Rest Framework. I got the error: "ImproperlyConfigured at /breeds/ Could not resolve URL for hyperlinked relationship using view name "breedimage-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.", and I am not sure how to solve it. Here is some of my code: models.py from django.db import models # Create your models here. class Breed(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class BreedImage(models.Model): breed = models.ForeignKey(Breed, related_name='BreedImages', on_delete=models.CASCADE) breedImage = models.ImageField(upload_to='photos') serializers.py from rest_framework import serializers from .models import Breed, BreedImage class BreedSerializer(serializers.ModelSerializer): BreedImages = serializers.HyperlinkedRelatedField(view_name='breedimage-detail', many=True, read_only=True, lookup_field='breed') class Meta: model = Breed fields = ['name', 'BreedImages'] views.py from django.shortcuts import render from rest_framework import generics from .models import Breed from .serializers import BreedSerializer # Create your views here. class BreedList(generics.ListCreateAPIView): queryset = Breed.objects.all() serializer_class = BreedSerializer class BreedDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Breed.objects.all() serializer_class = BreedSerializer urls.py from django.contrib import admin from django.urls import path from Breed import views urlpatterns = [ path('admin/', admin.site.urls), path('breeds/', views.BreedList.as_view()), path('breeds/<name>', views.BreedDetail.as_view()), ] I have followed this tutorial - https://www.django-rest-framework.org/api-guide/relations/#example. Thank you in advance for your help. -
How To Unit Test Crispy Error Messages Which Fail To Submit
Im unit testing my form and am wanting to test that if a user attempts to submit this blank field, the appropriate error message is displayed. I understand the problem I am having, that the form is not successfully submitting therefore is returning error 302, but I dont know how to test such cases. def test_error_message_for_incorrect_data(self): user = User.objects.create_superuser('username') self.client.force_login(user) response = self.client.post(reverse('study'), { 'years_of_study': '', } ) self.assertContains(response, escape('Please select an item in the list.')) the error message i am getting AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200) Thank you -
Syntax error with return function in Django application
I am working on a Django application that is meant to be a website for a pizza company. I have an error that I cannot figure out, and I cannot find a solution in the other forums. The line of code that has the error is return (f"{self.name} - $ {self.price}") The error says this: SyntaxError: invalid syntax -
How to add Search Index in elasticsearch document django?
I want to implement elasticsearch to search through the name field in the profiles. Suppose there are two users Hariharasudhan and Harish. Search query Hari should give me two users Hariharasudhan and Harish Search query Harish should give me only Harish But my code is returning two users for Harish also. I think it is because the search query is also using the edge_ngram tokenizer declared. I need help to resolve this issue. My elastic search document : from django.conf import settings from django_elasticsearch_dsl import Document, Index, fields from elasticsearch_dsl import analyzer, tokenizer from profiles.models import UserProfile #Signals from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from django_elasticsearch_dsl.registries import registry # Name of the Elasticsearch index INDEX = Index('profiles') # See Elasticsearch Indices API reference for available settings INDEX.settings( number_of_shards=1, number_of_replicas=1, max_ngram_diff = 50, ) html_strip = analyzer( 'html_strip', # tokenizer="standard", tokenizer=tokenizer('serializer','edge_ngram', min_gram=3, max_gram=6), filter=[ "lowercase"], ) @INDEX.doc_type class ProfilesDocument(Document): """User Profiles Elasticsearch document.""" id = fields.IntegerField(attr='id') name = fields.TextField(analyzer=html_strip) email = fields.TextField(analyzer=html_strip) user_details = fields.ObjectField( attr = "user_details", properties ={ "nickname" : fields.TextField(), "date_of_birth" : fields.DateField(), "roll_no" : fields.TextField(), "course" : fields.TextField(), "department" : fields.TextField(analyzer='keyword'), "batch" : fields.TextField(analyzer='keyword'), "gender" : fields.TextField(), "current_location" : fields.TextField(), "work_title" : fields.TextField(), "company_name" … -
Django: Search Form in Base Template
So I have a simple form to search for a zip code that I want in my base template so I don't have to render it in every view. I'm aware of this question but I can't seem to get their answer using context_processors to work for me. Not sure if it's because something's changed in Django or I'm just doing something wrong. Here's what I have: base.html {% load static %} <html> <head> <title>Restroom Rater</title> </head> <body> <h1>Restroom Rater</h1> <!-- THIS IS THE FORM I WANT ON EVERY PAGE --> <form action="{% url 'venue_list' %}"> {{ new_zip_form }} <input type='submit' value='Search'> </form> {% block content %} {% endblock %} </body> </html> views.py # import requests from django.shortcuts import render, redirect, get_object_or_404 from .forms import get_zip from . import yelp_api from .models import Venue def homepage(request): new_zip_form = get_zip() return render(request, 'restroom_rater/homepage.html', { 'new_zip_form': new_zip_form }) def venue_list(request): new_zip_form = get_zip() search_zip = request.GET.get('zip_code') if not Venue.objects.filter(zip_code=search_zip).exists(): venues = yelp_api.get_name(search_zip) venues = Venue.objects.filter(zip_code=search_zip).order_by('name') else: venues = Venue.objects.filter(zip_code=search_zip).order_by('name') return render(request, 'restroom_rater/venue_list.html', { 'venues': venues, 'new_zip_form': new_zip_form, 'search_zip': search_zip}) def venue_detail(request, venue_pk): venue = get_object_or_404(Venue, pk=venue_pk) return render(request, 'restroom_rater/venue_detail.html', {'venue': venue}) forms.py from django import forms class get_zip(forms.Form): zip_code = forms.CharField(required=True, label='Zip … -
how to run a django project (made on linux) on windows?
I am new to programming and started working on Linux, now I want to switch to windows and open my project there, look at the tutorials, it is written to activate the virtual environment in the Settings / activate.bat folder. but in my project there is no such folder and such file with the extension .bat. what should I do? -
Django inlineformset_factory with many to many relation
I need to make an inlineformset_factory in a CreateView, the relation between the parent and child models are many to many using the through argument to add an extra field on the intermediary model as described in django documentation. I've little experience on django and web development so I’ve a problem that I haven't been able to solve yet. Thanks before hand. The next sketch represents the result I need, in practice this sketch is form3 in my template; Final result These are my models; class TipoDiscapacidad(models.Model): tipo = models.CharField("Tipo de discapacidad", max_length=20) def __str__(self): return self.tipo class Persona(models.Model): primer_nombre = models.CharField("Primer nombre", max_length=30) segundo_nombre = models.CharField("Segundo Nombre", max_length=30, blank=True, null=True) apellidos = models.CharField("Apellidos", max_length=100) fecha_nacimiento = models.DateField() discapacitado = models.ManyToManyField(TipoDiscapacidad, through='Discapacidad', blank=True, null=True) nacionalidad = models.ManyToManyField(Nacionalidad) email = models.EmailField() tipo_sangre = models.ForeignKey(TipoSangre, on_delete=models.PROTECT) sexo = models.ForeignKey(Sexo, on_delete=models.PROTECT) estado_civil = models.ForeignKey(EstadoCivil, on_delete=models.PROTECT) licencia_conducir = models.BooleanField() titulo_academico = models.ManyToManyField(TituloAcademico) def __str__(self): return "{} {}".format(self.primer_nombre, self.apellidos) class Discapacidad(models.Model): discapacidad = models.ForeignKey(TipoDiscapacidad, on_delete=models.CASCADE) persona = models.ForeignKey(Persona, on_delete=models.CASCADE) porcentaje = models.FloatField() As you can see I'm using the through argument to point to the model that will act as an intermediary. Parent Model -> Persona Intermediary Model -> Discapacidad Child Model -> TipoDiscapacidad This … -
AttributeError: 'LoginUser' object has no attribute '_client'
I'm working on a GraphQL project using graphene-django. I wrote tests and after writing, I noticed that I had the following lines of code in all units that require authentication: response = self.query( ''' mutation tokenAuth($username: String!, $password: String!) { tokenAuth(username: $username, password: $password) { token } } ''', op_name='tokenAuth', variables={ 'username': '+2340000000001', 'password': 'testuser' } ) token = response.json()['data']['tokenAuth']['token'] For example, if there's a unit test_something_user in my User test case that requires authentication, I'd have to add the code as shown below and I have to do the same to every unit that requires it. class UserTestCase(GraphQLTestCase) ... ... def test_something_user(self): response = self.query( ''' mutation tokenAuth($username: String!, $password: String!) { tokenAuth(username: $username, password: $password) { token } } ''', op_name='tokenAuth', variables={ 'username': '+2340000000001', 'password': 'testuser' } ) token = response.json()['data']['tokenAuth']['token'] So I decided to write a reusable function that I could call whenever auth is required. from graphene_django.utils.testing import GraphQLTestCase from cnapi.schema import schema class LoginUser(GraphQLTestCase): def __init__(self, username, password): self.username = username self.password = password def token(self): response = self.query( ''' mutation tokenAuth($username: String!, $password: String!) { tokenAuth(username: $username, password: $password) { token } } ''', op_name='tokenAuth', variables={ 'username': self.username, 'password': self.password } ) return response.json()['data']['tokenAuth']['token'] … -
Django pagination without serializer
My api return json with data based in key/store etcd , so no queryset I would like add pagination , but i don't use model and serializer It's possible to add pagination without this ? -
Implementing Object-Dependent Condition on Django Model
I have a django model, for which I want to ensure first-last name combos are unique. One way of doing this is by adding constraints, such as with the following: class Meta: constraints = [UniqueConstraint(fields=['first_name', 'last_name'], name='unique_name')] However, this will not handle a situation with two objects where the names differ by capitalization (I want to identify 'First Last' with 'first last'). One can add a Q object to the constraint that defines a constraint, condition = Q(first_name__iexact=None) & Q(last_name__iexact=None) but I can't figure out what to put in place of None. How can I reference the first and last name fields there (simple first_name or self.first_name do not work)? On a related note, when is this sort of constraint preferable to implementing it in a clean() function? example models.py class Speaker(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) -
Can I use urls parameter again in Django?
path('list/<location_id>/', views.MyView.as_view(), name='myview'), path('list/<location_id>/<category_id>/', views.MyView.as_view(), name='myview_category') I use homepage 'myapp/list/2/', 'myapp/list/4/', ... I want to use category function in myview. But I can't write urls links that use location_id again in HTML. <li><a href="{% url 'cafeyo:myview_category' location_id=# category_id=1 %}">category 1</a></li> How can I use location_id??? Please Help me... -
How much knowledge do I need to have about object-oriented programming before I hit into the Django framework?
I finished the basics of python and I have two weeks start learning the object_oriented programming Actually, I do not want to spend so much time on it like what I did in the basics so I was wondering How much knowledge do I need for the Django framework is the basics enough or I have to dig into deeper topics? -
Print table information after onclick event in Django
I want to print table row information after button onclick event with Javascript Fuction. [Current Source] -view.py def table(request): test_list = TestInformation.objects.order_by() context = { 'test_list' : test_list, } return render(request, '/test.html', context) -test.html <label ~~ id="btn_click" onclick="btn()"> <table class="table table-bordered" id="data_table"> <thead> <tr> <th>ID</th> <th>Name</th> </tr> </thead> <tbody> {% for li in test_list %} <tr> <td> {{ li.Id }} </td> <td> {{ li.Name}} </td> </tr> {% endfor %} </tbody> </table> <Script type="text/javascript"> function btn { //I'd like to put above {for~~ endfor} source here! } </Script> -
Why is my Javascript not working for checking is Username already exists?
I am super new to Javascript, and I'm trying to implement some code that will search if a username already exists and then display an error if it does dynamically rather than having to hit submit and then finding out the username already existed. I tried implementing some JS but it's not working. What am I doing wrong? reg.html {% extends "dating_app/base.html" %} {% load bootstrap4 %} {% block content %} {% block javascript %} <script> $("#id_username").change(function () { var username = $(this).val(); $.ajax({ url: '/ajax/check_if_username_exists_view/', data: { 'username': username }, dataType: 'json', success: function (data) { if (data.is_taken) { alert("A user with this username already exists."); } } }); }); </script> {% endblock %} <br> <h1 class="text-center" style="color:#f5387ae6">Register to fall in love today!</h1> <form method="post" style="width:700px;margin:auto" action="{% url 'dating_app:register' %}" enctype="multipart/form-data" class= "form" > <div class="is-valid"> {% bootstrap_form registration_form%} </div> {% csrf_token %} {% for field in bootstrap_form %} <p> {{field.label_tag}} {{field}} {% if field.help_text %} <small style="color:grey;">{{field.help_text}}</small> {% endif %} {% for error in field.errors %} <p style="color: red;">{{error}}"</p> {% endfor %} </p> {% endfor %} <div class="form-check"> <input type="checkbox" id="accept-terms" class="form-check-input"> <label for="accept-terms" class="form-check-label">Accept Terms &amp; Conditions</label> </div> <div> <br> <button type="submit">Register</button> </div> </form> {% endblock content … -
Why am I getting a WinError 32 while deleting a file on django?
I added a function to my code that deletes files and text, when there is just text it deletes it with no problem but when there is a file(video) involved it returns a permission error [WinError 32], I dont know where am I bad but I think it might be on the views.py because I initially setted that code to just delete text. views.py def delete_video(request, video_id): delete_v = Post.objects.get(id=video_id) delete_v.delete() return HttpResponseRedirect('/') models.py (it has a @property that when a file is deleted, it also deletes it from the media folder) class Post(models.Model): text = models.CharField(max_length=200) video = models.FileField(upload_to='clips', null=True, blank="True") user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username') def __str__(self): return str(self.text) @receiver(models.signals.post_delete, sender=Post) def auto_delete_file_on_delete(sender, instance, **kwargs): if instance.video: if os.path.isfile(instance.video.path): os.remove(instance.video.path) urls.py urlpatterns = [ path('delete_clip/<int:video_id>/', views.delete_video, name='delete_video'), ] home.html <form action="delete_clip/{{ content.id }}/" method="post"> {% csrf_token %} <button type="submit">Delete</button> </form>