Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i make a main URL with sub URL for different Django app
i want to make main Url and that URl will be main route for all django app. Suppose i have 3 apps blog, linux, business. i want to make url like this: 127.0.0.1:8000/blog/ (when i will click blog menu) 127.0.0.1:8000/blog/linux ( when i will click linux menu) 127.0.0.1:8000/blog/business (when i will click business menu) the blog app will be my index home page and all app link will be like this. I don't want to import all views and models in blog app. the project structure will be same and i don't want to change it. All i want to make blog common for all the app link. If i click a post on linux page the url will be like this:- 127.0.0.1:8000/blog/linux/post name How can i do this.? this is my project structure.. project structure image -
Django ImageField.url returning URL with expiration querystring instead of plain url
I have a simple Model for storing a Client's Logo in my system. I am running into an issue where the returned file.url value is also providing expiration querystring parameters and occasionally it expires before the client logs out of the system so they get a 404 error. With that, I cannot figure out how to disable the querystring from being added other than by either building the URL manually (which probably isn't the best option as Django provides the URL), or by doing (what I have done) and parsed the querystring off from the URL before storing it. Can someone explain what is going on here? - I use Digital Ocean Spaces if that matters but it shouldn't as my static files are stored there as well and there is no expiration set on those files once they are loaded. Here is the model with the upload path: # for client logo uploads def logo_upload_path(instance, filename): # client_name/ClientLogo/logo.[png, jpg, ...] return f'{instance.client_url}/ClientLogo/logo.{filename.split(".")[-1]}' class ClientLogo(models.Model): """ Basically a singleton class, I only want 1 logo per client """ file = models.ImageField(upload_to=logo_upload_path,) client_url = models.CharField(max_length=100) changed = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): # already saved if self.pk is not None: super().save(*args, … -
Django PostgreSQL Connection refused
I am running two applications that use Django 3.07, psycopg2==2.8.5. Both of them live on an Ubuntu 20.04 server with PostgreSQL 10. The first app has no problem connecting to the db When I run the second app it returns this error: RuntimeWarning Traceback (most recent call last): File "/home/noodles/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/home/noodles/venv/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/noodles/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/home/noodles/venv/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/noodles/venv/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 185, in get_new_connection connection = Database.connect(**conn_params) File "/home/noodles/venv/lib/python3.6/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5342? The db settings are using the same structure and the only difference is in the dbuser, pass and dbname: postgres://dbuser:pass@localhost:5432/dbname The user and the database for the second app are created and can connect to the db using psql -h localhost -U {user} I'm baffled by this. Any ideas? -
How do I upload a file in a FileField using django rest framework
I'm trying to make an API endpoint to upload a file on the server under a unique name and have a FileField relate to it. My models.py: def user_directory_path(instance, filename): ext = filename.split('.')[-1] return f'construct/user_{instance.user.id}/{uuid.uuid4()}.{ext}' class File(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) scenariofile = models.ForeignKey(ScenarioFile, on_delete=models.CASCADE, null=True, blank=True) file = models.FileField(upload_to=user_directory_path, blank=True, null=True) My views.py class FileUploadView(APIView): parser_class = [FileUploadParser,] def put(self, request): if not request.user.is_authenticated: raise ParseError('User is not Authenticated') if 'file' not in request.data: raise ParseError('No file') f = models.File(user=request.user, file=request.data['file']) f.save() return Response(status=status.HTTP_201_CREATED, data={'id': f.id}) I would like to be able to upload a file using a single API endpoint (e.g /upload/file), I do not need to save the filename. My code seems to save the model instance saved in the database, but when I try to the file it seems to be corrupt and opening the file as plain text shows that the first two lines are HTTP headers that were passed in the file upload request. My request: curl --location --request PUT 'https://example.com/upload' \ --header 'Authorization: Token <TOKEN>' \ --header 'Content-Disposition: attachment; filename=img.jpg' \ --form 'file=@/home/myself/img.jpg' -
can i render the template with rest framework django?
how can i render the template with rest framework because when i try to run this code i am getting error 405 Method Not Allowed and in terminal "GET /report/create/ HTTP/1.1" 405 22. how can i solve this error! i want to make a post request with json form. views.py from rest_framework.renderers import TemplateHTMLRenderer, JSONRenderer from rest_framework.generics import (CreateAPIView) from .serializer import ArticleSerializer from .models import Article class ArticleCreateView(CreateAPIView): renderer_classes = [JSONRenderer, TemplateHTMLRenderer] template_name = 'create.html' queryset = Article.objects.all() serializer_class = ArticleSerializer -
For loop inside of Javascript dynamic Html content in Django
I will have a strange question. Version: Django version 3.0.8 This is my Javascript code: fetch(`/loadbox/${message.id}`) .then(response => response.json()) .then(dialog => { let detailcontent= `<div class="hepsi"> <div class="sender"> <h3>${dialog.sendername}</h3><br> @${dialog.sender}</div> <p class="posting msj"> ${dialog.content}</p> <p class="posting rep"> ${dialog.reply}</p> // Here I have a list named replies and I want to loop through all elements and display every reply for that particular message. <br> <div class="m-form"> <form class="form-control"> <input class="msj-i" type="text" placeholder="Start a new message"></input> <input type="submit" value="Send" class="msj-s"></input> </form> </div></div>` ; document.querySelector('#message-view').innerHTML=detailcontent; document.querySelector('.msj-s').onclick = function() { sender=`${dialog.sender}` reply_message(sender); } }) } so where I fetch the data /loadbox/message.id, I have this data for example: {"replies": ["hi there", "haha", "last"],"sendername": "Bilge", "sender": "bilge", "content": "hi"} As you see replies is a list and I want it to loop through in the HTML template. However, I use dynamic content in my javascript code. Normally in Django template, I would easily do {% for reply in replies %} {{reply }} { % endfor %} However, I am writing a dynamic html with this method: content = `"some content"` document.querySelector(".message-view").innerHtml = content So I need to loop this through inside of the content I think. I tried: {for (${reply} of ${replies})} <p class="posting rep"> … -
django form redirect to new url
I have a django form with a DateField and then I use it to construct a local url, the idea is to redirect the user to that url but all i get is a new tab with the current page. I use here a public url since the one I'm using is local. in my form.py I have this: class DateInput(forms.DateInput): input_type = 'date' class DateForm(forms.Form): date = forms.DateField(label='',widget=DateInput) def clean_date(self,*args,**kwargs): date = self.cleaned_data.get('date') if date < datetime.date.today(): raise forms.ValidationError("No past data available ") if date > datetime.datetime.now().date() + datetime.timedelta(days=2): raise forms.ValidationError("You cannot consult beyond three days") year_i=date.strftime("%Y") month_i=date.strftime("%m") day_i =date.strftime("%d") url=f'http://weather.uwyo.edu/cgi-bin/sounding?region=samer&TYPE=TEXT%3ALIST&YEAR={year_i}&MONTH={month_i}&FROM={day_i}12&TO=0212&STNM=72672' return redirect(url) in my views.py I have this: from .form import DateForm def met(request): form = DateForm() if request.method =='POST': form = DateForm(request.POST) context = { 'form':form } return render(request,'apps/met.html',context) and in my html file I have this: <form class="form-group pt-2 " method="post" target="_blank"> {% csrf_token %} <div class="pt-3"> {{ form.as_p }} <button class="btn btn-primary "type="submit" name="button">Seach</button> </div> </form> -
Django media url mismatch with digitalocean spaces
I have a droplet running a django app on digital ocean using digital ocean spaces.I have managed to set up the spaces wich runs well with static files using a cdn.However, my problem lies with the uploaded media files.I am facing an issue of mismatch in the urls of the uploaded file served by django and what the actual path of the uploaded files in the spaces. For example if i upload a file using models: attachment = models.FileField(upload_to='Mailserver/',blank=True,null=True) and the path of the file returned when i click on it, returns an error with the path as 'https://freelance.ams3.cdn.digitaloceanspaces.com/media/Mailserver/download.png' which is wrong because the correct path of the file uploaded to spaces is: 'https://freelance.ams3.cdn.digitaloceanspaces.com/freelance/media/Mailserver/download.png' This is my settings config: AWS_ACCESS_KEY_ID = '****************************' AWS_SECRET_ACCESS_KEY = '*****************************' AWS_STORAGE_BUCKET_NAME = 'freelance' AWS_S3_ENDPOINT_URL = 'https://freelance.ams3.digitaloceanspaces.com/' AWS_S3_CUSTOM_DOMAIN = 'freelance.ams3.cdn.digitaloceanspaces.com' AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_DEFAULT_ACL = 'public-read' STATIC_URL = '{}/{}/'.format(AWS_S3_CUSTOM_DOMAIN, 'static') STATIC_ROOT = 'static/' STATICFILES_STORAGE = 'custom_storages.StaticStorage' MEDIA_ROOT = 'media/' MEDIA_URL = '{}/{}/'.format(AWS_S3_CUSTOM_DOMAIN, MEDIA_ROOT) DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' And custom_storages looks like: from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings class StaticStorage(S3Boto3Storage): bucket_name = settings.AWS_STORAGE_BUCKET_NAME location = settings.STATIC_ROOT class MediaStorage(S3Boto3Storage): bucket_name = settings.AWS_STORAGE_BUCKET_NAME location = settings.MEDIA_ROOT I have tried creating folders and … -
Cannot filter data inside Django template html
I want to filter data using return redirect if the value is equals to somevalue then it will trigger the toast template but currently it doesn't work. Below is my current code. can you help me with this problem?, thanks in advance. views.py def register(request): somevalue='Successfully created' return render(request, 'register.html',{"somevalue":somevalue}) register.html -script {% if somevalue =="Successfully created" %} <script> $(document).ready(function() { setTimeout(function() { toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.success('Success', 'Successfully created'); }, 1300); }); </script> {% endif %} -
How to display the date of my selected item.? - Django
Right now the problem I want to show the date of the item1 I have selected, what days this item1 is available for sale. For example, item1 is available for sale on Monday, Tuesday. If I choose to buy this item1, In the Checkout page Must show the date All of this item1 In order that people can order and configure another date that they want to be delivered on. I don't know what to do. I'm not sure how to create a function in the Orderform class in form.py to display the date. Code snippets on this question 1. Models.py class Meal(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) name = models.CharField(max_length=255) slug = models.SlugField() def dates_available(self, mindate=None, maxdate=None): mindate = mindate or now().date() maxdate = maxdate or mindate + datetime.timedelta(days=365) ret = [] for availability in self.availability.all(): ret.extend( [available.available_on for available in availability.dates.all()] ) return list(filter(lambda a: mindate <= a <= maxdate, ret)) class MealAvailabilityManager(models.Manager): def available_meals(self, date=None): return self.get_queryset().filter(dates__available_on=date or now().date()) class MealAvailability(models.Model): meal = models.ForeignKey( Meal, on_delete=models.CASCADE, related_name="availability" ) supplier_price = models.DecimalField(max_digits=14, decimal_places=2) sell_price = models.DecimalField(max_digits=14, decimal_places=2) objects = MealAvailabilityManager() def __str__(self): return f"{self.meal}: {self.dates.first()} - {self.dates.last()}" class Order(models.Model): created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(get_user_model(), on_delete=models.SET_NULL, null=True) phone = … -
How to change my models.TextField to models.JSONField?
I'm using django as my backend and it was working very fine, but after I tried to replaced text = models.TextField(blank=True, null=True) text = models.JSONField(blank=True, null=True) but I got the text field is shown as string with slashes \ "text": "{\"name\": [\"test\", \"test2\"]}", while styles field look as json "style": { "borderRadius": "5px", "backgroundColor": "orange" }, despite they both are jsonfield. models.py class elements(models.Model): tag = models.CharField(blank=True, null=True, max_length=20) # it was # text = models.TextField(blank=True, null=True) # now it is text = models.JSONField(blank=True, null=True) src = models.TextField(blank=True, null=True) style = models.JSONField(blank=True, null=True) main = models.ForeignKey( 'self', null=True, blank=True, related_name="sub", on_delete=models.PROTECT) def __str__(self): return "<elements: {} {}>".format(self.tag, self.text, self.src, self.style) def __repr__(self): return self.__str__() Note: I tried to delete my data don't remigrate as well but did't work -
How can I launch my Django application internally for my company?
I am in the process of building a fairly large data analytics web app using Django - however I am more of a data scientist than a software developer so I am unsure of a few things here. The key issue I have is that the data this application contains is highly sensitive and there is a company-wide ban on microsites on their servers. As a result I cannot simply host this application on any old server or Heroku etc., and I'm not sure even a secure user authentication would suffice in this case without my company's own security layers included - something i'd be unlikely to get sorted in time for the project deadline. Is there an easy way I can package the app into a desktop application that only members of my organisation can install? If so how I do go about this and how can I enable specific colleagues to install it? Or am I missing a much more obvious method? Thanks -
SQL vs django: reproduce the __ from a filter
I have following django filter: replacement_device = DeviceReplacement.objects.filter( new_device__mac_address=mac_address ).all() I want to reproduce this in SQL but don't know how to do the __ in sql. more information: devicereplacement has 3 attributes: id, new_device_id, old_device_id device has many attributes including id and mac_address -
How to execute solr "rebuild_indexes" from deployment .yaml in k8s?
I have my app and database pods running and my database is initialized by loading some predefined data. Then I start my solr pod but i can only search newly created data from my app and not the predefined data which is loaded into my database. I assume a rebuild_indexes command needs to be issued from the deployment.yaml file of solr so that the predefined data is also indexed and can be searched? -
How to access Local file in Python from Website
I was able to access local file in local host by using the code 'src = path.realpath("C:\Users\HP\AppData\Local\imp.txt") but as I hosted it on heroku it shows error of file not found '/app/C:\Users\HP\AppData\Local\imp.txt' -
Django : 'bool' object is not callable - fields.py in clean, line 45 [closed]
I'm using django-messages app. Everything works well (reply, message, ... except compose). I can easily reply to a message. Assume I've created a message from my admin pannel. But If want to send a new message to someone and create new conversation, that does not work. I'm facing an issue when I try send a new message to someone. 'bool' object is not callable message/fields.py in clean, line 45 messages/fields.py from django import forms from django.forms import widgets from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from .utils import * User = get_user_model() class CommaSeparatedUserInput(widgets.Input): input_type = 'text' def render(self, name, value, **kwargs): if value is None: value = '' elif isinstance(value, (list, tuple)): value = (', '.join([getattr(user, get_username_field()) for user in value])) return super(CommaSeparatedUserInput, self).render(name, value, **kwargs) class CommaSeparatedUserField(forms.Field): widget = CommaSeparatedUserInput def __init__(self, *args, **kwargs): receiver_filter = kwargs.pop('receiver_filter', None) self._receiver_filter = receiver_filter super(CommaSeparatedUserField, self).__init__(*args, **kwargs) def clean(self, value): super(CommaSeparatedUserField, self).clean(value) if not value: return '' if isinstance(value, (list, tuple)): return value names = set(value.split(',')) names_set = set([name.strip() for name in names if name.strip()]) users = list(User.objects.filter(**{'%s__in' % get_username_field(): names_set})) unknown_names = names_set ^ set([getattr(user, get_username_field()) for user in users]) receiver_filter = self._receiver_filter invalid_users = [] if … -
Django Rest Framework(DRF): HyperlinkedModelSerializer Could not resolve URL for hyperlinked relationship
I have this issue: Could not resolve URL for hyperlinked relationship using view name "test-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. This error occurs from the below code: File: models.py class Test(models.Model): first_name = models.CharField(max_length=30, blank=False, null=False) last_name = models.CharField(max_length=30, blank=False, null=False) File: serializers.py class TestSeriliazer(serializers.HyperlinkedModelSerializer): class Meta: model = Test fields = ('first_name', 'last_name', 'url') File: apiviews.py class TestsList(generics.ListCreateAPIView): queryset = Test.objects.all() serializer_class = TestSeriliazer File: urls.py urlpatterns = [ .... path('tests/', TestsList.as_view(), name='tests-list') ] If i change the url name to 'test-detail' also does not work! How do i solve this issue? If it possible without Routes. -
Pytest Image Upload
I'm testing an API call that uploads an image to the user profile. The test case below returns status code 400. If I remove image_filename key from data, the test case succeeds. How can I test an image upload in pytest? def test_edit_user_profile(db, client): # stream the image into binary with open('C:/...../test.png', 'rb') as consultant_image: image_binary = BytesIO(consultant_image.read()) userdetail_response = client.patch(path=reverse('user-detail', args="1"), data={"full_name": "James edited", "image_filename": (image_binary, 'test2.png')}, content_type='multipart/form-data', HTTP_AUTHORIZATION='Token ' + data.json()['token_key']) assert userdetail_response.status_code == status.HTTP_200_OK -
Django - User created but Profile is missing
When I register a new user, I can see from the Admin page that the user was created. But whenever I go on my profile page in my nav var I get the following Error. It was actually working before I added a function on my Profile page (a button that deletes a user&profile) but I don't see what I need to page to fix this error. profile.html {% extends "digitalFarm/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="boder-bottom mb-4">Profile info</legend> {{ u_form|crispy }} {{ p_form|crispy }} {{ d_form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Update Profile</button> </div> </form> <form> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Delete User Account</legend> </fieldset> <div class="form-group"> <button class="btn btn-danger"> <a style="color: white" href="{% url 'profile_confirm_delete' %}">Delete Account</a></button> </div> </form> </div> {% endblock content %} views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to login') return redirect('login') else: form = UserRegisterForm() return … -
Django: @login_required decorator does not redirect to "next"
I am building a dictionary app using Django where users are able to define words. However, I want users to be logged in before being able to do that. I am trying to implement this constraint using the build-in @login_required decorator on my define view (the view that lets users define words). Using @login_required, when I am not logged in and try to define a word (using a definition form) I correctly get redirected to the login page. Here is my login_view view in views.py: def login_view(request): form = LoginForm(data=request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect(reverse(settings.LOGIN_REDIRECT_URL)) return render(request, "users/login.html", {"form": form}) At this time my URL looks something like: http://127.0.0.1:8000/login?next=/define So far so good. As soon as I log in, however, Django does not redirect me back to the definition form I was trying to access in the first place (located at /define). How can I tell Django to redirect me to the definition form in this situation? Also, in my settings.py I have redefined the LOGIN_URL, LOGIN_REDIRECT_URL, and LOGOUT_REDIRECT_URL variables as follows: LOGIN_URL = "users:login" LOGIN_REDIRECT_URL = "dictionary:index" LOGOUT_REDIRECT_URL = "dictionary:index" Might the … -
Django: how to create private groups and join them using password?
EXAMPLE to elaborate my problem -> I am the user of the website and i want to create a group. While creating group the website asked me the group_name,group_description ,group_password (as i don't want the group to be public and a person if want to join the group should know the password). now i have given the name and the password to my friends and they can join the group by authenticating with the password of group to successfully join. ISSUE i am facing -> i have created the password field in models.py. But the password is saved in the database as plane text but not something liked hashed django passwords. secondly, i want in the joining user to authenticate with the password in order to join the group. models.py class Group(models.Model): admin = models.ForeignKey(to=Profile, related_name="admin", on_delete=models.CASCADE) name = models.CharField(max_length=200, unique=True) password = models.CharField(max_length=200, default='thinkgroupy') slug = models.SlugField(allow_unicode=True, unique=True) group_pic = models.ImageField(upload_to="users/group_images/%y/%m/%d",null=True) about = models.CharField(max_length=255, null=True, blank=True) about_html = models.TextField(editable=False, default='', blank=True) created_at = models.DateTimeField(auto_now=True) members = models.ManyToManyField(User, through="GroupMember") def __str__(self): return "%s" % self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) self.about_html = misaka.html(self.about) super().save(*args, **kwargs) def get_absolute_url(self): return reverse("groups:single", kwargs={"slug": self.slug}) class Meta: ordering = ["name"] class GroupMember(models.Model): … -
Linking table in django
I have the tables below and I'm trying to link them such that I can query and perform calculation from fields of these tables.Example quantity - quantity_issued. Any help help would be highly appreciated. class Stock(models.Model): item_date = models.DateField(("Date"), default=datetime.date.today) item_name = models.CharField(max_length=100, blank=True, null=True) quantity = models.IntegerField(blank=True, null=True) quantity_expected = models.IntegerField(blank=True, null=True) total_cost = models.IntegerField(blank=True,null=True) supplier_details = models.CharField(max_length=100, blank=True, null=True) created_by = models.CharField(max_length=100, blank=True, null=True) last_update = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return self.item_name + " " + str(self.quantity) class Issued_items(models.Model): item_date = models.DateField(("Date"), default=datetime.date.today) item_name = models.CharField(max_length=100, blank=True, null=True) quantity_issued = models.IntegerField(blank=True, null=True) issued_to = models.IntegerField(blank=True, null=True) last_update = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return self.item_name + " " + str(self.quantity_issued) -
Nginx redirect with Gunicorn on Django app not working properly
I've developed a simple Django web application but am currently struggling to set up nginx to properly serve static files. The app runs correctly with Gunicorn on port 8000. I'm trying to add static files by accessing the port 8080. Unfortunately, I get the following timeout message after a request on port 8080: nginx_1 | 2020/09/02 12:16:56 [error] 27#27: *5 upstream prematurely closed connection while reading response header from upstream, client: 172.18.0.1, server: , request: "GET /admin/ HTTP/1.1", upstream: "uwsgi://172.18.0.4:8000", host: "0.0.0.0:8080" I believe the error is coming from the server: , part of the error message above, but can't seem to figure out how to actually solve it. Here is my nginx default.conf file: server { listen 8080; location /static { autoindex off; alias /vol/static; } location / { uwsgi_pass app:8000; proxy_request_buffering off; proxy_buffering off; proxy_set_header Host $host:$server_port; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; include /etc/nginx/uwsgi_params; } } Here is the Dockerfile of my nginx image: FROM nginxinc/nginx-unprivileged:1-alpine COPY /docker/prod/nginx/uwsgi_params /etc/nginx/uwsgi_params USER root RUN mkdir -p /vol/static RUN chmod 755 /vol/static USER nginx And here's my docker-compose.yml: version: "3" services: app: build: context: . dockerfile: docker/prod/python/Dockerfile ports: - 8000:8000 volumes: - .:/workspace:cached - static_data:/vol/web working_dir: /workspace/src/ environment: - DJANGO_SETTINGS_MODULE=config.settings.production env_file: - ./src/.env … -
Forgot Password API Django rest framework
I am using OTP authentication for the Forgot password of user. I want the phone no get verify then the user can able to change the password of their account. I want to change the password of the user if the user can verify their number the new password could get set. I someone able to give an answer please help. serializers.py class PasswordSerializer(serializers.Serializer): """ Serializer for password change endpoint. """ new_password = serializers.CharField(required=True) models.py class ResetPhoneOTP(models.Model): phone_regex = RegexValidator( regex = r'^\+?1?\d{9,14}$', message = "Phone number must be entered in the form of +919999999999.") phone = models.CharField(validators = [phone_regex], max_length=17, blank=True) otp = models.CharField(max_length=9, blank=True, null=True) count = models.IntegerField(default=0, help_text = 'Number of opt_sent') validated = models.BooleanField(default=False, help_text= 'if it is true, that means user have validate opt correctly in seconds') def __str__(self): return str(self.phone) + ' is sent ' + str(self.otp) views.py class UserViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): """ list: Return a list of all the existing users. read: Return the given user. me: Return authenticated user. """ queryset = User.objects.all() serializer_class = PasswordSerializer # permission_classes = (IsSuperuserOrIsSelf,) # @action(detail=True, methods=['put']) def post(self, request): phone = request.data.get('phone' , False) # new_password = request.data.get('new_password') if phone: old = ResetPhoneOTP.objects.filter(phone__iexact = … -
How to pass data in django redirect?
I want to pass JSON data with redirect URL, I used HttpResponseRedirect path('session_data_req/', SessionDataFetch.as_view(url='http://0.0.0.0:8080/reciever/')), class SessionDataFetch(APIView): url = None pattern_name = None def get(self, request, *args, **kwargs): url = self.get_redirect_url(*args, **kwargs) data = {"a": "a", "b": "b"} return HttpResponseRedirect(url, data=data) but I am getting an error __init__() got an unexpected keyword argument 'data' I also tried to use return redirect(url, kwargs={"ok", "ok"}) but not getting kwargs data in redirected URL views class ReceiverView(APIView): def get(self, request, *args, **kwargs): print(kwargs) # data = request.data data = kwargs return Response({"a": "----| In receiver |----", "data": data}) response: { "a": "----| In receiver |----", "data": {} } Is there any way to pass data in the redirect function?... and If you are downvoting this question then let me know the reason.