Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check user permission in ModelViewSet
I am want to check permission of the user in my ModelViewSet to understand how much data must be given to him? -
Django : Error: 'duplicate key value violates unique constraint'
I have to save images with s3 when creating a new object for my website. I have a code to save my images that I use in my model's save method. When I use the django administration panel, I can easily create my object without any error. But when I try to create my object throught my view, I get this error : Error: 'duplicate key value violates unique constraint « store_shop_pkey »' I think that in my serializer's create method, I try to save my object twice : once for the image and once for the rest of my object's keys. I don't know how to resolve this issue. It works well with PUT method. Here is my code : models.py : class Shop(models.Model): name = models.CharField(max_length=255) category = models.ForeignKey(ShopCategory, on_delete=models.SET_NULL, null=True, blank=True) description = models.TextField(blank=True, null=True) path = models.CharField(max_length=255, unique=True, null=True, blank=True) # Set a null and blank = True for serializer mustBeLogged = models.BooleanField(default=False) deliveries = models.FloatField(validators=[MinValueValidator(0),], default=7) message = models.TextField(null=True, blank=True) banner = models.ImageField(null=True, blank=True) def save(self, *args, **kwargs): try: """If we want to update""" this = Shop.objects.get(id=self.id) if self.banner: image_resize(self.banner, 300, 300) if this.banner != self.banner: this.banner.delete(save=False) else: this.banner.delete(save=False) except: """If we want to create … -
Hi i want to convert django project to exe format
Hi i want to convert django project to exe format I have converted python file to exe. But don't know about django to exe. Please anyone help me to do this -
E: dpkg was interrupted… run 'sudo dpkg --configure -a'
I was trying to deploy a Django project on AWS Deep Learning AMI (Ubuntu 18.04) Version 48.0. When I try to install packages I get this. "E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem." And when I run 'sudo dpkg --configure -a' nothing happens after this and the terminal get freeze Setting up linux-headers-5.4.0-1055-aws (5.4.0-1055.58~18.04.1) ... /etc/kernel/header_postinst.d/dkms: * dkms: running auto installation service for kernel 5.4.0-1055-aws Kernel preparation unnecessary for this kernel. Skipping... Building module: cleaning build area... 'make' -j32 NV_EXCLUDE_BUILD_MODULES='nvidia-drm ' KERNEL_UNAME=5.4.0-1055-aws IGNORE_CC_MISMATCH='1' modules..... -
How to set VSCode settings, so that an import is possible?
I have cloned a github repo and a project structure of it is a following (There are some files and subfolders in Lib\site-packages, Scripts\ and static\ ): -e_commerce\ --.idea\ --e_commerce_website\ ----.gitignore.txt ----db.slite3 ----manage.py ----requirements.txt ---.idea\ ---.vs\ ----e_commerce\v16\.suo ----ProjectSettings.json ----slnx.sqlite ----VSWorkspaceState.json ---e_commerce_env\ ----Include\ ----Lib\site-packages\ ----Scripts\ ----pyvenv.cfg ---ecom\ ----__pycache__\ ----___init___.py ----asgi.py ----settings.py ----urls.py ----wsgi.py ---static\ ---store\ ----__pycache__\ ----migrations\ ----templates\ ----___init__.py ----admin.py ----apps.py ----models.py ----tests.py ----urls.py ----views.py For example, in apps.py (and other files) an error occurs: Import "django.apps" could not be resolved from sourcePylance. ... which shows because of the line: from django.apps import AppConfig I have created an environment e_commerce_env which works successfully when I run the server from cmd / powershell. I checked where django is installed when being inside the env, and it turns out that the path is equal to: c:\users\user\desktop\e_commerce\e_commerce_website\e_commerce_env\lib\site-packages Should I set this path somewhere in VSCode to make it work? -
Media files don't preview - Django
I have a problem with media files. I read everything on Net and tried all offered solutions but nothing works. This is settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,"static") STATICFILES_DIRS = (os.path.join(BASE_DIR, './myapp/static/'), ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') This is urls.py: urlpatterns = [ path('application/admin/', admin.site.urls), path('application/accounts/', include('django.contrib.auth.urls')), path('application/', include('myapp.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is part of template where image needs to show: {% if word.image %} <img src="{{ word.image.url }}" alt="img" class="wordImg"> {% else %} <p class="wordPar">No image to preview</p> {% endif %} Everything seems fine to me but obviously there is a mistake, because image cannot preview. I get this: image cannot preview Thanks for help! -
How do I filter in URL a serializer when it's nested in another serializer In Django?
I'm creating an API that has nested data like in the picture Now how to search nested data in URL here's my model class Robot(models.Model): robot = models.CharField(max_length=100) short_Description = models.CharField(max_length=200) status = models.CharField(max_length=20) parameter = models.CharField(max_length=200) jenkins_job = models.CharField(max_length=100, default='JenkinsJobName') jenkins_token = models.CharField(max_length=100, default='JenkinsToken') def __str__(self): return self.robot class assignParameter(models.Model): parameterName = models.CharField(max_length=100, blank=True) assignRobot= models.ForeignKey(Robot, on_delete=models.CASCADE, related_name='param', blank=True, null=True) Here's my serializer.py from .models import Robot,assignParameter from rest_framework import serializers class assignParameterSerializer(serializers.ModelSerializer): class Meta: model = assignParameter fields = ['id', 'parameterName', 'assignRobot'] class RobotSerializer(serializers.ModelSerializer): param = assignParameterSerializer(many=True, read_only=True) JenkinJobName = jenkinsHistorySerializer(many=True, read_only=True) class Meta: model = Robot fields = ['id', 'robot', 'short_Description', 'status', 'parameter', 'jenkins_job', 'jenkins_token', 'param'] and here's my view for the api class RobotViewSet(viewsets.ModelViewSet): queryset = Robot.objects.all() serializer_class = RobotSerializer filter_backends = [filters.DjangoFilterBackend] filterset_fields = ['robot', 'JenkinJobName__jenkinsBuildNumber'] authentication_classes = [BasicAuthentication] permission_classes = [IsAuthenticated] in the API URL if I want to search a particular robot then using this URL URL/?robot=robotname I'm able to search that particular robot. But how can I search particular nested data using URL? using my view I'm getting search filters like this But that is not performing any Search. how to achieve that search and what is wrong with my code can … -
IntegrityError at /accounts/register/ NOT NULL constraint failed: accounts_profile.user_id
Hi everybody :) I try to add a profile user in my application.The goal is to create a profile in the same time that we create an account. But This error come : IntegrityError at /accounts/register/ NOT NULL constraint failed: accounts_profile.user_id I don't understand what is the probleme with my code because I have follow a youtube tutorial where this code works.. here is my code : views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from .forms import UserForm, ProfileForm # Create your views here. def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) profile_form= ProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): user = form.save(commit=False) profile = profile_form.save(commit=False) profile.user = user user.save() profile.save() return redirect('account:login') else: form = UserCreationForm() profile_form = ProfileForm() context = { 'form' : form , 'profile': profile_form, } return render(request, 'accounts/register.html', context) models.py : from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') birthday = models.DateField() mail = models.EmailField(max_length=254, null = True, blank = True) def __str__(self): return self.user.username forms.py : from django import forms from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.contrib.auth.models import User from .models import Profile class LoginForm(AuthenticationForm): … -
ClientConnectorCertificateError
I get an error. What is the reason for this error. I try to catch data from the api with an async function and it comes this error. ClientConnectorCertificateError at / Cannot connect to host swapi.dev:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1091)')] async def index(request): start_time = time.time() url = 'https://swapi.dev/api/starships/9/' async with aiohttp.ClientSession() as client: task = asyncio.ensure_future(fetch(client, url)) results = await asyncio.gather(task) total = time.time() - start_time print(total) return render(request, 'index.html', {'results':results }) -
Search multiple tags at same time
I am building a small Social Media App. I am making a features of searching multiple posts using multiple tags like :- first_post , second_post. AND It will retrieve all the posts which are associated with searched tags. When i search one tag then it is working fine BUT When i search two tags then it is not working ( showing nothing ). models.py class UserPost(models.Model): post_creater = models.ForeignKey(User, on_delete=models.CASCADE) tags = TaggableManager() body = models.CharField(max_length=30,default='') views.py def search_posts(request): search_it = request.GET.get('q') items = '' if search_it: items = UserPost.objects.filter(tags__name__icontains=search_it) context = {'items': items} return render(request, 'search_posts.html', context) When i search just one item like post_1 then it is showing all the posts BUT When i search two tags like :- post_1 , post_2 then it is showing nothing. I also tried using split method :- search_it = search_it.split('+') BUT it is still showing blank. I will really appreciated your Help. Thanks -
Django: Why i m getting 404 when i try to delete an object from my database?
i have an uploads model and i want to be able to delete the images, so i wrote a delete request that takes the id of the image however i keep getting 404 not found, i have the same thing and same steps for the files model that i created and it works fine. @api_view(['GET', 'POST','DELETE']) def Upload_list(request): if request.method == 'GET': queryset = Uploads.objects.all() uploads=queryset.filter(owner=request.user) serializer = UploadSerializer(uploads, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = UploadSerializer(data=request.data) if serializer.is_valid(): serializer.save(owner=request.user) respFile=list(File.objects.filter(id=str(File.objects.latest('created_at')))) serializers=Fileserializers(respFile,read_only=True,many=True) return Response(serializers.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def UploadsDetails(request,pk): try: image=Uploads.objects.get(pk=pk) except Uploads.DoesNotExist: return HttpResponse(status=404) if request.method =='GET': serializers=Fileserializers(image) return JsonResponse(serializers) elif request.method =='DELETE': image.delete() return HttpResponse(status=204) these are the urls: from django.urls import path from .views import Upload_list,login from .views import UploadsDetails urlpatterns=[ path('Uploads/',Upload_list), path('Uploads/<uuid:pk>/',UploadsDetails), path('login/', login) ] -
how can solve out circular import error in django
I have created MeterModel and MeterAbstract in app MeterApp. MeterAbstract have Meter_number and MeterModel have related field of Meter. I used MeterAbstract in BillModel. from MeterApp import MeterModel class BillDetailModel(BillAbstract, MeterAbstract): Bill_Name=models.CharField(max_length=20, null=True, blank=False) . . Now I want to update some field of MeterModel so I override save method to update and use def save(self,*args, **kwargs): meter = MeterModel.objects.filter(meter_number=self.meter_number) But giving error on from MeterApp.models import MeterModel ImportError: cannot import name 'MeterModel' from partially initialized module 'MeterApp.models' (most likely due to a circular import) How can I solved this and use abstract fields to override save method? -
How to loaddata only if it's not exist in DB with Django fixtures
I have some initial data to load with ./manage.py loaddata command. It's working correctly the problem is that when I call the loaddata function I want to load that data when the data is not there already if the data already loaded then I want to skip this step -
User login in Django + React
I have looked through quite a few tutorials (e.g. this, this, and this) on user authentication in a full-stack Django + React web app. All of them simply send username and password received from the user to the backend using a POST request. It seems to me that, if the user leaves the computer unattended for a minute, anyone can grab his password from the request headers in network tools in the browser. Is this a valid concern that must be taken care of? If so, how should these examples be modified? A tutorial / example of the correct approach would be appreciated. -
Django reset password via SMS
I'm working on a Django app, and I would like to authenticate users using their phone numbers, I also would like users to be able to reset their passwords via SMS, is there a way to do it, I can't seem to find anything referencing password reset via SMS in Django, thanks in advance. -
How to use open AI Codex in existing python projects.?
I want to develop a proof of concept based on open AI codex.I have tried with documentation but i am not getting that ,from where i have to start .So i want to know that how to develop a project or proof of concept with codex.I have knowledge in python So just want to use the Codex to use it in my existing projects. https://beta42.api.openai.com/codex-playground I have tried curl https://api.openai.com/v1/engines/davinci/completions -H "Content-Type: application/json" -H "Authorization: Bearer YOUR_API_KEY" -d '{"prompt": "This is a test", "max_tokens": 5}' -
Related Field got invalid lookup: icontains - While Search Tag
I am building a BlogApp and I am trying to implement a search field which will search ( filter ) with entered tag. When i try to access the page then it is keep showing Related Field got invalid lookup: icontains models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') tags = TaggableManager() views.py from taggit.models import Tag def search_page(request): query = request.GET.get('p') object_list = BlogPost.objects.filter(tags__icontains=query) context = {'posts': object_list, 'query': query} return render(request, 'search.html', context) I have also tried different methods but still showing the same error. I tried .filter(tags__in=query) then it showed NoneType' object is not iterable The i tried Tag.objects.filter(question__tags__icontains=query) then it showed Related Field got invalid lookup: icontains Any help would be much Appreciated. Thank You in Advance. -
save and load and fine tune ftlearn model?
I am trying to implement and simple chatbot model in django. So, I need to save the model and the weights in static files, to reuse them. Also, I need to add training data the to pre-trained model ( I think this called fine-tuning). problem1: when I use this code I got an error sayes NotFoundError: Restoring from checkpoint failed. This is most likely due to a Variable name or other graph key that is missing from the checkpoint. Please ensure that you have not altered the graph expected based on the checkpoint. Original error: new_model = tflearn.DNN(net) new_model.load('my_model.tflearn') problem2: I need to add new training data each week and in the code I added traning data only once. See the full code -
How could I translate a spatial `JOIN` into Django query language?
Context I have two tables app_area and ap_point that are not related in any way (no Foreign Keys) expect each has a geometry field, respectively of polygon and point type. The bare model looks like: from django.contrib.gis.db import models class Point(models.Model): # ... geom = models.PointField(srid=4326) class Area(models.Model): # ... geom = models.PolygonField(srid=4326) I would like to create a query which filters out points that are not contained in polygon. If I had to write it with a Postgis/SQL statement to perform this task I would issue this kind of query: SELECT P.* FROM app_area AS A JOIN app_point AS P ON ST_Contains(A.geom, P.geom); Which is simple and efficient when spatial indices are defined. My concern is to write this query without hard coded SQL in my Django application. Therefore, I would like to delegate it to the ORM using the classical Django query syntax. Issue Anyway, I could not find a clear example of this kind of query on the internet, solutions I have found: Either rely on predefined relation using ForeignKeyField or prefetch_related (but this relation does not exist in my case); Or use a single hand crafted geometry to represent the polygon (but this is not my … -
How to ensure a DKIM signature is sent when sending an email in Django through a custom office365 domain?
I have a domain registered with GoDaddy, and an associated Office365 account for email. I have setup DKIM and DMARC records for the domain. I have successfully checked that these are configured correctly by testing out emails sent from the office365 client to glockapps.com/inbox-email-tester-report and other sites. However, if I send a mail from the exact same address through my Django application, the DKIM signature is missing. I receive this error on glockapps Error details: This message doesn't contain DKIM signature matching your domain Is it a configuration issue in Django? These are my current settings. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = "hello@---.com" DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = EMAIL_HOST_USER EMAIL_HOST_PASSWORD = "---" EMAIL_PORT = 587 EMAIL_USE_SSL = False EMAIL_USE_TLS = True -
Tastypie resource filtering through foreign keys
I have some Django (3.1) models connected through foreign keys class Drone(models.Model): serial = models.CharField(max_length=200, null=False, unique=True) class Dive(models.Model): measurement_time = models.DateTimeField(db_index=True) drone = models.ForeignKey( Drone, on_delete=models.PROTECT, null=True, ) class Density(models.Model): measurement_time = models.DateTimeField(db_index=True) depth = models.IntegerField() density = models.FloatField(null=True) dive = models.ForeignKey( Dive, on_delete=models.PROTECT, db_index=True, null=True, ) I have a Tastypie (0.14.3) ModelResource class for my API defined like class DensityResource(ModelResource): class Meta: queryset = Density.objects.filter(dive__drone_id=13).order_by('-measurement_time', 'depth') that works as I'd expect for the single dive__drone_id. I want to implement get parameter filtering so I can do something like /?order_by=-measurement_time&order_by=depth&dive__drone_id=13 so I rewrote this class to class DensityResource(ModelResource): class Meta: queryset = Density.objects.all() filtering = { 'dive__drone_id': ALL } ordering = ['measurement_time', 'depth'] and the ordering works fine but not the filtering. What am I missing here? -
How do I access a single field while using For Loop to iterate through all the fields of a ModelForm in Django Template?
I have a model which has four ForeignKey fields, so they are dropdown fields in the form. class Package(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=models.ForeignKey(Treatment, on_delete=CASCADE) patient_type=models.ForeignKey(PatientType, on_delete=CASCADE) date_of_admission=models.DateField(default=None) max_fractions=models.IntegerField(default=None) total_package=models.DecimalField(max_digits=10, decimal_places=2) The forms.py: class PackageForm(ModelForm): class Meta: model=Package fields='__all__' widgets={ "patient_type" : forms.Select(attrs={"onblur":"mf();"}), "max_fractions" : forms.NumberInput(attrs={"onfocus":"mf();", "onblur":"tp();"}), "total_package" : forms.NumberInput(attrs={"onfocus":"tp();", "onblur":"onLoad();"}), 'date_of_admission': DateInput(attrs={'type': 'date'}), The views.py: def package_view(request): if request.method=='POST': fm_package=PackageForm(request.POST, prefix='package_form') if fm_package.is_valid(): package=fm_package.save() IpdReport.objects.create(patient=package.patient, package=package) fm_package=PackageForm(prefix='package_form') return render (request, 'account/package.html', {'form5':fm_package}) else: fm_package=PackageForm(prefix='package_form') return render (request, 'account/package.html', {'form5':fm_package}) The Template: <form action="" method="post" novalidate> {% csrf_token %} {{form5.non_field_errors}} {% for fm in form5 %} <div> {{fm.label_tag}} {{fm}} <span>{{fm.errors|striptags}}</span><br><br> </div> {% endfor %} <button type="submit" id="savebtn">Save</button> </form> Now, what I want is to insert an Anchor Tag next to all the foreign_key fields, in the template, to add a new object into the original table. For example, an Add Patient option next to the Patient's dropdown field, when clicked, a new, small window would show up with Patient form. The user enters the new patient's data, saves it and the same name shows up in the dropdown. But as I am using a For Loop in the template, how would I be able to access those foreign key fields … -
How do I use the key that is passing from page to page with django formset?
I have this key that I use to pass from page A to page B. How do I use this key with a formset to get the data according to the key. For model, its just the model.objects.get(variable = pk). But how about formsets? Tried the following but it doesnt work di_formset = modelformset_factory(DeviceInterface, fields=('moduletype', 'firstportid', 'lastportid'), can_delete=True) deviceInterface = di_formset.objects.get( I2DKEY=pk) -
django-cors-headers issue with Python 3.9 and Django 3.2.0
I have spent almost a day without any solution to this problem. I have applied all the solutions suggested by different folks on different forums. Recently we have upgraded the Python version of our project from 3.5 to 3.9. Upgraded Django version from 1.8 to 3.2.0. Post that this CORS issue is coming. It is working fine on my local MacBook. But when we deploy it on the Cent OS server, this issue starts appearing. in my settings.py I have added - MIDDLEWARE = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', # must be before CommonMiddleware 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'reversion.middleware.RevisionMiddleware', 'insights.middleware.RaiseErrorMiddleware', 'insights.middleware.IAMAuthenticationMiddleware', ) + getattr(settings_local, 'LOCAL_MIDDLEWARE', ()) ============== CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = [ "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ] CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "X-csrftoken", "X-Requested-With, Content-Type", "X-requested-with", "X-I-Token", "x-employer-key" ] Below is our server configuration. NAME="CentOS Linux" VERSION="7 (Core)" ID="centos" ID_LIKE="rhel fedora" VERSION_ID="7" PRETTY_NAME="CentOS Linux 7 (Core)" Can anyone please help. me with the solution. -
How to Optimize django application for images and static files
I'm building a website using Django(3) in which we have implemented blogs to post articles on the site. For each blog post, we have to add images one feature image and the other may need to be used within the post. You can find the site at: https://pythonist.org I can see in google console my website is too slow due to images and static css/js files. I'm compressing the image on uploading using the code below: from imagekit.models import ProcessedImageField class Course(models.Model): title = models.CharField(max_length=250, blank=False) slug = models.SlugField(blank=True, max_length=120) description = RichTextUploadingField(config_name='default') featured_image = ProcessedImageField(upload_to='course_images/', format='JPEG', options={'quality': 80}, blank=False) I'm using safe to load template variables and utilize cache, prefetch_selected, and other basic optimization tweaks. But are there other practical ways to load my images and static files faster? My site has been deployed on Heroku.