Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to use Firestore with Pyrebase Django
Hey I would like to use Firestore as db in my app rather than RTDB. Is there any way to use firestore with Pyrebase? More over ,if this is not possible, I already tried to use firebase_admin in order to use firestore, But I encountered a problem with authenticating users. When I looked into firebase documentation I saw that there is no native way to authenticate user via Python. https://firebase.google.com/docs/auth, I did find a JS script that can do the job,Is it good practice? is There any security issue with this? ``firebase.auth().createUserWithEmailAndPassword(email, password) .then((user) => { // Signed in // ... }) .catch((error) => { var errorCode = error.code; var errorMessage = error.message; // .. }); `` Any solutions? -
Reverse for 'post_share' with arguments '('',)' not found. 1 pattern(s) tried: ['post_share/(?P<post_id>[0-9]+)$']
views.py def post_share(request, post_id): post = get_object_or_404(Post,id=post_id) sent = False if request.method == 'POST': form = EmailPost(request.POST) if form.is_valid(): cd = form.cleaned_data post_url = request.build_absolute_url(post.get_absolute_url()) subject = f"{cd['name_subject']} recommends you read " \ f"{post.post_title}" message = f"Read {post.post_title} at {post_url}/n/n" \ f"{cd['name_subject']}\'s description: {cd['description']}" send_mail(subject,message, '--------@gmail.com', [cd['send_to']]) sent = True else: form = EmailPost() return render(request, 'mains/post_share.html', {'post':post,'form':form,'sent':sent}) urls.py path('post_share/<int:post_id>',views.post_share,name='post_share'), forms.py class EmailPost(forms.Form): name_subject = forms.CharField(max_length=400) email = forms.EmailField() send_to = forms.EmailField() description = forms.CharField(required=False,widget=forms.Textarea) show_more.html <p><a href="{% url 'mains:post_share' post.id %}">Share this post</a></p> When i click on Share this post ( link ) in share_more.html Reverse for 'post_share' with arguments '('',)' not found. 1 pattern(s) tried: ['post_share/(?P<post_id>[0-9]+)$']. I have tried everything but nothing happens. Please have a look and Please help me in this. I will really appreciate your Help. -
Git submodule: git@github.com: Permission denied (publickey). fatal: Could not read from remote repository
I have a problem with git submodule update --init --remote. I receive errors: Permission denied and Failed to clone. But I added SSH keys to my github repository. I can pull, push, git clone. I have all needed accesses. I use OS Windows 10. I changed in .gitmodules file url=git@github.com:xxx to url=https://github.com/xxx , but not helped. -
How can i access an attribute from another table through many to many relationship in Django?
I am a beginner in django this might be a silly question. I want to access the product table's selling_price & other's data through the order table. This my view.py def createOrder(request): form = OrderForm() if request.method == 'POST': # print('Printing POST:',request.POST) form = OrderForm(request.POST) if form.is_valid(): form.save() return redirect('order') context={'form':form} return render(request,'accounts/order_form.html',context) This is my model.py class Order(models.Model): STATUS=( ('paid','paid'), ('due','due'), ('cancel','cancel') ) customer=models.ForeignKey(Customer,null=True,on_delete=models.SET_NULL) product=models.ManyToManyField(Product) discount=models.FloatField(max_length=200,null=True) total=models.FloatField(max_length=200,null=True) paid=models.FloatField(max_length=200,null=True) due=models.FloatField(max_length=200,null=True) status=models.CharField(max_length=200,choices=STATUS) create_date=models.DateTimeField(auto_now_add=True,null=True) def __str__(self): return self.product.name Here you can see in model i have a many to many relationship with product. Can i get product table's other's details on template through this relationship. <div class="form-group col-md-4"> <label for="name">Product</label> <!-- {{form.product|add_class:"form-control select2bs4"}} --> {% render_field form.product|add_class:"form-control select2bs4" id='productdropdown' %} </div> For say i want to get the selling_price,purchase price of product table instead of a name in the dropdown how can i do that. -
Use checksum to verify integrity of uploaded and downloaded files from AWS S3 via Django
Using Django I am trying to upload multiple files in AWS S3. The file size may vary from 500 MB to 2 GB. I need to check the integrity of both uploaded and downloaded files. I have seen that using PUT operation I can upload a single object up to 5GB in size. They also provide 'ContentMD5' option to verify the file. My questions are: Should I use PUT option if I upload a file larger than 1 GB? Because generating MD5 checksum of such file may exceed system memory. How can I solve this issue? Or is there any better solution available for this task? To download the file with checksum, AWS has get_object()function. My questions are: Is it okay to use this function to downlaod multiple files? How can I use it to download multiple files with checksum from S3? I look for some example but there is noting much. Now I am using following code to download and serve multiple files as a zip in Django. I want to serve the files as zip with checksum to validate the transfer. s3 = boto3.resource('s3', aws_access_key_id=base.AWS_ACCESS_KEY_ID, aws_secret_access_key=base.AWS_SECRET_ACCESS_KEY) bucket = s3.Bucket(base.AWS_STORAGE_BUCKET_NAME) s3_file_path = bucket.objects.filter(Prefix='media/{}/'.format(url.split('/')[-1])) # set up zip folder zip_subdir … -
How can I integrate Tailwind css into my Django project with Docker?
I'm trying to use Tailwind CSS in my Django project running with Docker / Docker-compose. my Django container is built with python:3.9-slim, which has no npm built-in. I am thinking to use node:15.4-alpine to install tailwind css. How can I do so? Can someone give me guidance on Dockerfile and docker-compose.yml I've tried to start with this tailwind playground. But I don't need to run the live-server. -
Test cookies in django
I wanted to check if a browser accepts cookies, so I used set_test_cookie and test_cookie_worked methods to check the same. Then I deleted the test cookies using delete_test_cookie method if the browser passed the test. But to my surprise the session cookie still resides in the browser. This issue exists in both Firefox and Chrome. So what exactly the delete_test_cookie does? Does it delete session cookie? Or is it that session cookie and test cookie are different? -
How to make an asynchronous script for checking online from Minecraft servers?
I need a script to check online from Minecraft servers every 5 minutes. Now the script executes a query request to the server and saves one server to the online database only when entering the server page. Advise how to implement an asynchronous (background for the user) online validation script for all servers views.py class NewsDetailView(DetailView): model = Servers template_name = 'server/server_detail.html' def get_context_data(self, **kwards): ctx = super(NewsDetailView, self).get_context_data(**kwards) ctx['title'] = Servers.objects.filter(pk=self.kwargs['pk']).first() return ctx queryset = Servers.objects.all() def get_object(self): obj = super().get_object() try: server = MinecraftServer.lookup(obj.ip) status = server.status() try: obj.num_players = status.players.online obj.max_players = status.players.max except: print('[Error] Server', str(obj.ip), 'not available') obj.num_players = 0 obj.max_players = 0 obj.save() except: pass return obj -
how to pass another argument to url django?
dans my views.py of page1.html : def spwords(request, spray_id) if request.method == 'POST': value= request.POST["rangeVal"] #### the other argument that i want to pass it to views.py of the second page html ... form = forms.SprayKeywordsForm(request.POST) return HttpResponseRedirect(reverse('sp_url', args=[sp_id])) # if POST we go to page2.html on this url in my url.py : url(r'^queries/(.*)$', qviews.sp_queries, name='sp_url') in my views.py of the Page2.html : def sp_queries(request, sp_id): #### here i want to recupere arguments : sp_id and value i want to pass value= request.POST["rangeVal"] of the views.py of the first page html to the second page html, i.e , i want to pass value in arguments of "HttpResponseRedirect(reverse('sp_url', args=[sp_id]))". but i want to keep the format of urls.py : i.e just queries/sp_id -
how can i show images and checkboxes in xhtml2pdf using django
I am converting Html into pdf using xhtml2pdf using Django and this is my code def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None def myView(request): pdf = render_to_pdf(pdf_template, params) return HttpResponse(pdf, content_type='application/pdf') everything's working fine till now, but I also want to show the company logo and some checkboxes on pdf and that is not working. no error, no wrong output, just blank space in place of image and checkboxes. Any idea of how can I get images and checkboxes in my pdf? -
How can I show the StringRelatedField instead of the Primary Key while still being able to write-to that field using Django Rest Framework?
Models: class CrewMember(models.Model): DEPARTMENT_CHOICES = [ ("deck", "Deck"), ("engineering", "Engineering"), ("interior", "Interior") ] first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) email = models.EmailField() department = models.CharField(max_length=12, choices=DEPARTMENT_CHOICES) date_of_birth = models.DateField() join_date = models.DateField() return_date = models.DateField(null=True, blank=True) leave_date = models.DateField(null=True, blank=True) avatar = models.ImageField(null=True, blank=True) active = models.BooleanField(default=True) def __str__(self): return f"{self.first_name} {self.last_name}" class RosterInstance(models.Model): date = models.DateField(default=timezone.now) deckhand_watchkeeper = models.ForeignKey(CrewMember, on_delete=models.PROTECT, null=True, related_name="deckhand_watches") night_watchkeeper = models.ForeignKey(CrewMember, on_delete=models.PROTECT, null=True, related_name="night_watches") def __str__(self): return self.date.strftime("%d %b, %Y") Views: class CrewMemberViewSet(viewsets.ModelViewSet): queryset = CrewMember.objects.all() serializer_class = CrewMemberSerializer filter_backends = [SearchFilter] search_fields = ["department"] def destroy(self, request, *args, **kwargs): instance = self.get_object() instance.active = False instance.save() return Response(status=status.HTTP_204_NO_CONTENT) class RosterInstanceViewSet(viewsets.ModelViewSet): queryset = RosterInstance.objects.all() serializer_class = RosterInstanceSerializer Serializers: class CrewMemberSerializer(serializers.ModelSerializer): class Meta: model = CrewMember fields = "__all__" class RosterInstanceSerializer(serializers.ModelSerializer): class Meta: model = RosterInstance fields = "__all__" The resulting data looks like this: { "id": 2, "date": "2020-12-09", "deckhand_watchkeeper": 1, "night_watchkeeper": 3 } But I want it to look like this: { "id": 2, "date": "2020-12-09", "deckhand_watchkeeper": "Joe Soap", "night_watchkeeper": "John Smith" } I can achieve the above output by using StringRelatedField in the RosterInstanceSerializer but then I can no longer add more instances to the RosterInstance model (I believe that is because StringRelatedField … -
show a new input in django forms with a button click
I have a form that has 13 inputs some of them are <input> and others are <select> In the beginning I only show the first two inputs and the others are completely ignored, now what I want is to make a button to show the next input. My Idea was that I make 13 forms in the forms.py file but I don't think it's a good idea. so how can I do that? -
Backend countdown timer in django
I am developing a quiz application in Django. I wish to maintain a timer for attending a quiz, and user shouldn't be able to change the time from the front end. There maybe ways to implement one using JavaScript, but those could be easily changed by the user. So what i want is something like maintain a timer at the server side so that the quiz gets automatically submitted once the time is up. I am working on django 3.1. Please help. -
Best approach to customize django admin page for existing app
I'm currently learning some basics of django by trying to implement admin page for the following app: PowerGSLB Though it already has nice UI based on W2UI my goal is to learn django and make role based authentication with help of django admin module. But it's actually not the point of the question. I got stuck with presenting basic list of DNS records to user. DB model looks like this: db_model_image So, I ran through inspectdb and created models, based on this structure. After all, my Records model looks like this: class Records(models.Model): id = models.BigAutoField(primary_key=True) name_type = models.ForeignKey(NamesTypes, models.DO_NOTHING) content_monitor = models.ForeignKey(ContentsMonitors, models.DO_NOTHING) view = models.ForeignKey('Views', models.DO_NOTHING) disabled = models.BigIntegerField() fallback = models.BigIntegerField() weight = models.BigIntegerField() def __str__(self): return f"{self.name_type} {self.content_monitor} {self.disabled} {self.fallback} {self.weight}" def get_all(self, in_var): self.result = dict() # Objects to get results from self.name_type_obj = NamesTypes.objects.get(id=self.name_type_id) self.content_monitor_obj = ContentsMonitors.objects.get(id=self.content_monitor_id) self.view_obj = Views.objects.get(id=self.view_id) self.names_obj = Names.objects.get(id=self.name_type_obj.name_id) self.domain_obj = Domains.objects.get(id=self.names_obj.domain_id) self.contents_obj = Contents.objects.get(id=self.content_monitor_obj.content_id) self.monitor_obj = Monitors.objects.get(id=self.content_monitor_obj.monitor_id) self.types_obj = Types.objects.get(value=self.name_type_obj.type_value_id) # Result vars self.result['domain'] = self.domain_obj.domain self.result['name'] = self.names_obj.name self.result['type'] = self.types_obj.type self.result['content'] = self.contents_obj.content self.result['ttl'] = self.name_type_obj.ttl self.result['id'] = self.id self.result['disabled'] = self.disabled self.result['fallback'] = self.fallback self.result['persistence'] = self.name_type_obj.persistence self.result['weight'] = self.weight self.result['monitor'] = self.monitor_obj.monitor self.result['view'] = self.view_obj.rule … -
drf if not verified create user
i have this app and i'm doing otp verification on mail after registration. if user not verified then send mail again so i have added this check on registration if user exist and is_verified then return user already exist otherwise i want to delete and create again because it'll proceed without deleting but i'm getting error on else condition: AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'tuple'>` seems its expect response on else condition after deleting user and i want to create again after delete and also if user doestnotexist then simply create one and send mail @api_view(["POST"]) @permission_classes((AllowAny,)) def register(request): try: user = CustomUser.objects.get( email=request.data.get('email')) if user.is_verified: return Response({'message': 'Customer with this mail already exists', 'status': 'false', 'status_code': status.HTTP_401_UNAUTHORIZED, 'currentTimeStamp': datetime.datetime.now()}, status=status.HTTP_400_BAD_REQUEST) else: user.delete() except CustomUser.DoesNotExist: serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() serializers.py: class CustomUserSerializer(serializers.ModelSerializer): profile = UserProfileSerializer(required=False) password = serializers.CharField(write_only=True, required=False) class Meta: model = CustomUser fields = ('id', 'first_name', 'last_name', 'email', 'mobile_number', 'password', 'is_active', 'user_type', 'otp', 'profile') def create(self, validated_data): profile_data = validated_data.pop('profile', None) user = CustomUser( email=validated_data['email'], mobile_number=validated_data['mobile_number'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], user_type=validated_data['user_type'], ) user.set_password(validated_data['password']) def random_with_N_digits(n): range_start = 10**(n-1) range_end = (10**n)-1 return randint(range_start, range_end) … -
How to delete from queryset without deleting the original model itself in Django
So, I have two model sets like the following: # User class class User(AbstractBaseUser, PermissionsMixin): objects = CustomUserManager() ... email = models.EmailField(verbose_name='email', max_length=50, null=False, unique=True) password = models.CharField(verbose_name="password", max_length=200) name = models.CharField(verbose_name="name", max_length=50) username = models.CharField(verbose_name="nickname", max_length=50, unique=True) date_of_birth = models.DateField(verbose_name="birthday", max_length=8) profile_pic = models.ImageField(verbose_name="profile picture", default="default_profile.png") USERNAME_FIELD='email' REQUIRED_FIELDS=['password', 'name', 'username', 'date_of_birth'] followers = models.ManyToManyField( 'self', symmetrical=False, through='Relationship', related_name='followees', through_fields=('to_user', 'from_user'), ) @property def followers(self): follower_relationship = self.relationship_to_user.filter(relationship_type=Relationship.RELATIONSHIP_TYPE_FOLLOWING) follower_list = follower_relationship.values_list('from_user', flat=True) followers = User.objects.filter(pk__in=follower_list) return followers @property def followees(self): followee_relationship = self.relationship_from_user.filter(relationship_type=Relationship.RELATIONSHIP_TYPE_FOLLOWING) followee_list = followee_relationship.values_list('to_user', flat=True) followees = User.objects.filter(pk__in=followee_list) return followees def follow(self, to_user): self.relationship_from_user.create( to_user = to_user, relationship_type='f' ) def __str__(self): return self.username # Relationships class class Relationship(models.Model): RELATIONSHIP_TYPE_FOLLOWING = 'f' RELATIONSHIP_TYPE_BLOCKED = 'b' CHOICE_TYPE = ( (RELATIONSHIP_TYPE_FOLLOWING, '팔로잉'), (RELATIONSHIP_TYPE_BLOCKED, '차단'), ) from_user = models.ForeignKey( User, related_name='relationship_from_user', on_delete=models.CASCADE, ) to_user = models.ForeignKey( User, related_name='relationship_to_user', on_delete=models.CASCADE, ) relationship_type=models.CharField(max_length=1, choices=CHOICE_TYPE) def __str__(self): return f"{self.from_user} follows {self.to_user}, type={self.relationship_type}" And in the python manage.py shell, I did the following: >>> user1 = User.objects.get(id=1) # user1@gmail.com >>> user2 = User.objects.get(id=2) # user2@gmail.com >>> user3 = User.objects.get(id=3) # user3@gmail.com >>> user1.follow(user2) >>> user1.follow(user3) >>> user1.followees <QuerySet [<User: user2@gmail.com>, <User: user3@gmail.com>]> Now my main question is related to the user1.followees. I want to delete <User: … -
Using django Authentication form with the html form
I am trying to build a login module in django. I already have a nice HTML form for login which has username and password field. But in my views.py I have imported default Django AuthenticationForm, but if integrate it with my nice-looking HTML form, there will be two forms. How can I import the Authentication form and use it with the mt HTML form?? My code is here: My view: def login(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() authlog(request, user) return redirect('home') else: messages.error(request, 'Invalid username or password') # back_page = request.META.get('HTTP_REFERER') return redirect('login') # return HttpResponse(back_page) else: content = { 'form': AuthenticationForm() } return render(request, 'sign-in.html', content) If I use Django default form, the code will be following, but it won't look good as my other Html login page. My sign-in html: <hr> <form action="" method="post"> {% csrf_token %} {{form|crispy}} <button type="submit" class=" btn btn-success ">Sign-Up</button> </form> I haven't posted my other HTML form though as it is very large. Hope it explains. -
How to use a C++ UDF in MySql with Django cursor?
I have a Django project where I am using MySQL. I want to use a C function for a particular kind of filter. I read up about using C function in MySQL but I could get nowhere how to use it with a cursor in Django. I tried using cur.execute('CREATE FUNCTION udf RETURNS STRING SONAME "udf_example.so";'), but that did not work. This is my views.py def testSearch(subject, year=0, department="", paper_type="", keywords=""): year_filter = "AND p.year = {}".format(year) if year > 0 else "" dep_filter = "AND d.code = '{}'".format(department)\ if department != "" else "" type_filter = "AND p.paper_type = '{}'".format(paper_type)\ if paper_type != "" else "" keyword_filter = "AND kt.text IN {}".format(keywords)\ if keywords != "" else "" if subject == "": return [] if keyword_filter == "": query =\ """ SELECT p.subject, p.year, d.code, p.paper_type, p.link, p.id FROM papers p JOIN departments d ON p.department_id = d.id WHERE bitap(p.subject, '{}') = 1 {} {} {} ORDER BY year DESC LIMIT 30; """.format(subject, year_filter, dep_filter, type_filter) else: query =\ """ SELECT p.subject, p.year, d.code, p.paper_type, p.link, p.id, GROUP_CONCAT(kt.text) AS keywords FROM papers AS p JOIN departments AS d ON p.department_id = d.id LEFT OUTER JOIN ( SELECT pk.paper_id, k.text … -
Whats problem with my code because my navbar is not looks like i want to
Help me with my navbar design and code is below <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> </head> <body> <nav class = "navbar navbar-expand-lg navbar-light bg-light"> <div class = "container"> <ul class = "navbar-nav"> <li class="nav-item"> <a class = "navbar-brand" href="{% url 'index' %}">Django </a> </li> <li class="nav-item"> <a class = "navbar-link" href="{% url 'admin:index' %}"> Admin </a> </li> <li class="nav-item"> <a class = "navbar-link" href="{% url 'basic_app:register' %}"> Register </a> </li> </ul> </div> </nav> <div class="container"> {% block body_block %} {% endblock %} </div> </body> </html>[![enter image description here][1]][1] I have attacted the screenshot of my webpage also. Whats problem with my code because my navbar is not looks like i want to -
Django-channels : ChatConsumer is sending message to only one user instead of sending it to both users
I am implementing a chat application in django and angular using django-channels and redis. The sockets get connected and work properly but the problem I am facing is that when two users are online and connect the same chatroom with the same thread url it connects but the messages sent by any user are only sent to the user that connected the socket recently and they are sent twice to only that user. In django I did the following configurations: settings/base.py .... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'channels', 'chats' ] ASGI_APPLICATION = "influnite.routing.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], # "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')] }, }, } .... routing.py from django.conf.urls import url from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator, OriginValidator from chats.consumers import ChatConsumer application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url(r"^messages/(?P<thread_id>[\w.+]+)/", ChatConsumer()) ] ) ) ) }) I created three models namely Thread, ThreadMember & ChatMessage. chats/models.py from django.db import models from django.db.models import Q from django.utils import timezone from django.contrib.auth.models import User from base.models import BaseModel # Create your models here. MESSAGE_TYPE = [ ('text', 'Text'), ('audio', 'Audio'), ('img', 'Image'), ('doc', … -
Django Rest framework list object has no attribute lower when specifying date format in settings
I want to format date fields to d/m/y format. However when I use the below code in the settings file I get the following error: 'list' object has no attribute 'lower' when performing the get request to fetch the data. My model field looks like this: licence_expiry_date = models.DateField() https://www.django-rest-framework.org/api-guide/settings/#date-and-time-formatting REST_FRAMEWORK = { "DATE_FORMAT": ["%d/%m/%Y"], } -
XMLHttpRequest doesn't send the data
I'm making a POST request from my react component to django-backend. My request goes to my server but I can't take the data I sent. The thing is I can log the status with onload on browser and I get 200 and I do get a POSTrequest in django so there is no problem with making a POSTrequest, the problem is sending data. send seems the problem here. My react component: import React, { useEffect, useState } from "react"; import { BiMeteor } from "react-icons/bi"; import { registerUser } from "../lookup"; export function RegisterComponent() { function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== "") { const cookies = document.cookie.split(";"); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === name + "=") { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function registerUser(e) { e.preventDefault(); const url = "http://localhost:8000/register"; const method = "POST"; /* const data = JSON.stringify({ username, password }) */ const xhr = new XMLHttpRequest(); const csrftoken = getCookie("csrftoken"); xhr.open(method, url); xhr.setRequestHeader("Content-Type", "application/json"); xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest"); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.setRequestHeader("X-CSRFToken", csrftoken); … -
drf CustomUser matching query does not exist
i'm working on mobile app with customuser. i'm trying to send otp on mail while creating user and set is_verify to false and after that user verify with otp then is_verify will set to true but if user does't verify otp add closes app then again while signup we're adding check if user exist and is_verified to true then return already exist otherwise create user and send otp again. so i'm getting error on if user doesnotexist then its showing this error: users.models.CustomUser.DoesNotExist: CustomUser matching query does not exist. and its getting this error from except customuser.doesnotexist block models.py: class CustomUser(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(_('first name'), max_length=50) last_name = models.CharField(_("last name"), max_length=50) email = models.EmailField(_('email address'), unique=True) mobile_number = models.CharField( _('mobile number'), max_length=12, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) user_type = models.IntegerField(_("user_type")) otp = models.CharField(_("otp"), max_length=10, default="0") is_verified = models.BooleanField(default=False) USER_TYPE_CHOICES = ( (1, 'users'), (2, 'courier'), (3, 'admin'), ) user_type = models.PositiveSmallIntegerField( choices=USER_TYPE_CHOICES, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserMananager() def __str__(self): return self.email seralizers.py: class CustomUserSerializer(serializers.ModelSerializer): profile = UserProfileSerializer(required=False) password = serializers.CharField(write_only=True, required=False) class Meta: model = CustomUser fields = ('id', 'first_name', 'last_name', 'email', 'mobile_number', 'password', 'is_active', 'user_type', 'otp', 'profile') def … -
How to store form data as draft in django
I'm working on a project that requires to store form data as a draft if the user closes the browser or leave the tab or any other case. and when the user opens the same form next time the user can see the previously entered data -
The requested resource was not found on this server. React + Django
I'm deploying my first Django + React app do a Droplet with Apache2. I've deployed some Django apps but this is my first time deploying a React app not to mention a React and Django app. When I visit the homepage I get The requested resource was not found on this server. and when I visit /admin I get the login page but without any styles. I notice in my dev tools I see 404 in the network tab. settings.py import environ ROOT_DIR = ( environ.Path(__file__) - 3 ) REACT_APP_DIR = ROOT_DIR.path("react_frontend") STATICFILES_DIRS = [ os.path.join(str(REACT_APP_DIR.path("build")), 'static'), ] STATIC_ROOT = '/srv/react-django-portfolio/react_frontend/build/static' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ str(REACT_APP_DIR.path("build")), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] sites-available/portfolio.conf <VirtualHost *:443> ServerName example.com DocumentRoot /srv/react-django-portfolio/django_backend/django_backend SSLEngine on SSLCertificateFile /etc/ssl/example.crt SSLCertificateKeyFile /etc/ssl/example.key SSLCertificateChainFile /etc/ssl/example.ca-bundle ErrorLog ${APACHE_LOG_DIR}/portfolio-error.log CustomLog ${APACHE_LOG_DIR}/portfolio-access.log combined WSGIDaemonProcess portfolio processes=2 threads=25 python-path=/srv/react-django-portfolio/django_backend WSGIProcessGroup portfolio WSGIScriptAlias / /srv/react-django-portfolio/django_backend/django_backend/wsgi.py Alias /robots.txt /srv/portfolio/static/robots.txt Alias /favicon.ico /srv/portfolio/static/favicon.ico Alias /static/ /srv/django-react-portfolio/react_frontend Alias /media/ /srv/portfolio/media/ <Directory /srv/react-django-portfolio/django_backend/django_backend> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /srv/react-django-portfolio/react_frontend/build/static> Require all granted </Directory> <Directory /srv/reat-django-portfolio/django_backend/media> Require all granted </Directory> </VirtualHost>