Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
concatenating string variables to obtain value
How would I concatenate these two string variables in Django templates? At the moment question.correct_answer is the position the correct answer should be (so if there were 4 potential answers and the first answer was correct, question.correct_answer would return 1 instead of the value the answer holds. I have tried the below code, but it shows a string of 'question.answer_1' <h5 class="homework_desc"> {{ question.answer_4 }}</h5> <br> <h4 class="homework_correct hidden" id="{{question.id}}"> {{'question.answer_'|add:question.correct_answer}} </h4> -
What code should we write in "Templates" to display "zhanr" (in Post model)?
I want create a blog application and write in "templates/blog/detail.html": <a href='#'>{{ post.zhanr.genre }}</a> but it doesn't show in browser, i don't know why. you sure about "Mozu in model", I added information about "genre" in database. my model: in Post model i use ManyToManyField for Mozu model from django.db import models class Mozu(models.Model): genre = models.CharField(max_length=250, help_text='نوشتن موضوع') def __str__(self): return self.genre class Aks(models.Model): img = models.ImageField() class Post(models.Model): title = models.CharField(max_length=250) zhanr = models.ManyToManyField(Mozu, help_text='موضوع انتخب کنید') image = models.ManyToManyField(Aks ,null=True, blank= True) video = models.FileField(null=True, blank= True) desc = models.TextField() date = models.DateTimeField() how_time = models.IntegerField(null=True, blank= True) def __str__(self): return '{}-{}'.format(self.title, self.date) my view: i want using Zanr in detail.html from django.shortcuts import render, get_object_or_404 from .models import * from django.views import generic from django.contrib.auth.decorators import login_required, user_passes_test class IndexView(generic.ListView): template_name = 'blog/index.html' context_object_name = 'posts' def get_queryset(self): return Post.objects.all().order_by('date') class DetailView(generic.DetailView): model = Post template_name = 'blog/detail.html' -
django form queryset for image URL
I have a form that links an image model to another model. I'm trying to preview the images in the form, not like the default dropdowns menu, but I'm struggling with the image URL. I tried image.urlbut it's not working my models.py class Images(models.Model): image = models.ImageField(unique=False,upload_to='images/') def get_absolute_url(self): return reverse("image_detail",kwargs={'pk':pk}) #connect days and images together class DayImage(models.Model): date = models.ForeignKey('luach.MyDate',related_name='day',on_delete=models.CASCADE) images = models.ForeignKey('luach.Images',related_name='images',on_delete=models.CASCADE) def get_absolute_url(self): return reverse("dayimage_detail",kwargs={'pk':self.pk}) my forms.py class DayImageForm(forms.ModelForm): class Meta: model = DayImage fields = ('images',) my views.py def create_day_image_view(request,pk): date = get_object_or_404(MyDate,pk=pk) if request.method == 'POST': form = DayImageForm(request.POST) if form.is_valid(): dayimage = form.save(commit=False) dayimage.date = date dayimage.save() return redirect('date_detail',pk=date.pk) else: form = DayImageForm() context = {'form': form,'date': date,} return render(request,'luach/dayimage_form.html',context=context) my dayimage_form.html <form method="POST"> {% csrf_token %} <select class="image-picker"> {% for image in form.images %} <option data-img-src="{{image.value.images.image.url}}" value="{{forloop.counter}}">{{image.label}}</option> {% endfor %} </select> <button type='submit' class='btn btn-success'>save</button> <a class="btn btn-danger" href="{% url 'date_detail' pk=date.pk %}">cancel</a> </form> -
Model inheritance many to one, and return view to template
Struggling again. I would like to apply model inheritance to a template. I have 2 models. Customerprofile and Customerquote. I would like the customerquote to inherit the data records from customerprofile. The model has done this in the backend setup as the models below. The issue is I have 3 seperate fields in the customerquote template for title, firstname and surname with fields. Title, firstname and surname. I would like that I setup a dropdown in the customerquote that when I select firstname all the firstname records appear in the dropdown, when I select the firstname option, Surname and title fields are automatically populated based on inheritance of customerquote and the associated record linked to address 1, is this possible. I have included the template setup below, which in it's basic form is not working even for firstname, before looking at the next steps/ Please see curent setup, is their a way that I can do this and save to new model customerquote, the new instance? Create your models here. class Customerprofile(models.Model): Title = models.CharField(max_length=5, blank=True) Firstname = models.CharField(max_length=100, blank=True) Surname = models.CharField(max_length=100, blank=True) Mobile = models.CharField(max_length=11, validators=[int_list_validator(sep=''), default='12345678901') Email = models.EmailField(max_length=100, blank=True) Datecreated = models.DateField(default=now) Profilefield = models.IntegerField(default="12345678", blank=True) … -
Django rest Framework - Custom Json Response
i'm new into Python and Django Rest Framework. I'm trying to return a "custom" json response but i can't figure it out how to achieve the result i want. I'm building an Ecommerce api where i have "boxes" with "products", this BoxProduct model was created because i need a relation between Products and Boxes, but the same product can be in different boxes, ex: Product.id=1 is in box_id=2 and box_id=4. That's why i created this middle model. BoxProduct Model class BoxProduct(models.Model): product = models.ForeignKey(Product, on_delete=models.DO_NOTHING, null=True, related_name='box_product') box = models.ForeignKey(Box, on_delete=models.DO_NOTHING, null=True, related_name='box_box') product_price = models.DecimalField(max_digits=8, decimal_places=0, null=True, blank=True) I tried to link the serializers of Product and Box but i didn't get wat i want. BoxProduct Serializer class BoxProductSerializer(serializers.ModelSerializer): product = ProductSerializer(many=True, read_only=True) box = BoxSerializer() class Meta: model = BoxProduct fields=['box', 'product'] The idea is to have a returned json like this: { "box_id": 232323, "box_name": "Box name Test", "products": [ { "name": "product name 1", "type": "product_type" }, { "name": "product name 2", "type": "product_type" }, { "name": "product name 3", "type": "product_type" } ] } What would be the best approach to do this? Thanks for your help! -
hi i am getting "CSRF Failed and CSRF cookie not set." error
{"detail": "CSRF Failed: CSRF cookie not set."} error in postman , i am using django rest_framework for developing ios android backend . when i first time clear all cookies and use my login api is working fine this will give me all info about user as per my code but after that when i try to hit any api using post method its always give crsf failed. i also use csrf_exempt decorator in view and urls.py and also tried CsrfExemptMixin from brace package. my login code is from django.contrib.auth import login,logout from django.shortcuts import render,redirect # local py files from .models import * from .serializers import * from app_apis.models import * # third party from rest_framework import (generics, permissions) from knox.views import LoginView as KnoxLoginView from rest_framework.response import Response from rest_framework.authtoken.serializers import AuthTokenSerializer from knox.models import AuthToken from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator from braces.views import CsrfExemptMixin from django.middleware.csrf import get_token # Register API class RegisterView(CsrfExemptMixin,generics.GenericAPIView): serializer_class=RegisterUserSerializer @method_decorator(csrf_exempt) def post(self,request,*args, **kwargs): serializer=self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() print logout(request) return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) class LoginAPI(CsrfExemptMixin,KnoxLoginView): permission_classes = (permissions.AllowAny,) def get(self,request): example={ "username":"user_name", "password":"Your Password" } return Response(example) @method_decorator(csrf_exempt) def post(self, request, format=None): serializer = AuthTokenSerializer(data=request.data) … -
How to customize Image Chooser in Wagtail?
How do I customize the Image Chooser in Wagtail? I need to block the user from having the ability to upload GIFs > ~1 MB in size. Uploading a 3 MB GIF crashes the server right now, and even a 1.5 MB GIF timed out on production. I'm using wand and ImageMagick for the GIFs, I altered the disk quota for ImageMagick but it's not a viable solution on the server, the compression takes forever. So my next step is to totally block large GIFs from being uploaded. I want to set a limit of about 1 MB for GIFs. I don't want to fork the Wagtail framework to do this. Are there any alternative suggestions to get around this GIF problem? -
Django model inline with multiple FK's for both keys to the same model under one inline
I have a situation where I have a model related by two possible foreign keys to another, and I would like to display using a single inline, all the related model fields including both possible FK's. In the example below I have the models of an account and a transaction. All transactions are credit/debit pairs, which indicate the source and destination account using the two FK's, credited_account, and debited_account. class Account(models.Model): owner = models.ForeignKey(User) account_type = models.ForeignKey(AccountType) class Transaction(models.Model): created = models.DateTimeField(auto_now_add=True) amount = models.PositiveIntegerField() credited_account = models.ForeignKey(Account, related_name='credit_transactions', on_delete=models.PROTECT) debited_account = models.ForeignKey(Account, related_name='debit_transactions', on_delete=models.PROTECT) In the AccountAdmin I would like to display all the transactions where the account is either credited or debited, using a single Inline, under a single Transactions header. I know, as per the docs, that I am able to specify them independently by indicating the foreign key and using two different inlines, like so: class DebitInline(admin.TabularInline): model = Transaction fk_name = 'debited_account' class CreditInline(admin.TabularInline): model = LedgerTransaction fk_name = 'credited_account' class AccountAdmin(admin.ModelAdmin): inlines = [CreditInline, DebitInline] The problem I'm having here is that the credit and debit transactions are separated under two different inlines, of the same header, and I would like them ordered by … -
Django Form Fields not Displaying
So I am trying to basically have a check box on an image page which lets me set a boolean field true/false if I want this image to be deemed the "profile image." The problem is that the form field options are not showing up in the template. Any suggestions? single_image.html <form method='POST' action="{% url 'set_profile_image' plant_pk=plnt.pk image_pk=img.pk %}"> {% csrf_token %} <hr> {{ form.as_p }} <hr> <input type="submit" value="Submit"> forms.py class SetProfileImageForm(forms.ModelForm): """A form to set profile image.""" image_main = forms.BooleanField(required=True) class Meta: model = Image fields = ["image_main","image_url",] views.py def set_profile_image(request, plant_pk, image_pk): """A custom view function to set profile image.""" # find the plant for whom we are setting the image plant = Plant.objects.get(pk=plant_pk) if request.method == 'POST': if "cancel" in request.POST: return redirect('display_plant', pk=plant.pk) form = SetProfileImageForm(request.POST or None, request.FILES or None) if form.is_valid(): plant.set_profile_image(image_pk) return redirect('display_plant', pk=plant.pk) else: print("Error: the form was not valid.") else: return reverse('gallery', kwargs={'pk':plant.pk}) -
django only listening at 127.0.0.1
No matter what ip I put in it always listens on 127.0.0.1 This is what I enter to start django python manage.py runserver 0.0.0.0:8000 I am running it on windows WSL ( windows subsystem for linux ) ,this is my first time doing so . Now the wierd part : If I remove '127.0.0.1' from 'allowed_host' in settings it won't start and will ask me to put '127.0.0.1' in 'allowed_host'. The starting message is Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). October 15, 2020 - 16:18:59 Django version 3.1.2, using settings 'document_manager.settings' Starting development server at http://0.0.0.0:8000/ however when I make any request to http://0.0.0.0:8000/ it dosen't work ,but if I make a request on 127.0.0.1 it works . -
URL Based Language Setting Instead of Browser Language Preferences
I am trying to have both Persian (RTL) and the English version of the website in separate URLs like: www.domain.com/en-us www.domain.com/fa-ir This is the first time I am doing this. Therefore, I am kind of confused about that. What I actually did was getting help from this tutorial: https://monicalent.com/blog/2014/08/10/internationalization-with-django-backbone-underscore-template-and-sass-ltr-and-rtl-language Yet, I have no idea how should I make separate URLs for each language. Settings.py: USE_I18N = True USE_L10N = True USE_TZ = True LOCAL_PATHS = ( '/locale/' ) LANGUAGE_CODE = 'en-us' LANGUAGES = ( ('en-us', 'English'), # You need to include your LANGUAGE_CODE language ('fa-ir', 'Farsi') ) Views.py of my home app: from django.shortcuts import render # Create your views here. def home(request): if hasattr(request.user, 'lang'): request.session['django_language'] = request.user.lang return render(request, 'index.html') Urls.py : from django.contrib import admin from django.urls import path import home.views urlpatterns = [ path('admin/', admin.site.urls), path('', home.views.home, name='index') ] index.html: {% load i18n %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Kilka Shafagh</title> </head> <body> <span>{% trans "Test" %}</span> </body> </html> However, Even when I set language preferences to persian, the translation does not occur. I would be grateful if anyone guide me through this as the related topics on stackoverflow could … -
Running a JS module in a Django project
I am a beginner and would like to use this Javascript module (meant for Node) in my Django project in which I'm using Django's template system for the front-end: https://github.com/jshemas/openGraphScraper What is the best way to do this? Do I have to run Node alongside Django separately? -
unable to deserialize self referential foreign key with custom serializer
I am using django and django-rest-framework to create APIs I have a model like this class Version(models.Model): version_tag = models.IntegerField(verbose_name=_("Version")) data = models.TextField(verbose_name=_("Data")) cloned_from = models.ForeignKey( "self", on_delete=models.SET_NULL, null=True, blank=True ) endpoint = models.ForeignKey( ManagedEndpoint, verbose_name=_("Endpoint"), related_name="versions", related_query_name="version", on_delete=models.CASCADE, ) and a serializer like this class VersionSerializer(serializers.ModelSerializer): data = serializers.JSONField() version_tag = serializers.IntegerField(required=False) cloned_from = ClonedFromSerializer(required=False) resource_purpose = serializers.CharField( source="endpoint.resource_purpose", required=False ) class Meta: model = models.Version fields = [ "resource_purpose", "version_tag", "data", "cloned_from" ] and i have custom serializer ClonedFromSerializer like this class ClonedFromSerializer(serializers.Field): def to_representation(self, value): if value.endpoint is None: return "" return "%s : %s" % (value.endpoint.resource_purpose, value.version_tag) def to_internal_value(self, data): resource_purpose, version_tag = data.split(":") try: endpoint = models.ManagedEndpoint.objects.get( resource_purpose=resource_purpose.strip() ) return models.Version.objects.get( endpoint=endpoint, version_tag=version_tag.strip() ) except models.ManagedEndpoint.DoesNotExist: raise serializers.ValidationError( "invalid clone_from value passed" ) What I wanted to do is, cloned_from should output a string with resource_purpose and version_tag which is working correctly. What is not working is that when I make a post call i.e. when i want to create a new version with cloned_from is passed as a string, it is creating with clone_from=None. I don't have a clue why it is still None when am returning Version object. can anyone help ? -
How to show the total count of online users in the template (django)?
This is my user model- class CustomUser(AbstractUser): user_id = models.UUIDField(default=uuid.uuid4,editable=False,primary_key=True) username = models.CharField(max_length = 100,unique = True) friends = models.ManyToManyField('CustomUser',related_name="friend", blank= True) user_last_seen = models.DateTimeField(auto_now_add=False) I am able to track the time when a user was last seen (whether they log out or not) using the following middleware: class ActiveUserMiddleware(MiddlewareMixin): def process_request(self, request): current_user = request.user if request.user.is_authenticated: now = datetime.datetime.now() current_user.user_last_seen = now current_user.save(update_fields=['user_last_seen']) And also able to show in my template that whether they are active at the current moment, or when they were last seen - {%if i.user_last_seen|timesince|upto:',' < "1 minutes" %} <td style="font-size:small; color:green;text-align:right;"> Active Now </td> {%else%} <td style="font-size:small; color:gray;text-align:right;"> {{i.user_last_seen|timesince|upto:','}} ago </td> {%endif%} Along with this, I want to show the total number of users that are active right now. But I am having a hard time to understand how to do that exactly. I am still a beginner when it comes to Django, any suggestions or ideas would be really helpful. -
Django postgres connection, SET timezone for psycopg2
In django settings.py I have TIME_ZONE = 'Asia/Tbilisi' I have same timezone for postgres also and separately, both works correctly. Though, in Django, when I run raw queries like: from django.db import connection ... cursor = connection.cursor() cursor.execute("select localtimestamp(0)") res = cursor.fetchall() This shows datetime with UTC time zone. Probably this is caused by psycopg2 connection settings? because this: print( connection.cursor().connection.get_parameter_status("TimeZone") ) shows: UTC. Question: How can I change this connection settings and SET needed timezone? -
Django hosting raw HTML files behind authentication
I inherited an NGINX/Gunicorn/Django (1.11) server. I've only been poking around with Django for a little while. We have a piece of software that not everyone has a license for. It can dump out its data in a series of linked HTML files: index.html models/model_a.html models/model_b.html models/model_b/model_1.html models/model_b/model_2.html And so on. They're all linked together and navigable from the top-most file, index.html. I created a menu button and I linked it to a location where the HTML model is stored. Users can navigate to it and browse around, exactly as expected. Here's my problem. We're using SAML authentication. To use the menu button in Django, you obviously have to be logged in. But once you are sent to the link, you can reuse it forever. A user can send out the URL and and anyone using the link will bypass logging in completely. The URL would look like this: https://example.com/models/model_b/model_1.html Again, anyone with that URL can get to the information. I want to ensure anyone trying to access that HTML render of the software's model has to authenticate first. Any ideas? (Sorry if it's a basic question. I'm new at this and I'm not very smart in general. So there's … -
Email Verification django rest framework
I am creating an api using Django Rest Framework, when user signs up (registers) for an account, the user receives a verification email, with a verification link, once clicked the account should be verified. I got the email sending part working and configured. My question is: How to have the link in the verify-email endpoint activate account when user clicks on it (decode payload) ? I cannot seem to find what I am looking for over the internet, I browsed the DRF documentation, but could not find it. I am using Django Token Authentication for authentication, that ships with Django rest. Your inputs are much appreciated. Thank you. -
How to generate slug according to title of post in django?
Well i dont want to work with id of post in my urls so i want to generate slug according to to post title and that can be same. so i dont understand how can i do that can you guys tell me it can be done, my model post is given below. model.py class Post(models.Model): username = models.ForeignKey(UserProfile, on_delete=models.CASCADE) description = models.CharField(('Description'),max_length=250) title = models.CharField(('Content Title'), max_length=250) create_date = models.DateTimeField(default = timezone.now) image_data = models.ImageField(upload_to='User_Posts', height_field=None, width_field=None, max_length=None) slug = (title) def __str__(self): return self.title -
How do I get the API Key message to go away TinyMCE? (Django)
I've included the TinyMCE editor into my program and it's showing up, but says I need to add a API key. I've tried doing this but can't figure out where: {% extends "blog/base.html" %} {% load crispy_forms_tags %} <head> <script src="https://cdn.tiny.cloud/1/<KEY>/tinymce/4/tinymce.min.js" referrerpolicy="origin"></script> </head> {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} {{ form.media }} <fieldset class="form-group" id = #mytextarea> <legend class="border-bottom mb-4">Add Law</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Finish</button> </div> </form> </div> {% endblock content %} This is my form.html template. Here is my settings.py: TINYMCE_DEFAULT_CONFIG = { 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'silver', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak ''', 'toolbar1': ''' fullscreen preview bold italic underline | fontselect, fontsizeselect | forecolor backcolor | alignleft alignright | aligncenter alignjustify | indent outdent | bullist numlist table | | link image media | codesample | ''', 'toolbar2': ''' visualblocks visualchars | charmap hr pagebreak nonbreaking anchor | code | ''', 'contextmenu': 'formats | link image', 'menubar': True, 'statusbar': True, } TINYMCE_JS_URL = 'https://cdn.tiny.cloud/1/<KEY>/tinymce/5/tinymce.min.js' and finally my … -
For loop in Django doesnt show up the result from database
i have a problem with for loop. First i have this views.py: from django.shortcuts import render from .models import * def store(request): products = Product.objects.all() context = {'products':products} return render(request, 'store/store.html') As you see from the .models i am importing everything (*), but in particular i am interested in class Product (code from models.py): class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() digital = models.BooleanField(default=False, null=True, blank=False) def __str__(self): return self.name Then in Django admin http://127.0.0.1:8000/admin i have created several products: So i have the model, products in database and view. Finally in my template store.html i have for loop: {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row"> {% for product in products %} <div class="col-lg-4"> <img src="{% static 'img/placeholder.png' %}" alt="" class="thumbnail"> <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <button class="btn btn-outline-secondary add-btn">Add to Cart</button> <a class="btn btn-outline-success" href="#">View</a> <h4 style="display: inline-block; float: right"><strong>${{product.price|floatformat:2}}</strong></h4> </div> </div> {% endfor %} </div> {% endblock content %} But it doesnt show the products from the database: If i delete in store.html a for loop: {% for product in products %} and {% endfor %} Then the plain html displays. Any clue why the for loop doesnt work please? … -
Python create_user Object of type 'set' is not JSON serializable
I have this code: class usuario(APIView): def post(self, request): try: data = json.dumps(request.data) #usuario = UserSerializer(data = request.data) #print(usuario) #if usuario.is_valid(): # print(usuario.data) #print("'"+str(data['email'])+"'") #firebase_admin.initialize_app() user = auth.create_user( email='user@example.com', email_verified=False, phone_number='+15555550100', password='secretPassword', display_name='John Doe', photo_url='http://www.example.com/12345678/photo.png', disabled=False) print('Sucessfully created new user: {0}'.format(user.uid)) return JsonResponse({"user": 'teste}'}, status=status.HTTP_201_CREATED) except Exception as ex: print(ex) return JsonResponse({"Ocorreu um erro no servidor"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR, safe=False) When I try to do a post request with postman, it returns: Object of type 'set' is not JSON serializable line 37, in post Line 37 is: disabled=False) -
Django Rest frame work error get() returned more than one Customer_Notes -- it returned 3
I am using react app to fetch data from a django rest api. The issue here is there are multiple notes added for one single user and when I am trying to make a get request it is throwing the above error. It is allowing me to only fetch one single row when i specify the lookup field to be pk. However I want to return all the objects. class Customer_NotesViewSet(viewsets.ModelViewSet): queryset = Customer_Notes.objects.all() serializer_class = serializers.Customer_NotesSerializer lookup_field = 'customer' class Customer_NotesSerializer(serializers.ModelSerializer): class Meta: model = Customer_Notes fields = "__all__" What changes or work around can be done here ? -
ProgrammingError at /accounts/facebook/login/token/
I'm having trouble setting up the facebook login in django. Whenever I click the facebook log-in link it tells me this: ProgrammingError at /accounts/facebook/login/token/ (1146, "Table 'user$db.account_emailaddress' doesn't exist") I followed the set up recommended here. From what the error message says I suspect it is related to the migrations in my database. The Traceback leads me to /allauth/account/utils.py where I can the see the problem is the use of EmailAddress.objects.filter(). In fact, when I go in the shell and try: from allauth.account.models import EmailAddress I can import EmailAddress successfully. It's only when I try to use EmailAddress.objects.all() that I get the same 1146 error. I tried to redo all migrations related to allauth but my database still never shows any table related to allauth or account. Here are the details of my settings.py file: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'social_django.context_processors.login_redirect', 'django.template.context_processors.request', ], }, }, ] INSTALLED_APPS = [ 'django.contrib.admin.apps.SimpleAdminConfig', 'django.contrib.auth', 'django.contrib.messages', 'django.contrib.sites', 'social_django', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'custom_user.apps.CustomUserConfig', 'user_profile', 'django_email_verification', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] SITE_ID = 1 and urls.py: urlpatterns = [ path('accounts/',include('allauth.urls')), path('request-reset-email', RequestResetEmailView.as_view(), name='request-reset-email'), ] Thanks everybody for your help. -
Django redirect interfering with stat files loading
I am having a Django app where users search for files that are generated as reports (edited html creating reports Impression) . On the front-end,the search form makes a Get action '/search/q=someValue' However,the query url needs to be replaced and so I updated my views.py such that Def search_view(request): //Validate the query is valid //Redirect to some_new_url Def some_new_url(request): //Now use this view for search When i carry out a search, static files are not applying but if i navigate using internal links referencing the same url(some_new_url) everything works okay.What could be the issue -
Counting specific field of deeply nested Object django
I have a model Category and it has children and also the Product model looks like this class Category(models.Model): name = models.CharField(max_length=200) category = models.ForeignKey(Category, related_name='children') product_count = models.IntegerField(null=True) class Product(models.Model): category = models.ForeignKey(Category) sub_category = models.ForeignKey(Category, related_name='sub_category_products') name = models.CharField(max_length=300) price = models.DecimalField() and I need to count all products belong to the specified category it can be in the subcategory of the category. The Category model can be deeply nested. How can I do this query! Any would be appreciated. Thanks in advance!