Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to paginate/search/filter objects simultaneously. Query parameters [Django]
I have 3 different forms in my html template: to filter, search and paginate results. I want there to be an option to do that simultaneously: shop/?filter_by=diary_products&paginate_by=6 shop/search/?q=milk&filter_by=diary_products&paginate_by=6 The problem is when form is been submitted. Query parameters does not append, so i cannot reach the above mentioned result. Search form <form action="{% url 'search_products' %}" method="GET"> {% csrf_token %} <button type="submit">Search</button> <input type="text" name="q" placeholder="Search"> </form> Select form to choose items per page (pagination) <form action="{% what should i put here? %}" method="GET"> <select name="paginate_by" onchange="this.form.submit()"> <option selected>1</option> <option>2</option> <option>3</option> </select> <noscript><input type="submit" value="Submit"></noscript> </form> Filter form <form action="{% what should i put here? %}" method="GET"> <select name="filter_by" onchange="this.form.submit()"> <option selected>diary_products</option> <option>by_price</option> <option>newest_first</option> </select> <noscript><input type="submit" value="Submit"></noscript> </form> urls.py from django.conf import settings from django.conf.urls.static import static from django.urls import path from . import views urlpatterns = [ path('', views.shop, name='shop'), path('search/', views.search_products, name='search_products'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Jquery plugin for fixed column with django formset
Did any one use any jquery plugin for fixed columns with Django formset. The django formset is normal table that have events to create or delete row. I have try with css sticky property but it doesn't work. The DataTables fixedColumn is not suitable for django formset table. You can look her for more inforamtion about the django formset blugin. -
django specify column arrangement in SQL Server
I am using Django ORM to create my database tables and perform the rest of the operations. However, I've noticed that the columns if I see in the database are not in the order I specify in the django models. For example, my model is class ItemMetaData(models.Model): item = models.ForeignKey(Item, on_delete=CASCADE) field = models.CharField(max_length=80) field_value = models.CharField(max_length=80) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) But in the database when I see the table, the foreign key is the last column so it looks like id | field | field_value | created_at | modified_at | item_id I would like my item_id to be the first column after id . Like this: id | item_id | field | field_value | created_at | modified_at Is this possible? I tried to search but when I look for ordering all the answers assume it's row ordering and suggest using order_by -
How to send some value if unchecked for each checkbox with same name?
Here I have multiple checkbox with same name. Checkbox can be added to n no. of times. Here if already checked I want to send 1 and if not 0. Right now in my django backend I am getting the list like this. If all checked [1, 1, 1] which is fine . if only one checked [1] but I want like this [1, 0, 0] <input name="need_a" type="checkbox" class="custom-control-input" value="1" {% if some_condition %}checked{% endif %}/> <input name="need_a" type="checkbox" class="custom-control-input " value="1" {% if some_condition %}checked{% endif %}/> <input name="need_a" type="checkbox" class="custom-control-input" value="1" {% if some_condition %}checked{% endif %}/> -
Can I test celery with mock.patch('django.utils.timezone.now', mock.Mock(return_value=mocked))?
I have celery task that create new Alert objects after 3 days from the POST action, and I want to test that. I create a test that assert assert Alert.boject.count() == 0 right now and it assert that the alert will be 1 after 3 days. But, the alerts returns 0 instead of 1 My code is so complicated and long so it is not practical idea to share it Goal I just need to know if the mock.patch actually work on celery countdown functions. res = self.client.post('/alerts/rules/', data) self.assertEqual(res.status_code, status.HTTP_201_CREATED) i = now + delta_time(3,'days') mocked = datetime.datetime(2021, 4, i, 0, 0, 0, tzinfo=pytz.utc) assert Alert.boject.count() == 0 with mock.patch('django.utils.timezone.now', mock.Mock(return_value=mocked)): assert Alert.bojects.count() == 1 -
UnitTest for Django Inline Formset
I have a formset with custom validation logic: forms.py class MyFormSet(BaseInlineFormSet): def clean(self): super().clean() forms = list(filter(lambda form: len(form.cleaned_data), self.forms)) if not forms or any(self.errors): return for form in forms: ... And I use this custom formset in admin-site models: admin.py class MyInline(admin.TabularInline): formset = MyFormSet model = ClientAgreement class ClientAdmin(admin.ModelAdmin): form = Client inlines = [ MyInline ] So what I want to do now - test my custom clean logic in unit test. Inside the test I create formset with: formset = inlineformset_factory(Client, ClientAgreement, formset=MyInlineFormSet, fields='all') After that I create instance with my object: object_formset = formset(instance=client1) Now I can see all prepopulated test data inside object_formset according to ClientAdmin model. But how can I pass changes to forms data to check my clean logic? Or maybe there is different path to solve this? -
ValueError: too many values to unpack (expected 2) Django
Not sure why but my code is getting the following error: ValueError: too many values to unpack (expected 2) Here is my models.py: class UserList(models.Model): list_name = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.list_name Here is my views.py def otherUserList(request): userName = request.GET.get('userName', None) print(userName) qs = UserList.objects.filter(user__username=userName) return qs Here is the traceback: Internal Server Error: /electra/otheruserlist/ Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/deprecation.py", line 116, in __call__ response = self.process_response(request, response) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/middleware/clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 418, in get clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 942, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 962, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 969, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1358, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1377, in _add_q child_clause, needed_inner = self.build_filter( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1255, in build_filter arg, value = filter_expr ValueError: too many values to unpack (expected 2) [02/Sep/2021 05:38:43] "GET /electra/otheruserlist/?userName=alice HTTP/1.1" 500 94227 I'd be very grateful for any assistance. -
Django Send email for new model object create
I want to send email if user placed a new order. I want to do the send email function from my models.py. Is it possible?? I setup my settings.py for email. I am looking for a easiest way to do this. I don't want to touch my views so is it possible? #this is my Order model class Order(models.Model): PENDING_PAYMENT = 'Pending Payment' ON_HOLD = 'On Hold' status_choices = [ ('Cancel', 'Cancel'), ('Pending Payment', 'Pending Payment'), ('On Hold', 'On Hold'), ('Waiting For Payment', 'Waiting For Payment'), ('Processing', 'Processing'), ('Done', 'Done'), ] orderstatus_choices = [ ('Cancel', 'Cancel'), ('Pending Payment', 'Pending Payment'), ('On Hold', 'On Hold'), ('Waiting For Payment', 'Waiting For Payment'), ('Processing', 'Processing'), ('Done', 'Done'), ] Ordinary = 'Ordinary' customer_choices = [ ('Ordinary', 'Ordinary'), ('Police', 'Police'), ('RAB', 'RAB'), ('DGIF', 'DGIF'), ('CID', 'CID'), ('NAVY', 'NAVY'), ('Air Force', 'Air Force'), ('Army', 'Army'), ('DB', 'DB'), ('Administration', 'Administration'), ] user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) paymentMethod = models.CharField(max_length=200, null=True, blank=True) taxPrice = models.DecimalField(max_digits=11, decimal_places=2, null=True, blank=True) shippingPrice = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) totalPrice = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True) isPaid = models.BooleanField(default=False) paidAt = models.DateTimeField(auto_now_add=False, null=True, blank=True) isDelivered = models.BooleanField(default=False) deliverAt = models.DateTimeField(auto_now_add=False, null=True, blank=True) createdAt = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=220, choices=status_choices, default=PENDING_PAYMENT) orderStatus= models.CharField(max_length=220, choices=orderstatus_choices, default=ON_HOLD, … -
UsZipCode --> Input -> (zipcode, radius) output -> (List of Zipcodes)
This is what I have tried from this search = SearchEngine() search.query(zipcode="74104", radius="30", returns=5) this returns [SimpleZipcode(zipcode='74104', zipcode_type='Standard', major_city='Tulsa', post_office_city='Tulsa, OK', common_city_list=['Tulsa'], county='Tulsa County', state='OK', lat=36.15, lng=-95.96, timezone='Central', radius_in_miles=1.0, area_code_list=['918'], population=12724, population_density=4673.0, land_area_in_sqmi=2.72, water_area_in_sqmi=0.0, housing_units=6606, occupied_housing_units=5794, median_home_value=136200, median_household_income=36848, bounds_west=-95.970417, bounds_east=-95.940281, bounds_north=36.160214, bounds_south=36.13323)] If I specify radius as an int search = SearchEngine() search.query(zipcode="74104", radius=30, returns=5) I get You can either specify all of lat, lng, radius or none of them Not sure what I am doing wrong -
OSError: cannot load library 'gobject-2.0-0'
I am currently implementing code that can print my database outputs to a pdf file. The following error (Title) is given when I do 'manage.py runserver' I have just installed weasyprint and imported HTML from it in the top of my views file , as per the below: Views.py: from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse import pyodbc from django.http import FileResponse from django.contrib import messages from django.views import View from django.template.loader import render_to_string from weasyprint import HTML import tempfile from django.db.models import Sum def home(request): return render(request , 'main/home.html') def Kyletrb(request): all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] '\ 'Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink = PostGL.AccountLink '\ 'Inner JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType' cursor = cnxn.cursor(); cursor.execute(all); xAll = cursor.fetchall() cursor.close() xAll_l = [] for row in xAll: rdict = {} rdict["Description"] = row[0] rdict["Account"] = row[1] rdict["Credit"] = row[2] rdict["Debit"] = row[3] xAll_l.append(rdict) return render(request , 'main/Kyletrb.html' , {"xAlls":xAll_l}) def printToPdf(request): response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalance' + \ str(datetime.datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] '\ 'Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink … -
django - How to display a form in a modal window?
On the details page of a particular object (in my case, 'TrimType'), I want to display the create form when I press the 'Create' button, and the update form when I press the 'Update' button in one modal window. Does it need multiple url/view for the modal window that displays the Create or Update form? Or is it possible in single url/view? I implemented it in a single url/view, create works well, but it doesn't work as an update function. How do I implement views.py? models.py: class Car(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, null=False, blank=False) class TrimType(models.Model): car = models.ForeignKey(Car, on_delete=models.SET_NULL, blank=True, null=True,) typeName = models.CharField(max_length=50, blank=False, null=False) forms.py: class TrimTypeForm(forms.ModelForm): class Meta: model = TrimType fields = ('car', 'typeName') typeName = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) detail_view.html: <div class="text-right mt-3 mb-3"> <a href="" id="btn_trimtype_add" class="btn btn-primary btn-icon waves-effect waves-themed" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo" title="">add</a> <a href="" id="btn_trimtype_modify" class="btn btn-info btn-icon waves-effect waves-themed" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo" title="">modify</a> </div> {% include 'modal_form.html' %} modal_form.html: <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h3 class="modal-title">TrimType</h3> <form method="post" class="form-horizontal" enctype="multipart/form-data"> {% csrf_token %} <p>{{ form.errors }}</p> <input type="hidden" name="car" value="{{ carID }}"> <div … -
Increment Integer Field only once per post
I am building a Blog App And I am implemented a feature of , When user edit a post then it will add +1 point in the User Profile's Integer Field. Everything is working fine But Integer Field is increasing every time I refresh the page. And I am trying to add only +1 point in it. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') full_name = models.CharField(max_length=30,default='') edited_count = models.IntegerField(default=0) class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30, default='') body = models.CharField(max_length=30, default='') blog_post_edited_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_post_edited_by') views.py def blog_post_detail_view(request,blogpost_id): post = get_object_or_404(BlogPost,id=blogpost_id) post_edited_by = post.blog_post_edited_by if post_edited_by == request.user: request.user.profile.edited_count += 1 request.user.profile.save() context = {'post':post} return render(request, 'blog_post_detail_view.html', context} What have i tried ? I have also tried using Boolean Field if user is awarded +1 point then it will turn to False, But it will create a problem, I mean I am awarding user in every edit But it will only award once every time. I have also tried by awarding +1 point in Edit Form like :- def edit_blogpost(request,blogpost_id): post = BlogPost.objects.get(id=blogpost_id) if request.method != 'POST': form = BlogPostEditForm(request.POST or None, request.FILES or None, instance=post) else: form = BlogPostEditForm( instance=post, data=request.POST, files=request.FILES) if … -
How to write Elasticsearch query in elasticsearch_dsl in python
I am newbie in Python Django and could not get started though I have seen basic documentations at https://www.elastic.co/guide/en/elasticsearch/reference/6.8/query-dsl.html Here is my Elasticsearch query api for aggregation curl -X POST "localhost:9200/my_index/_search?pretty" -H 'Content-Type: application/json' -d' { "aggs": { "imei_count": { "cardinality": { "field": "imei" } } } } ' Explanation of code block is welcome. Thanks -
Call a specific custom migration operation whenever a model is created
I am trying to implement this, http://docs.citusdata.com/en/v10.1/develop/migration_mt_django.html#:~:text=4.%20Distribute%20data,tenant_migrations.Distribute(%27Task%27)%2C%0A%20%20%5D Since I cannot hard code this operation for hundreds of models, I am wondering whether there is a way to automate this "make migration" whenever a model is created and me specifying the "reference" attribute in the model's meta class. Thank you -
Django unit test taking a long time to run
I tried different approaches like python manage.py test --keepdband creating a separate test database. I'm getting an error -: Using existing test database for alias 'default'... Got an error creating the test database: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATE DATABASE IF NOT EXISTS `test_b2b ;\n SET sql_notes = @' at line 2") I'm using MySQL as a database. -
How to add a js without static folder un django
So I have a html template in Django and I want to include it with some js but I don't want my js to be in my static folder and I don't want to let any users in my site view that Javascript by going to any url so it it possible to that in django? -
Django - How to add access token to Client.post in Django test?
So I have some code below. Every endpoint has an authentication process, which is below as well. I want to be able to attach an access token, which is in cls.user to the Client.post so that I can test all the endpoints and ensure they are authenticating properly as well. How can I do this? So ideally I'd be attaching <bearer> <access token> to request.Meta['HTTP_AUTHORIZATION'] test.py import json from cheers.models import * from warrant import Cognito from django.urls import reverse from django.test import TestCase from rest_framework import status from cheers.models import GoalCategory, Post from dummy_factory.Factories import UserFactory, GoalFactory class PostTest(TestCase): @classmethod # Generates Test DB data to persist throughout all tests def setUpTestData(cls) -> None: cls.goal_category = 'health' GoalCategory.objects.create(category=cls.goal_category, emoji_url='url') cls.user = UserFactory() cls.goal = GoalFactory() user_obj = User.objects.get(pk=cls.user.phone_number) goal_obj = Goal.objects.get(pk=cls.goal.uuid) Post.objects.create(creator_id=user_obj, goal_id=goal_obj, body='Some text') cls.user = Cognito(<Some login credentials>) cls.user.authenticate(password=<password>) def test_create(self): response = self.client.post(reverse('post'), data=json.dumps({'creator_id': str(self.user.uuid), 'goal_id': str(self.goal.uuid), 'body': 'Some text #Test'}), content_type='application/json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) Test authenticator function def cognito_authenticator(view_func): def wrapped_view(request, *args, **kwargs): # Check the cognito token from the request. token = request.META['HTTP_AUTHORIZATION'].split(' ')[1] try: jwt.decode_cognito_jwt(token) except Exception: # Fail if invalid return Response("Invalid JWT", status=status.HTTP_401_UNAUTHORIZED) # Or HttpResponseForbidden() else: # Proceed with the view … -
Django ModelChoiceField initial value is not showing up while editting
I have an form "ModelChoiceField" form field, and when adding the data it works fine ! But how to retrieve the saved data database to get selected when the form is edited ? form = AddForm(owner=pk, instance=data, initial={'course': data.course}) I even tried setting initial value, but still am not getting to selected value to get displayed ! class AddForm(ModelForm(: def __init__(self, owner, *args, **kwargs): super(AddForm, self).__init__(*args, **kwargs) self.fields['course'].queryset = Faculty.objects.filter(owner=owner) And note, that the selected values are correctly getting saved on database ! But its not showing up -
Continuous cycling through all objects in a table with django
As a learner of the django framework, I face the challenge of looping through all primary keys of a table, beginning with the first, and at the end of the sequence, to start all over again. The id field is an auto-incrementing serial field in postgres. A very basic breakdown of the project is as follows: models.py ... class Event(models.Model): id = models.BigAutoField(primary_key=True) event_name = models.BigIntegerField(blank=True, null=False) timestamp = models.DateTimeField(blank=True, null=True) viewed = models.BooleanField(default=False) views.py def home(request, id=None): from .models import Event first_obj = Event.objects.order_by('id').first() my_json = serialize('json', first_obj, fields=('event_name', 'timestamp')) return render(request, 'home.html', {'items': my_json}) def confirm(request): #set viewed=True on current object .save() return redirect('home') #move to next object home.html ... <form method="POST" action="{% url 'confirm' %}"> <button>confirm</button> </form> ... The idea is to send the my_json object to an html template. A user clicks a button, which should then mark the current object as viewed (sets viewed from False to True), then the next object should be fetched (by incremental primary key), and so on. If it has reached the last object, the first object (pk=1) should be fetched next, and the cycle continues. I would like to avoid making ajax requests and think a second url would … -
Is it possible to list out a range of values in the database?
Let's say I have a form that has 2 fields, First and Last. For example, the input for First: 1 and Last : 5. Upon saving: It saves the range: 1, 2, 3, 4, 5 and stored under a single field (Num) in a database table called (Numbers), row 1 - 1, row 2 - 2, row 3 - 3, row 4 - 4, row 5 - 5 It saves the First and Last values in a table called Range. Using a view (Django) and somehow uses the numbers of 1 & 5 and derive the range of 1, 2, 3, 4, 5 and stored in another table (Numbers) where under the field (Num), row 1 - 1, row 2 - 2, row 3 - 3, row 4 - 4, row 5 - 5 Which is possible? And how do i do it? Appreciate it for any help provided -
How to use Django rest framework query parameters
I'm trying to create an API with Django and I'm having a hard time understanding how query string parameters work: So far I created an endpoint which gives out a list of products and know I want to be able to filter those products by name like /api/Products/name=guitar or any equivalent of /api/Products?name=guitar I created this view and serializer: serializer_class = ProductSerializer def get_queryset(self): queryset = ProductJoinShop.objects.raw(f'select * from Product join Shop using (id_shop) limit 12') name = self.request.query_params.get('name') if name is not None: queryset = ProductJoinShop.objects.raw(f'select * from Product join Shop using (id_shop) where name like \'%{name}%\' limit 12') return queryset And this is my urls.py: router = routers.DefaultRouter() router.register(r'Products', views.ProductView, 'Products') router.register(r'Products/(?P<name>.+)/$', views.ProductView, 'ProductsSearch') urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)) ] This doesn't crash but for /api/Products/guitar/ I get nothing back. I also tried /api/Products/?name=guitar/ and that throws an error. Thanks! -
django unable to save req body to sqlitedb
I have a nitpicky problem with my Django rest api, I'm using postman to POST in some basic information as raw json then make an instance of the model 'Planet' then store it in the sqlite db that comes with django as standard, I'm getting a 200 response but it is failing the try block for some weird reason?, I have tried changing the param values and also the model data types but it doesn't seem to fix it, there are no errors server side either hoping someone can point out my logic error here :) Model class class Planet(models.Model): name = models.CharField(max_length=20) temp = models.CharField(max_length=20) hrs = models.CharField(max_length=20) mass = models.CharField(max_length=20) diameter = models.CharField(max_length=20) circumference = models.CharField(max_length=20) def add_planet(request): if request.method == 'POST': payload = json.loads(request.body) planet_name = payload['name'] avg_temp = payload['temp'] day_hrs = payload['hrs'] planet_mass = payload['mass'] planet_diameter = payload['diameter'] planet_circumference = payload['circumference'] //data prints out correctly here print(planet_name,avg_temp,day_hrs,planet_mass,planet_diameter,planet_circumference) planet = Planet(name=planet_name,temp=avg_temp,hrs=day_hrs,mass=planet_mass, diameter=planet_diameter, circumference=planet_circumference) try: planet.save() response = json.dumps([{ 'Success': 'Planet added successfully!'}]) except: response = json.dumps([{ 'Error': 'Planet could not be added!'}]) return HttpResponse(response, content_type='text/json') here is my json body being sent in postman, I'm using POST and raw json as my option as I don't have … -
Unable to verify email while using simple JWT in django
The register and login sections are functioning properly in my django application. When someone registers he receives a confirmation email, but on clicking the email confirmation link the account is not verified. I'm using try and except, it's the except that is being executed each time and try never executes. models.py username = models.CharField(max_length=255, unique=True, db_index=True) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) views.py serializer_class = EmailVerificationSerializer def get(self, request): token = request.GET.get('token') try: key = jwt.decode(token, settings.SECRET_KEY) user = User.objects.get(id=key['user_id']) if not user.is_verified: user.is_verified = True user.save() return Response({'email': 'Your email has been activated'}, status=status.HTTP_200_OK) except jwt.exceptions.DecodeError as identifier: return Response({'error': 'token not valid'}, status=status.HTTP_400_BAD_REQUEST) Please I want to know why the the code in the try section never gets executed even when the token is intact and has not expired. -
How to implement only one user session to perform specific task in my django application
I have a application, in that one page has form submit operation which writes a data to data base, I want this submit operation to perform by only one user session at a time, if other user submitted it must show , please wait some user is performing operation like that, please suggest here. -
Can't access django admin anymore
I can no longer access my admin page after the last migration I made. All I did was add a foreign field connecting two models (Listing and User). I am getting the message: “C:... Django\commerce\media\admin” does not exist I did a lot of searching but all I came up with was to delete 'django.contrib.sites', or to add it instead while setting SITE_ID equal to 1. There was also the suggestion to put: from django.contrib.sites.models import Site Site.objects.create(pk=1, domain='localhost', name='localhost') into python shell. None of these things worked for me. For some reason django seems to be searching in my media folder but I have no idea why it would do that. My settings: """ Django settings for commerce project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '6ps8j!crjgrxt34cqbqn7x&b3y%(fny8k8nh21+qa)%ws3fh!q' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True …