Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Build folder ./build does not exist
I was trying to deploy my django project using render and I am getting this error that build does not exists.. I have no idea how to fix this. Can anyone help? I tried to look for any solutions on the internet but could not find any...I don't know if I typed any code wrong or am I missing some commands. -
Manager isn't available auuth.User has been swapped
As a precursor to asking, I have already looked at a few similar questions and answers. I am trying to extend my user class to include other fields and then pass down these extra fields as payload on my access_token. I get this error message when I try to run makemigrations/migrate or run my code AttributeError: Manager isn't available; 'auth.User' has been swapped for 'accounts.CustomerUser' This is what I have in models.py from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import AbstractUser # #extending user model to include class CustomerUser(AbstractUser): city = models.CharField(max_length=50,blank=True) country = models.CharField(max_length=50, blank=True) bio = models.CharField(max_length=500, blank=True) serializers.py: from django.contrib.auth import get_user_model User = get_user_model() class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User #removed url from fields fields = ['username', 'email', 'password', 'first_name', 'last_name', 'city', 'country', 'bio'] extra_kwargs = { 'password': {'write_only': True}, } def create(self,validated_data): user = User.objects.create_user( username=validated_data['username'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], city=validated_data['city'], country=validated_data['country'], bio=validated_data['bio'], email=validated_data['email']) user.set_password(validated_data['password']) user.save() return user #customizing the payload we get from our access tokens class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) token['username'] = user.username token['first_name'] = user.first_name token['last_name'] = user.last_name token['country'] = user.country token['city'] = user.city token['bio'] = user.bio return token class UserSerializer(serializers.ModelSerializer): class Meta: model = User … -
Adding extended user class fields to payload data in access token
I extended my user class to include other fields (city, country, bio). I would like to pass these down along to customizing my JWT access_token to include these fields as a payload in addition to username. This is what I have in my models.py (extending my user class): from django.db import models from django.contrib.auth.models import User #extending user model to include class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=50,blank=True) country = models.CharField(max_length=50, blank=True) bio = models.CharField(max_length=500, blank=True) def __str__(self): return self.user.username serializers.py: #changed from serializers.HyperLinked to ModelSerializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = Profile #removed url from fields fields = ['username', 'email', 'password', 'first_name', 'last_name', 'city', 'country', 'bio'] extra_kwargs = { 'password': {'write_only': True}, } def create(self,validated_data): user = Profile.objects.create_user( username=validated_data['username'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], city=validated_data['city'], country=validated_data['country'], bio=validated_data['bio'], email=validated_data['email']) user.set_password(validated_data['password']) user.save() return user #customizing the payload we get from our access tokens class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) token['username'] = user.username token['first_name'] = user.first_name token['last_name'] = user.last_name token['country'] = user.profile.country token['city'] = user.profile.city token['bio'] = user.profile.bio return token and api.py #Register API class RegisterApi(generics.GenericAPIView): serializer_class = RegisterSerializer #remove this if it doesn't work authentication_classes = (TokenAuthentication,) permission_classes = (AllowAny,) def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) … -
How the through model object is created in django?
I want to overwrite a creation of M2M through model object. I thought that overwriting save method will be sufficient, but it appears that after saving admin form, the method is not called. I am having a hard time finding how this object is created. Here is the code snippet class ProductVariantToAttributeValue(models.Model): product_variant = models.ForeignKey(ProductVariant, on_delete=models.CASCADE) attribute_value = models.ForeignKey(AttributeValue, on_delete=models.CASCADE) attribute = models.ForeignKey( Attribute, on_delete=models.CASCADE, null=True, blank=True ) class Meta: db_table = "productvariants_to_attributevalues" unique_together = [("product_variant", "attribute")] verbose_name_plural = "Product Variants To Attribute Values" def save(self, **kwargs): self.attribute = self.attribute_value.attribute super().save(**kwargs) -
DRF Framework - allow User CRUD on another Users related field if they are in relationship through another model
I have a model Application that has fields applicant = ForeignKey('User'...) and coapplicant = ForeignKey('User'...). There is also a model Income that has field user = ForeignKey('User'.... I want to allow User A to create, edit, delete Income objects of User B if A and B are in a relationship through Application. That means: User A can CRUD Incomes of User B and vice-versa if there is such Application object where A is an applicant and B co-applicant or A is a co-applicant and B applicant. Do you know how to make that work? -
Django multiple image upload like ecommerce website
I want to let the user upload multiple images per model as Instagram or Amazon does. Till now I have title and featured_images fields in my model but the "multiple" attribute seems not to work. Thanks models.py class Project(models.Model): title = models.CharField(max_length=200) featured_images = models.ImageField(null=True, blank=True) forms.py class ProjectForm(ModelForm): class Meta: featured_images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) model = Project fields = ['title', 'featured_images'] views.py def createProject(request): form = ProjectForm() if request.method == 'POST': form = ProjectForm(request.POST, request.FILES.getlist('featured_images')) if form.is_valid(): project = form.save(commit=False) project.save() context = {'form':form} return render(request, 'projects/project_form.html', context) project_form.html <form class="form" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form__field"> <label for="formInput#text">{{field.label}}</label> {{field}} </div> {% endfor %} <input type="submit" name="" id=""> </form> -
How to fetch integer values from the Django objects?
I already created integerField for saving data in the model. But showing the bellow error. How can I convert a string list into an integer list? Django Model: class Frontend_Rating(models.Model): Rating = models.IntegerField( null=True) Views: #index def index(request): frontend_all_ratings = Frontend_Rating.objects.all() number_of_frontend_rating = frontend_all_ratings.count() frontend_rating_list = [] total_ratings = 0 for frontend_rating_item in frontend_all_ratings: frontend_rating = int(frontend_rating_item.Rating) frontend_rating_list.append(frontend_rating) total_ratings = total_ratings+frontend_rating_list[frontend_rating_item] context = { "number_of_frontend_rating":number_of_frontend_rating, "frontend_rating_list":frontend_rating_list, "total_ratings":total_ratings } return render(request,'0_index.html',context) Erorr: TypeError at / list indices must be integers or slices, not Frontend_Rating Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.3 Exception Type: TypeError Exception Value: list indices must be integers or slices, not Frontend_Rating Exception Location: D:\1_WebDevelopment\Business_Website\business_app\views.py, line 33, in index Python Executable: C:\Users\DCL\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.5 -
Catch errors in password validation in Django
i have a problem. I'm trying to catch errors from password validation in Django, but I don't know how to do it. Password validation is called in forms.py, and form.isValid() is called in views.py I'd like to know exactly what errors has been found in the password validation called in forms.py, so i can do use an if to launch a bootstrap warning chosen by me. Here is the code: forms.py class RegistrationForm(forms.Form): username = forms.CharField(label="Inserisci username", max_length=50) password = forms.CharField(label="Inserisci password", widget=forms.PasswordInput) repeatPassword = forms.CharField(label="Ripeti password", widget=forms.PasswordInput) def clean_username(self): username = self.cleaned_data['username'] if User.objects.filter(username=username).exists(): raise forms.ValidationError('Nome utente già in uso') return username def clean_password(self): username = self.cleaned_data['username'] password = self.cleaned_data['password'] validate_password(password, username) return password def clean_password2(self): password = self.cleaned_data['password'] repeatPassword = self.cleaned_data['repeatPassword'] if password != repeatPassword: raise forms.ValidationError('Le password devono corrispondere') return password views.py def registration(request): if request.method == "POST": registrationForm = RegistrationForm(request.POST) if registrationForm.is_valid(): # Creazione utente username = RegistrationForm.cleaned_data['username'] password = RegistrationForm.cleaned_data['password'] playerStatistics = Statistics(health=randint(90, 110), armor=0, strength=randint(5, 15), speed=randint(15, 25), dexterity=randint(15, 25)) equipmentStatistics = Statistics(health=0, armor=0, strength=0, speed=0, dexterity=0) playerStatistics.save() equipmentStatistics.save() equipment = Equipment(statistics=equipmentStatistics) equipment.save() inventory = Inventory() inventory.save() newPlayer = Player(username=username, password=password, statistics=playerStatistics, equipment=equipment, inventory=inventory) newPlayer.save() return render(request, "playerHome.html") else: return HttpResponse("Errore nell'inserimento dei dati") … -
How I get all products into subcategories when I filter through the parent category in django rest
When I filter by subcategories, only those products that are directly related to this category are displayed, and when I filter, the parent category returns an empty one, but in fact there is a subcategory on this parent category and there are products on this category. I wanted to make sure that all products related to the parent categories were returned. in views.py class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductsSerializer serializers = { 'create': ProductsSerializer, 'list': ProductDetailSerializer, 'retrieve': ProductDetailSerializer, 'default': ProductsSerializer, 'add_favorite': FavouriteSerializer } filter_backends = (filters.DjangoFilterBackend, OrderingFilter) filter_fields = { 'category__title': ["in",] } in models.py class Category(MPTTModel): """Categorizing posts""" title = models.CharField(max_length=128, verbose_name="Title", unique=True, default=None) description = models.TextField(verbose_name="Description", null=True, blank=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['title'] class Product(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey( Category, on_delete=models.PROTECT, related_name="products", verbose_name="Category of a product" ) in screen i have 2 category Parent and Child in screen when i filter by Child category in screen when i filter by Parent category and its response is empty how can I fix this and get all the products from the subcategories through the parent category filter -
Why is the Django template file not updating value from the context?
(I am a beginner in Django) I am following along a tutorial in Django where we can dynamically pass some variable to a template file from associated function in views.py When I am running the code for the first time, it works fine, but when I change the values within the context, the template does not update with the new values even when I refresh it Here is my views.py code - from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): # return HttpResponse('<h1>Hey, welcome</h1>') # we can dynamically send data to our index.html file as follows - context={ 'u_name': 'Ankit', 'u_age': 25, 'u_nationality': 'Indian', } return render(request,'index.html',context) Here is my template index.html - <h1> How are you doing today {{u_name}} <br>You are {{u_age}} years old<br>Your nationality is {{u_nationality}} </h1> settings.py has been correctly set as well - TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR,'templates'], Here is my output - does not take the values from the context Would be glad if someone could point out what error I am making. Thanks in advance -
How to retrieve data from html form and pass it into my database as an sql query in django
i am trying to make use of django to retrieve data from my sign up form and pass it into my database in pgadmin 4 as a query. I got error and doesnt know how to go about doing it. This is my code which i tried to use pymysql. Thanks in advance def booknow(request): c = pymysql.connect(host='localhost', user='postgres', password='pw', db='users') cur = c.cursor() if request.method == 'POST': display_name = request.POST.get['your-name'] email = request.POST.get['your-email'] age = request.POST.get['your-age'] phone_number = request.POST.get['phone-number'] gender = request.POST.get['your-gender'] vaccination_status = request.POST.get['your-vaccination'] password = request.POST.get['your-password'] insert_query = "INSERT INTO users (display_name, email, age, phone_number, gender, vaccination_status, password) VALUES ('%s','%s','%s','%s','%s','%s','%s');" % (display_name,email,age,phone_number,gender,vaccination_status,password) c = connection.cursor() c.execute(insert_query) return render(request, 'booknow.html') -
Reverse for 'temp1' with arguments '('',)' not found. 1 pattern(s) tried: ['userinput/(?P<id>[0-9]+)/\\Z']
I just want to retrieve data dynamically. urls.py I think there is something error in views.py or urls.py from django.urls import path from . import views urlpatterns = [ path("", views.home, name='home'), path("userinput/", views.template, name='template'), path("userinput/<int:id>/", views.temp1, name='temp1'), ] views.py from django.shortcuts import render, HttpResponseRedirect from home.models import UserDetail # Create your views here. def template(request): if request.method == 'POST': nm = request.POST['name'] eml = request.POST['email'] adrs = request.POST['address'] data = UserDetail(name=nm, email=eml, address=adrs) data.save() return render(request, 'template.html') def temp1(request, id): userdetail = UserDetail.objects.get(pk=id) return render(request, 'temp1.html', {'userdetail':userdetail}) template.html I think my error is related to views.py or in template.html file {% load static %} {% block css_files %} <link rel="stylesheet" href="{% static '' %}"> {% endblock %} {% block content %} <form id="resume-form" action="" method="POST"> {% csrf_token %} <h1>Enter your details</h1> <div class="generate"> <div class="per"> <h2>Personal details</h2> <div class="a"> <label for="namefields">Your Name</label><br> <input type="text" class="" id="namefields" placeholder="Enter here" name="name"> </div> <div class="a"> <label for="emailfield">Your Email</label><br> <input type="email" class="" id="emailfield" placeholder="Enter here" name="email"> </div> <div class="a"> <label for="addressfield">Your Address</label><br> <textarea id="addressfield" placeholder="Enter here" rows="3" cols="" name="address"></textarea> </div> <div class="generatebtn"> <a href="{% url 'temp1' userdetail.id %}"><button type="Submit">Submit</button></a> </div> </form> {% endblock %} can anyone say why it shows "NoReverseMatch at /userinput/" … -
Does select_for_update() work if AUTOCOMMIT is set to False in Django Rest-Framework
I am writing a celery task which would get invoked if a row is being inserted into a table. This task is being executed in a transaction and the task also locks the certain rows of several tables. Now lets assume this task is being executed when AUTOCOMMIT & ATOMIC_REQUESTS is enabled. This is how it looks like - @app.task @transaction.atomic def celery_task(a, b): result = Orders.objects.filter(filed = "Value") # here the result might have 10 of records but I just need few of them based on a very # specific business logic. # so I pick those which are required and should be locked. rows_to_lock = [result[0], result[1]] # has only ids of the rows in this list # Now to put on the records which are in - rows_to_lock result = Orders.objects.select_for_update().filter(id__in=rows_to_lock) ... ... Now when this celery task is being invoked twice with two different arguments and at the same time and if the resultant rows of orders are exactly same then I have noticed that the locks to update the records aren't working. Does the decorator @transaction.atomic works with the current database configurations that I have? Will I be able to solve the issue if I … -
Django - How to go back to previous url
I have multiple todo lists on different pages in an app written in python. I dont want to use delete and update functions over and over again. I want to use one for all pages. In update and delete functions, I can redirect to a certain page after code execution. But its not dynamic. How can I make it dynamic? def updateTodo(request, pk): task = Todo.objects.get(id=pk) form = FormTodo(instance=task) if request.method == 'POST': form = FormTodo(request.POST, instance=task) if form.is_valid(): form.save() return redirect('/page_path') context = {'form':form} return render(request, 'update_task.html', context) What should I write instead of page_path so that it redirects to the page it comes from? I thought going back to the latest page would be an option but guess what? I couldnt do it either. Also, would going back create an error or something? since I'm updating an entry. Any suggestions ? (I saw some options with selenium but it seems to work for chrome or selected browsers only. I'd like to avoid using selenium if there is another way) -
Prevent overwriting existing objects when applying fixture
I have a model representing my application's settings. The settings I define in a fixture. Now, everytime I redeploy the app I also apply the fixture with ./manage.py loaddata settings. The problem I noticed now is that everytime I do this already changed settings get reset as well, it's appearantly deleting the dataset and creating it new. Is there a way to avoid this? settings.yaml: ## Einstellungen - model: preferences.settings pk: agent_name fields: name: Agenten-Name description: Name, welcher dem Kunden im Chat angezeigt wird default: Agent public: true type: text category: 2 - model: preferences.settings pk: greeting fields: name: Begrüßungstext description: Begrüßungstext der dem Kunden angezeigt wird wenn ein Agent Online ist default: Hallo, wie können wir Ihnen helfen? public: true type: textarea category: 2 -
covert txt file into json python django
i have this file of weather data i'm trying to send it through API: view.py: @api_view(['get']) def weatherDataList(request,region,parameter): try: url = 'https://www.metoffice.gov.uk/pub/data/weather/uk/climate/datasets/'+parameter+'/date/'+region+'.txt' print(url,"this is url") r=requests.get(url) data = r.text new_data = data[274:] a=json.loads(new_data) return Response({"message":"Data List","status":True,"data":a},status=status.HTTP_200_OK) except Exception as e: print(e) return Response({"message":str(e),"status":False,"data":{}},status=status.HTTP_400_BAD_REQUEST) i'm not able to format and output the data. what should be the better way to achieve this. output the whole data as json. -
Django putting logic in view vs serializer vs model best approach
What is the best approach about putting logic and what is best in my current scenario where I have a view which uses a query + subquery to fetch and return data. @action(detail=False, methods=["get"], url_name="inventory") def inventory( self, request: Request, *args: None, **kwargs: None ) -> Response: required = ( ProductionJob.objects.filter(item=OuterRef("pk")) .order_by() .filter(status="Pending") .annotate( amount_sum=Sum( "required_item", output_field=FloatField() ) ) .values("amount_sum") ) data = ( Item.objects.select_related("supplier") .prefetch_related("item_jobs") .annotate( item_required=Coalesce( Subquery(required), 0, output_field=FloatField(), ) ) .values( "id", "article_id", "composition", "width_meter", required_for_jobs=Sum("item_required"), supplier_name=F("supplier__name"), ) ) return Response(data=data, status=HTTP_200_OK) The question is what is the best place to keep this code. It can be put on a model's QuerySet or if it should be moved to serializer then how? Thank you. -
Filtering duplicate model elements in django templates
It was necessary to weed out duplicate model elements on django. Removing identical elements is not suitable for me, but only filtering is suitable. My model includes albums and photos that are in those albums. If I send objects.all() to my template in views.py and try to display only my albums without repetition, then the album name is displayed in the template as many times as there are images in it. Is it possible to somehow check for a non-repeating output of my albums. PS: I am using sql database so objects.all().distinct('albom') doesn't seem to work for me... My views.py (I want to filter the proverka function): from django.shortcuts import render, redirect from .models import Image, Albom def proverka(request): if not request.user.is_authenticated(): return redirect("/accounts/login/") else: albom = Image.objects.all() return render(request, 'Фото/Альбом.html', {'albom': albom}) def gallery_view(request, pk): if not request.user.is_authenticated(): return redirect("/accounts/login/") else: albom = Albom.objects.get(id=pk) return render(request, 'Фото/Фото.html', {'albom': albom}) My urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.proverka, name="albomm"), url(r'^Альбом/(?P<pk>\d+)', views.gallery_view, name="foto"), ] My models.py: from django.db import models class Albom(models.Model): name = models.CharField(max_length=120) def __str__(self): return self.name def upload_gallery_image(instance, filename): return f"images/{instance.albom.name}/gallery/{filename}" class Image(models.Model): image = models.ImageField(upload_to=upload_gallery_image) albom = models.ForeignKey(Albom, on_delete=models.CASCADE, related_name="images") … -
How to override .py files in third party INSTALLED_APPS, django
I'm using https://github.com/jazzband/django-two-factor-auth I want to edit the file core.py in folder https://github.com/jazzband/django-two-factor-auth/tree/master/two_factor/views Where can I put core.py in my project to override and edit it? For example I edited the templates by placing them in: /home/johndoe/projects/example_project/example_project/templates/two_factor/core/setup.html How can I do the same for core.py? My project structure is: ├── example_project └──example_project └──users └──views.py └──models.py └──apps.py └──... └──blog └──views.py └──models.py └──apps.py └──... └──settings.py └──urls.py └──wsgi.py └──manage.py └──static └──templates └──users └──blog └──two-factor └──core └──setup.html I want to edit it to check if the user's email is verified before they enable 2FA. -
i need to send in response array of chats in my my chat view from chat model
Following are my models: class MediaUploads(models.Model): file = models.FileField(upload_to='embla/uploads/') caption = models.CharField(max_length=256, null=True, blank=True) owner = models.ForeignKey(User, related_name='embla_uploads', on_delete=models.CASCADE, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) class Profile(models.Model): ...other unlreated keys, photo = models.ForeignKey(MediaUploads,on_delete=models.DO_NOTHING,related_name='profile_photos', null=True, blank=True) name = models.CharField(max_length=256) ...other unrelated keys, class Message(models.Model): sender = models.ForeignKey( to=Profile, on_delete=models.CASCADE, related_name="sender") receiver = models.ForeignKey( to=Profile, on_delete=models.CASCADE, related_name="receiver") message = models.CharField(max_length=999) timestamp = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) def __str__(self): return self.message class Meta: ordering = ('timestamp',) Following is my view: class ChatView(APIView): searilzer_class = MessageSearlizer def get(self, request, *args, **kwargs): user_id = self.request.user.profile.pk # i need this chats here # On client side i need to show the list of chats along with the names and pictures # of the people the user is engaged in chat. i have attached the picture of the #[[client side view of chat][1]][1] client side view chats = return Response({"chats": chats}) I am Nodejs developer and due to insistence of client, doing my first project on django. chat would be array of objects. This array will have 3 keys. receiver name, receiver photo and receiver last message. I apologise in advance for my noobness in python. please dont downvote this. -
How to store nav menu urls in database?
I'm working on my first django app, and i have side nav menu like in twitter. To prevent the dozens of lines in my template like this <ul class="nav d-flex flex-column"> <li class="nav-item align-self-start rounded-pill mb-3"><li> <li class="nav-item align-self-start rounded-pill mb-3"><li> ... <li class="nav-item align-self-start rounded-pill mb-3"><li> </ul> and for app extensibility i want to store nav menu in database to be able to loop over the menu items <ul class="nav d-flex flex-column"> {% for item in menu %} <li class="nav-item align-self-start rounded-pill mb-3"><li> {% endfor %} </ul> But the problem is that i can't store direct urls for menu items in database, because several of them have dynamic urls e.g. profile page, which has 'slug:username/' pattern. I've tried to store template tags in database like {% url 'app_name:view_name' %} but of course it doesn't work. My current idea is to store in database namespaced url e.g. 'app_name:view_name' for static urls and 'request.user.get_absolute_url()' for pages which have username in urls. The next step is to get QuerySet with menu items from database, loop over them and transform namespaces url with reverse (it works), but 'request.user.get_absolute_url()' is just a string and it doesn't work. Then make list of ditcs and pass … -
http API requests are executed for more than 20 seconds
I have an application on django that can search for YouTube videos via the YouTube Data API v3 and translate their description using the Yandex Translate API. Often everything works fine, both services respond normally. But about once every 10 calls, the request stretches for about 20 seconds. This happens with both translation and YouTube. I look in the developer console, in the column "Waiting (Time to receive the first byte)" just these 20 seconds. I do not understand why this is so, it is unlikely that the problem is on the side of the services, because it is observed on both. But I can't figure out what my problem is then... I tried to set DEBUG to False, it was advised somewhere. But the problem has not gone away. Code of functions for receiving data from YouTube: from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import os import pickle SCOPES = ["https://www.googleapis.com/auth/youtube.force-ssl"] def auth(): os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1" api_service_name = "youtube" api_version = "v3" credentials_filename = "credentials.json" credentials = None if os.path.exists("token.pickle"): with open("token.pickle", "rb") as token: credentials = pickle.load(token) if not credentials or not credentials.valid: if credentials and credentials.expired and credentials.refresh_token: credentials.refresh(Request()) else: flow = … -
How to upload random pictures from a folder to database
i want to upload random pictures from a static named folder to my database. These are my files. Please suggest a way. I am stuck here forever. views.py class VerifyOTPView(APIView): permission_classes = (AllowAny,) serializer_class = VerifyOTPSerializer def post(self, request): serializer = VerifyOTPSerializer(data=request.data) mobile = request.data['mobile'] otp_sent = request.data['otp'] #print('one_time_password', one_time) if mobile and otp_sent: old = Profile.objects.filter(mobile = mobile) if old is not None: old = old.first() otp = old.otp if str(otp) == str(otp_sent): serializer = self.serializer_class(data=request.data) mobile = request.data['mobile'] if serializer.is_valid(raise_exception=True): instance = serializer.save() content = {'mobile': instance.mobile, 'otp': instance.otp, 'name':instance.name, 'username':instance.username, 'logo':instance.logo, 'profile_id': instance.profile_id } return Response(content, status=status.HTTP_201_CREATED) else: return Response({ 'status' : False, 'detail' : 'OTP incorrect, please try again' }) serializers.py class VerifyOTPSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['mobile','otp'] def create(self,validated_data): instance = self.Meta.model(**validated_data) mywords = "123456789" res = "expert@" + str(''.join(random.choices(mywords,k = 6))) path = os.path.join(BASE_DIR, 'static') random_logo = random.choice([ x for x in os.listdir(path) if os.path.isfile(os.path.join(path, x))]) instance = self.Meta.model.objects.update_or_create(**validated_data, defaults = dict( username = res, name = instance.mobile, logo = random_logo, profile_id = res))[0] instance.save() return instance models.py class Profile(models.Model): mobile = models.CharField(max_length=20) otp = models.CharField(max_length=6) name = models.CharField(max_length=200) username = models.CharField(max_length=200) logo = models.ImageField(upload_to ='profile/', blank=True,null = True) profile_id = … -
Django Rest Framework Simple JWT getting anonymous user
I want to use Rest Framework simpleJWT as authentication earlier I was using Django default authentication. Here are views currently I am getting AnonymousUser error, what changes do I need to get a user request from JWT Authenticated user. I want to get a request.user from a jWT Authenticated user. Please help me out. class MessagesModelList(ListView): http_method_names = ['get', ] paginate_by = getattr(settings, 'MESSAGES_PAGINATION', 500) def get_queryset(self): if self.kwargs.get('dialog_with'): qs = MessageModel.objects \ .filter(Q(recipient=self.request.user, sender=self.kwargs['dialog_with']) | Q(sender=self.request.user, recipient=self.kwargs['dialog_with'])) \ .select_related('sender', 'recipient') else: qs = MessageModel.objects.filter(Q(recipient=self.request.user) | Q(sender=self.request.user)).prefetch_related('sender', 'recipient', 'file') return qs.order_by('-created') def render_to_response(self, context, **response_kwargs): user_pk = self.request.user.pk data = [serialize_message_model(i, user_pk) for i in context['object_list']] page: Page = context.pop('page_obj') paginator: Paginator = context.pop('paginator') return_data = { 'page': page.number, 'pages': paginator.num_pages, 'data': data } return JsonResponse(return_data, **response_kwargs) class DialogsModelList(ListView): http_method_names = ['get', ] paginate_by = getattr(settings, 'DIALOGS_PAGINATION', 20) def get_queryset(self): qs = DialogsModel.objects.filter(Q(user1_id=self.request.user.pk) | Q(user2_id=self.request.user.pk)) \ .select_related('user1', 'user2') return qs.order_by('-created') def render_to_response(self, context, **response_kwargs): # TODO: add online status user_pk = self.request.user.pk data = [serialize_dialog_model(i, user_pk) for i in context['object_list']] page: Page = context.pop('page_obj') paginator: Paginator = context.pop('paginator') return_data = { 'page': page.number, 'pages': paginator.num_pages, 'data': data } return JsonResponse(return_data, **response_kwargs) class SelfInfoView(DetailView): def get_object(self, queryset=None): return self.request.user def render_to_response(self, … -
The view Project.views.index didn't return an HttpResponse object. It returned None instead
So I have encountered this problem while this is my views.py code Create your views here. # Create your views here. def index(request): if request.method == 'POST': feature1 = Feature.objects.all() Appnt = Appointment.objects.all() Appnt.name = request.POST['name'] Appnt.email = request.POST['email'] Appnt.phone = request.POST['phone'] Appnt.Adate = request.POST['date'] Appnt.Dept = request.POST['department'] Appnt.Doc = request.POST['doctor'] Appnt.message = request.POST['message'] return render(request, 'index.html', {'feature1' : feature1}, {'Appointment' : Appnt} ) I have tried many ways but still it keep saying that error