Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'ManyToManyDescriptor' object has no attribute 'add' in Django with PostgreSQL
I am trying to store some data in my database, where 2 different model refer each other with 'Many-to-Many' fields. my models.py: class CorrectAns(models.Model): ansId = models.IntegerField(primary_key=True) responseText1 = models.TextField(null=True, blank=True) isDeleted = models.BooleanField(default=False) questionRef = models.ManyToManyField('Questions') class Questions(models.Model): questionId = models.IntegerField(primary_key=True) groupId = models.IntegerField(default=0) questionTitle = models.TextField() correctAnsRef = models.ManyToManyField(CorrectAns, related_name="questionReletedResponses") my views.py: for i in QuestionsList: questionObj = Questions( questionId = i['Id'], groupId = i['GroupId'], questionTitle = i['QuestionTitle'], ) questionObj.save() for j in i['Responses']: correctAnsObj = CorrectAns.objects.create( ansId = j['Id'], responseText1 = myResponseText1, isDeleted = j['IsDeleted'], ) correctAnsObj.questionRef.add(questionObj) correctAnsObj.save() Questions.correctAnsRef.add(correctAnsObj) return now it shows error with line: Questions.correctAnsRef.add(correctAnsObj) Like: 'ManyToManyDescriptor' object has no attribute 'add' Please suggest how can I fix this? -
Django Session Auth and DRF Knox JWT
I have an API from which users can login to get a token so they can make requests, etc and I have also made a a session login as there are a few scenarios where I need the user session token. Now if a user logs in to the API and afterwards they need to login using the session Auth its all good however the reverse does not work. If you are logged in using session Auth and then want to login via the API to release a token I get a response of Forbidden. Could someone please offer some insight? -
JWT Authorization multiple role in django rest framework using simple-jwt
I have a django website using django-rest-framework and simple-jwt for authentication. Docs: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/index.html My website have 2 role with different capability. I have to authorize them. But I can't find how to do it. Anyone can give me an example or docs to do this function. Thank you very much. -
How to implement a verification system? Django
The task is to implement a verification system for the following actions: registration, password reset, change of email address, change of phone number. What do I mean by this task? Need to generate tokens and then send them to user email address or phone number. After using them, user will be verified. For myself, I have identified a bunch of options, but I don’t know which one to choose. Generate the same type of token for SMS and email. This token is a code, six-digit, for example. Store them in redis, where the key is the user id and the value is the token itself. When the code comes from the client, search for it in redis. If it does not exist, then it is possible that it expired, or it did not exist at all. Store codes in the Django model, delete expired ones on access and make a management command so that we can delete those that have not been accessed. Generate only digital codes for SMS, and character tokens for email. It is possible that there is no best option at all among those listed. Please tell me the best practices. I am interested in what method … -
Problem with testing custom admin actions
Running into some problems when testing my custom admin actions. First I can show you an example of a test that works and the actions it's testing. custom action, Product model @admin.action(description="Merge selected products") def merge_products(self, request, queryset): list_of_products = queryset.order_by("created_at") list_of_products = list(list_of_products) canonical_product = list_of_products[0] list_of_products.remove(canonical_product) for p in list_of_products: for ep in p.external_products.all(): ep.internal_product = canonical_product ep.save() p.save() canonical_product.save() related test class MockRequest(object): pass class ProductAdminTest(TestCase): def setUp(self): self.product_admin = ProductAdmin(model=Product, admin_site=AdminSite()) User = get_user_model() admin_user = User.objects.create_superuser( username="superadmin", email="superadmin@email.com", password="testpass123" ) self.client.force_login(admin_user) def test_product_merge(self): self.boot1 = baker.make("products.Product", title="Filippa K boots", id=uuid4()) self.boot2 = baker.make("products.Product", title="Filippa K boots", id=uuid4()) self.external_product1 = baker.make( "external_products.ExternalProduct", internal_product=self.boot1 ) self.external_product2 = baker.make( "external_products.ExternalProduct", internal_product=self.boot2 ) self.assertEqual(self.boot1.external_products.count(), 1) self.assertEqual(self.boot2.external_products.count(), 1) request = MockRequest() queryset = Product.objects.filter(title="Filippa K boots") self.product_admin.merge_products(request, queryset) self.assertEqual(self.boot1.external_products.count(), 2) self.assertEqual(self.boot2.external_products.count(), 0) Might not be the pretties test but it works, so does the action. The code above works as it should but has been running into problems when trying to test an almost identical action but for another model. custom action, Brand model @admin.action(description="Merge selected brands") def merge_brands(self, request, queryset): qs_of_brands = queryset.order_by("created_at") list_of_brands = list(qs_of_brands) canonical_brand = list_of_brands[0] for brand in list_of_brands: if brand.canonical: canonical_brand = brand list_of_brands.remove(canonical_brand) … -
Trouble in setting only one serializer field to read_only Django Rest Framework
I have this model serializer and it has a lot of fields I want to use fields="__all__" but still be able to set one field to read_only = True. I tried having it like this: class InstitutionSerializer(serializers.ModelSerializer): class Meta: model = Institution fields = "__all__" def __init__(self, *args, **kwargs): super(InstitutionSerializer, self).__init__(*args, **kwargs) for field in self.fields: if field == "owner": self.fields[field].read_only = True But it still flags "owner": ["This field is required."] which is unneccessary for me because I want it to be able to set it on my view. I also tried extra_kwargs = {"owner": {"read_only": True}} and read_only_fields = ("owner",) but still fails. -
clean() method in Django ModelForm to avoid duplicate entries creates another instance upon updating the data. And doesn't even save a new instance
I have a few models, two of which are as follows: class Receivables(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) pattern = RegexValidator(r'(RT|rt|rT|Rt)\/[0-9]{4}\/[0-9]{2}\/[0-9]{4}', 'Enter RT Number properly!') rt_number=models.CharField(max_length=15, validators=[pattern]) discount=models.DecimalField(max_digits=9, decimal_places=2, default=0) approved_package=models.DecimalField(max_digits=10, decimal_places=2, default=0) approval_date=models.DateField(default=None) proposed_fractions=models.IntegerField() done_fractions=models.IntegerField() base_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True) expected_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True) class Discharge(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) date_of_discharge=models.DateField(default=None) mould_charges=models.DecimalField(max_digits=7, decimal_places=2, default=0, blank=True) ct_charges=models.DecimalField(max_digits=7, decimal_places=2, default=0, blank=True) discharge_updated=models.BooleanField(default=False) The views to save the new instance and update the existing one respectively, are: 1. def discharge_view(request): if request.method=='POST': fm_discharge=DischargeForm(request.POST, request=request) if fm_discharge.is_valid(): discharge=fm_discharge.save() ipd=IpdReport.objects.create(patient=discharge.patient, package=Package.objects.filter(patient=discharge.patient).order_by('-id').first(), receivables=Receivables.objects.filter(patient=discharge.patient).order_by('-id').first(), discharge=discharge) if discharge is not None: OngoingReport.objects.filter(ipdreport__patient=discharge.patient).delete() package=Package.objects.filter(patient=discharge.patient).order_by('-id').first().patient_type.patient_type if discharge.discharge_updated==False and package!='CASH': UnclaimedPendingCases.objects.create(ipdreport=ipd) elif discharge.discharge_updated==True and package!='CASH': ClaimedPendingCases.objects.create(ipdreport=ipd) fm_discharge=DischargeForm(request=request) return render(request, 'account/discharge.html', {'form':fm_discharge}) else: fm_discharge=DischargeForm(request=request) return render(request, 'account/discharge.html', {'form':fm_discharge}) def update_discharge_view(request, id): di1=Discharge.objects.get(pk=id) fm1=di1.discharge_updated if request.method=='POST': print(request.POST) di=Discharge.objects.get(pk=id) form=DischargeForm(request.POST, instance=di, request=request) if form.is_valid(): discharge=form.save() else: di=Discharge.objects.get(pk=id) form=DischargeForm(instance=di, request=request) return render(request, 'account/update_discharge.html', {'form':form}) The ModelForm looks as below: class DischargeForm(ModelForm): class Meta: model=Discharge fields='__all__' widgets={ 'date_of_discharge': DateInput(attrs={'type': 'date'}), } def __init__(self, *args, **kwargs): self.request=kwargs.pop('request') self.instance=kwargs.pop('instance') super(DischargeForm, self).__init__(*args, **kwargs) def clean(self): super().clean() pt=self.request.POST.get('patient') if not self.instance: rec=Receivables.objects.filter(patient__pk=pt).order_by('-id').first() if Discharge.objects.filter(patient__pk=pt, date_of_discharge__gt=rec.approval_date).exists(): raise ValidationError('The patient has already been discharged!') I want the discharge to be saved only once, for each time the patient gets treatment. Though it can be updated. Earlier I had written … -
Django form is not being valid, how to fix it?
I am new to Django and I was creating an e-commerce store using Django. I successfully created User Login Form which works perfectly, but I am stuck at User Registration Form. It is not being valid. My forms.py: from django import forms from django.forms.widgets import PasswordInput class UserLoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) class UserRegistrationForm(forms.Form): username = forms.CharField() email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) def clean(self): cleaned_data = super().clean() data = self.cleaned_data password = cleaned_data.get('password') password2 = cleaned_data.get('password2') if password2 != password: raise forms.ValidationError("Passwords must match") return data My register.html <div> <form method="POST" action=""> {% csrf_token %} {{ form.as_p }} <input type="submit" name="Register"> </form> </div> My login.html <div> <form method="POST" action=""> {% csrf_token %} {{ form.as_p }} <input type="submit" name="Login"> </form> </div> My views.py from django.contrib.auth import authenticate, login from django.shortcuts import render, redirect from .forms import UserLoginForm, UserRegistrationForm # Create your views here. def userRegistrationPage(request): form = UserRegistrationForm() context = { 'form': form } if request.method == 'POST': form = UserRegistrationForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") print(username, password) else: print("Form is not valid") return render(request, 'index/register.html', context) def userLoginPage(request): form = UserLoginForm() context = { 'form': form } … -
How do I JSON parse a Django queryset?
So I'm trying to parse each object in my Django queryset, and deal with the data through JavaScript. Below is my code (simplified) : views.py (using Django Paginator, but the basic idea is the same.) def main_page(request): all_contents = Contents.objects.all() paginator_contents = Paginator(contents,10) page = request.GET.get('page') all_contents_paginated = paginator_contents.get_page(page) context = { 'contents' : contents, 'all_contents_paginated' : all_contents_paginated } return render(request, 'main/home.html', context) template {% for c in all_contents_paginated %} <div class="text-m"> {{c.author}} </div> <div class="text-s" onclick="DetailModal('{{c}}')"> {{c.body}} </div> {% endfor %} <script> function DetailModal(c) { } </script> Now obviously, the '{{c}}' cannot be parsed into JSON since it's string. I want to parse it into JSON in function DetailModal() and display the data in a separate modal element or do any other stuff with each data. But I can't figure out how to parse each object in the Django queryset. Any ideas? Thanks. -
Fill out Django form with data obtained from URL
I want to create a new Fallacy (see models.py) via the form to which I get over the url path('<slug:slug_tree>/new/', views.CreateFallacyView.as_view(), name='create_fallacy'),. So the user is on the TreeDetailView (which corresponds to a certain Tree), and he can add a new Fallacy to this tree. The user should input title and detail, but the Tree (ForeignKey) should be assigned in the code. It should be assigned to the corresponding Tree from which he was directed to the CreateFallacyView. The slug of the tree is inside the URL, so I thought I could use that information somehow, but I have no idea how I can proceed with that information. Any help is appreciated! Or probably there are other more elegant solutions? Many thanks! models.py class Tree(models.Model): title = models.CharField(max_length=50) detail = models.TextField() slug = models.SlugField(allow_unicode=True, unique=True, null=True, blank=True) class Fallacy(models.Model): title = models.CharField(max_length=50) detail = models.TextField() tree = models.ForeignKey(Tree, related_name='fallacy', on_delete=models.CASCADE) views.py class CreateFallacyView(generic.CreateView): form_class = forms.FallacyForm forms.py class FallacyForm(forms.ModelForm): class Meta: model = models.Fallacy fields = ('title', 'detail') urls.py app_name = 'argtree' urlpatterns = [ path('', views.TreeListView.as_view(), name='all'), path('<slug:slug_tree>/', views.TreeDetailView.as_view(), name='tree_detail'), path('<slug:slug_tree>/new/', views.CreateFallacyView.as_view(), name='create_fallacy'), -
I’ve set the exact date in admin but it keeps saying that there’s no available rooms. Maybe incorrect date format? Thanks in advance
In models.py This is the models.py I used DateTimeField for this In views.py this is the views to check if the room is available or not -
django get_queryset() with conditional filter()
I have a custom model manager on model such as: class MyCustomManager(models.Manager): def doFoo(self, user, s_format): qs = super().get_queryset().filter(created_by=user) return qs which is returning data based on the user passed as the argument. However, how would I go about adding more AND conditions to the above query based on if conditions? Something like this: class MyCustomManager(models.Manager): def doFoo(self, user, s_format): qs = super().get_queryset().filter(created_by=user) if <condition 1>: qs.filter(mode='A') elif <condition 2>: qs.filter(mode='B') return qs If I do the above, even if <condition 2> is true, it's not generating created_by=1 AND mode='B' SQL I'm basically trying to do the equivalent of the following but split by conditions qs = super().get_queryset().filter(created_by=user, mode='A') -
How to configure celery for concurrent execution with multi process?
I have a task that talks to an external API, the json response is quite large and I have to make this call multiple times followed by further python processing. To make this less time-consuming, I initially tried: def make_call(*args, **kwargs): pass def make_another(*args, **kwargs): pass def get_calls(): return make_call, make_another def task(*args, **kwargs): procs = [Process(target=get_calls()[i], args=(,), kwargs={}) for i in range(3)] _start = [proc.start() for proc in procs] _join = [proc.join() for proc in procs] # transaction.on_commit(lambda: task.delay()) However, I ran into an ```AssertionError: daemonic processes are not allowed to have children. What would be my best approach to speed up a celery task with additional processes? -
Python/Django - How to check url endpoint with an attached JWT?
I need to connect to a server from my Django application (Connection Test). The problem is that the server I'm trying to connect to only returns http_200 if an attached JWT token at the Authorization Header is given. How can I attach a JWT to a request I send from my application? Currently, I generate the JWT for the test connection like so: user = self.context['request'].user jwt_payload = jwt_payload_handler(user) access_token = str("Bearer " + jwt_encode_handler(jwt_payload)) Thanks in advance -
I want to get current url in settings.py file in django
I want to set an if condition in settings.py in my django app, to check the url and apply correct GOOGLE_RECAPTCHA_SECRET_KEY for the site. because of difference in local host and web server domin. I used requests._current_scheme_host but get an error: File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/registry.py", line 136, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
template tags is showing duplicate items in template
I am building a Blog App and I built a template tag to sort posts by likes. Template tag I working fine, But when I sort by likes then it is showing duplicate items according to likes. I mean, If a post got 3 likes then it is showing that post thee times. models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=1000) body = models.CharField(max_length=1000) likes = models.ManyToManyField(User, related_name='likes') template_tags.py from django import template register = template.Library() @register.filter def sort(queryset, order): return queryset.order_by(order) views.py def posts(request): posts = BlogPost.objects.filter(user=request.user) context = {'posts':posts} return render(request, 'posts.html', context) posts.html {% load template_tags %} {% for post in posts|sort:'likes' %} {{post.title}} {% endfor %} I have also tried by using distinct() in both template_tags.py and views.py but it is making no effect on query. Any help would be much Appreciated. Thank You -
ERROR when i run pip install mssql-django
Running setup.py install for pyodbc ... error ERROR: Command errored out with exit status 1: command: 'C:\Users\Admin\env\Scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-8lp5uvpv\\pyodbc_fab15be00b0e459faaa8c78be119016d\\setup.py'"'"'; __file__='"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-8lp5uvpv\\pyodbc_fab15be00b0e459faaa8c78be119016d\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Admin\AppData\Local\Temp\pip-record-clbuf4z_\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\Admin\env\include\site\python3.10\pyodbc' cwd: C:\Users\Admin\AppData\Local\Temp\pip-install-8lp5uvpv\pyodbc_fab15be00b0e459faaa8c78be119016d\ Complete output (12 lines): running install running build running build_ext building 'pyodbc' extension creating build creating build\temp.win-amd64-3.10 creating build\temp.win-amd64-3.10\Release creating build\temp.win-amd64-3.10\Release\src C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -DPYODBC_VERSION=4.0.32 -IC:\Users\Admin\env\include -IC:\Users\Admin\AppData\Local\Programs\Python\Python310\include -IC:\Users\Admin\AppData\Local\Programs\Python\Python310\Include -IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\include /EHsc /Tpsrc\buffer.cpp /Fobuild\temp.win-amd64-3.10\Release\src\buffer.obj /Wall /wd4514 /wd4820 /wd4668 /wd4711 /wd4100 /wd4127 /wd4191 /d2FH4- buffer.cpp C:\Users\Admin\AppData\Local\Temp\pip-install-8lp5uvpv\pyodbc_fab15be00b0e459faaa8c78be119016d\src\pyodbc.h(19): fatal error C1083: Cannot open include file: 'windows.h': No such file or directory error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Tools\\MSVC\\14.29.30133\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2 ---------------------------------------- ERROR: Command errored out with exit status 1: 'C:\Users\Admin\env\Scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-8lp5uvpv\\pyodbc_fab15be00b0e459faaa8c78be119016d\\setup.py'"'"'; __file__='"'"'C:\\Users\\Admin\\AppData\\Local\\Temp\\pip-install-8lp5uvpv\\pyodbc_fab15be00b0e459faaa8c78be119016d\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Admin\AppData\Local\Temp\pip-record-clbuf4z_\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\Admin\env\include\site\python3.10\pyodbc' Check the logs for full command output. -
how to get specific field in serialiser with related_name by Django rest
i have model named ContactPhone and in the model link to Lead model with field lead_id and ralated_name phones class ContactPhone(models.Model): phone_number = PhoneNumberField(blank=True, default='') phone_type = models.CharField( max_length=100, blank=True, choices=ContactPhoneInterface.phone_number_types, default=PhoneNumbers.mobile.name ) contact_id = models.ForeignKey( Contact, on_delete=models.CASCADE, null=True, related_name='phones_c' ) lead_id = models.ForeignKey( Lead, on_delete=models.CASCADE, null=True, related_name='phones' ) by this serilizer class i got id of ContactPhone table, but i need got phone_number field in ContactPhone. class LeadListSerializer(serializers.ModelSerializer): class Meta: model = Lead fields = ( 'id', 'full_name', 'responsible_id', 'phones', 'emails', ) tried different options to solve this problem but it doesn't help. In the screenshot you can see response of this moment, id of ContactPhone -
how can i login with local url in Django administration and add user?
i tried for make a django userprofile but i can't Enter to login page there is my error when i enter to my local url TypeError at /account/login/ __init__() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/account/login/ Django Version: 3.2.9 Exception Type: TypeError Exception Value: __init__() takes 1 positional argument but 2 were given Exception Location: /home/pantea/.local/lib/python3.6/site-packages/django/core/handlers/base.py, line 181, in _get_response Python Executable: /usr/bin/python3 Python Version: 3.6.9 Python Path: ['/home/pantea/tutorial', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/pantea/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] here is my url file from django.conf.urls import url from django.contrib.auth.views import LoginView,LogoutView from accounts import views # from accounts import views urlpatterns = [ url(r'^$',views.home), url(r'^login/$', LoginView, {'template_name': 'accounts/login.html'}), url(r'^logout/$', LogoutView, {'template_name': 'accounts/logout.html'}), url(r'^register/$',views.register, name ='register'), url(r'^profile/$',views.view_profile, name ='view_profile'), url(r'^profile/edit/$',views.edit_profile , name ='edit profile'), ] and also my views file from django.contrib.auth.views import PasswordChangeDoneView from django.shortcuts import render,redirect from accounts.forms import NewUserForm from django.contrib.auth.models import User from django.contrib.auth.forms import PasswordChangeForm, UserChangeForm def home(request): numbers = [1,2,3,4,5] name = 'max' args = {'myName': name,'numbers':numbers} return render(request, 'accounts/home.html',args) def register(request): if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): form.save() return redirect('/account') else: form = NewUserForm() args = {'form':form} return render(request,'accounts/reg_form.html',args) def view_profile(request): args ={'user':request.user} return render(request,'accounts/profile.html',args) def edit_profile(request): … -
How to return ajax response as well as redirection in the views.py Django
I am trying to response the ajax when it successfully gets login but on the other hand, I want to check based on what user profile, it will redirect to the profile. Following is my function in views.py @csrf_exempt def login_view(request): next = request.GET.get('next') email = request.POST.get("email") password = request.POST.get("password") user = authenticate(username=email, password=password) if user is not None and user.is_active: login(request,user) if user.is_male: return redirect('/male_profile') elif user.is_female: return redirect('/female_profile') elif user.is_other: return redirect('/other_profile') data_json = {"error" : False, "errorMessage" : "Login Successful!"} return JsonResponse(data_json, safe=False) else: data_json={"error":True,"errorMessage":"Username or password is incorrect!"} return JsonResponse(data_json,safe=False) What the problem I am facing is it only return Ajax response or redirect to user based profile.. but not both together. Can anyone please help me out with how can I first send the response to ajax and then I redirect it to another page in views.py based on user profile. Thanks. -
How to mask IP address during verification email in Django-Rest-Framework backend?
I am building an application with Django-Rest-Framework as my backend and React-Native as front-end. When a user registers an activation email is generated which is something of this sort http://192.168.0.109:8000/api/auth/register/account-confirm-email/MTU:1mmAOY:3c3emcDMtURa4euwcg3a-Iwb3YYh3pdmM4Dme8emwN0/ Which gives out the IP-address of my hosted server. How do I mask this IP address - http://192.168.0.109? -
Connect Android emulator to Django webserver filles when running locally
In Django under my settings.py I have the following set MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' But for some reason my images aren't rendering on my Android Emulator when I look at the request being set I see for the first post on the screen the image url is: pycharm console: >>> serializer.data[0]['images'] PyDev console: starting. OrderedDict([('uuid', '9df1b544-611c-4f31-a4eb-8c48cb183d45'), ('image_url', '/media/images/user_6badb4b8-33ba-4bb9-aa9a-2e3afb359960/9df1b544-611c-4f31-a4eb-8c48cb183d45.jpg'), ('created', '2021-11-03T04:51:51.830285Z')]) Then I run console.log on the React Native side and the url is: React Native Code to set URL: const getImageUrls = () => { console.log(url + images.image_url); return [ { uri: url + images.image_url, }, ]; }; log statement LOG http://10.0.2.2:8000/media/images/user_6badb4b8-33ba-4bb9-aa9a-2e3afb359960/9df1b544-611c-4f31-a4eb-8c48cb183d45.jpg url is just a constant I have on the React Native side. It gets set dynamically depending on what mobile OS is running the emulator if it's Android it'll set to http://10.0.2.2:8000 and if it's IOS it'll set to http://127.0.0.1:8000. Why isn't the image showing up? I checked <project folder>/media/images/user_6badb4b8-33ba-4bb9-aa9a-2e3afb359960/7afbaf6f-67ef-4879-bd61-026cc947933b.jpg and the file I'm trying to render is definitely there. Why is React Native not rendering the image URL? -
how to restrict a user from using application to just one tab, device or windows at a time?
This is how i am doing right now my middleware.py class MySessionMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) if request.user.is_authenticated: user, _ = LoggedInUser.objects.get_or_create(user=request.user) print(user) if not request.session.session_key: request.session.save() prev_session_key = user.session_key if prev_session_key: if prev_session_key != request.session.session_key: return JsonResponse("you already have a active session kindly logout from that", status=400, safe=False) user.session_key = request.session.session_key user.save() return response my models.py class LoggedInUser(models.Model): user = models.OneToOneField(User, related_name='logged_in_user', on_delete =models.CASCADE, null=True, blank=True) session_key = models.CharField(max_length=32, null=True, blank=True) my signals.py @receiver(user_logged_in) def when_user_logs_in(sender, user, request, **kwargs): print('user_logs_signal is called') LoggedInUser.objects.get_or_create(user=kwargs.get('user')) @receiver(user_logged_out) def when_user_logs_out(sender, user, request, **kwargs): print('user logs out signal iscalled') LoggedInUser.objects.get_or_create(user=kwargs.get('user')).delete() my errors my signals are not firing , i am currently testing the application via postman and using token based authentication, they are not firing thats why i am creating object inside middlware While using postman LoggedInUser object session key and request.session session key always comes out to be same my doubts I know when a user signs up from different tab, window a new session key is generated but what are the other scenarios when a new session key is generated . If the issues that i am facing is because i am using postman … -
Overwriting default login template
I'm trying to overwrite the default login template, but I'm getting an error. My apologies. I'm very weak with class based views. views.py from django.contrib.auth.views import LoginView class CustomLoginView(LoginView): #to override the template_name used in LoginView template_name = 'website/login.html' urls.py url(r'^access/login/$', website_views.CustomLoginView, name='auth_login'), When I visit this url, I get the following error: __init__() takes 1 positional argument but 2 were given Traceback C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars -
How do I make a POST request using axios in react?
I am having issues with the axios post request. When I click on the Button, nothing happens. What is supposed to happen is that the data that I enter into the input fields is submitted to the API. However, no redirect or anything happens when I click the Button. I am not sure whether the onClick function in the Button is never being triggered or whether the issue lies with the call of axios and then the useNavigate function. I have tried several different ways of using these function but none worked. It might be a syntactic issue as I am a beginner with react. Any help would be appreciated! Full Code: import axios from 'axios'; import React, { useState } from 'react'; import { Container, Button } from 'react-bootstrap'; import { useNavigate } from 'react-router-dom'; const AddContact = () => { const [first_name, setFirstName] = useState("") const [last_name, setLastName] = useState("") const [mobile_number, setMobileNumber] = useState("") const [home_number, setHomeNumber] = useState("") const [work_number, setWorkNumber] = useState("") const [email_address, setEmailAddress] = useState("") const history = useNavigate(); const AddContactInfo = async () => { let formField = new FormData(); formField.append('first_name', first_name) formField.append('last_name', last_name) formField.append('mobile_number', mobile_number) formField.append('home_number', home_number) formField.append('work_number', work_number) formField.append('email_address', email_address) …