Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Framework, front-end, back-end, full stack? Or not to learn a framework?
I have several questions. I am a student and am training in web development. I have practically finished developing my first site which uses HTML, CSS, Javascript, PHP and MySQL. I want to acquire a certain ease in web development, but in theory this will not become my job, nor my daily life. I am about to start a bigger project (several months of development to be expected) because I am starting to be confident and have the capacities of my ambitions (not crazy either). Basically I'm more Python, not web development. So I would like to know if it is important to learn a framework? Especially since not wishing to be professionalized, therefore not specialized in front-end or back-end, I would prefer to solidify myself in full-stack knowledge for the moment. I have heard of Symfony (PHP), Node.js (JS), Bootstap (JS), etc ... But these are specialized front or back frameworks. If I have to learn a framework I would prefer it to be full-stack. And I ask myself the question if Django will not be what I need since it is a Python web framework. But is it good? Is it "full-stack" or just back-end? Isn't it a … -
Django querryset annotate and aggregation
I have a few models for which I am trying to create custom managers and query sets. In this example, I want to get the total paid amount throughout all the orders for each customer. But unfortunately, I will keep getting the wrong values, why?! Here is an example of some of my models: class customer(models.Model): name = models.CharField(max_length=100, blank=False, null=False) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="customer") objects=CustomerManager() #My customer manager class order(models.Model): paid = models.DecimalField(default=0.00, max_digits=30, decimal_places=2) customer = models.ForeignKey(customer, on_delete=models.CASCADE, related_name="order") class order_item(models.Model): quantity = models.PositiveIntegerField(default=0, null=False) price = models.DecimalField(decimal_places=2, max_digits=30, default=0.00) product = models.ForeignKey(product, on_delete=models.CASCADE, related_name="order_item") order = models.ForeignKey(order, on_delete=models.CASCADE, related_name="order_item") Here is my manager: class CustomerManager(models.Manager): def get_queryset(self): return CustomerManagerQuerry(self.model, using=self.db) def get_customer_stats(self): return self.get_queryset().customer_stats() Querryset: class CustomerManagerQuerry(models.QuerySet): def customer_stats(self): table = self.annotate(total_paid=Sum('order__paid', output_field=FloatField())) return table.values('total_paid') My goal is to get the summation of paid attributes throughout the orders for the customer. When the order object includes only one order_item the querryset outputs the correct value, But when the order object contains more than one order_item I will get the wrong result. For example when I run the code customer.objects.get_customer_stats() for only one customer who has only one order with the paid amount of 10.0, I will … -
How to send excel file as a download link button by email using celery?
I need to send an excel file as a download link button in html template by Email using celery my question: do I need to use a field to save the file and use it as a url ? or can I send the export data directely to the html template button as a file ? can I : send the file with generate http so can the user download it ? the target: the data is huge and limit of gmail is 20mb for a file attached,for this need to make it as a download link button not send it as an attached file task.py dataset = OrderResource().export(queryset=queryset) export_data = format_type.export_data(dataset) # Send E-mail start here NotificationSender.send(user, SalesReportEmail(file_name, export_data, content_type)) the celery here is for send the file and email and it doesn't return any thing to the views.py and for that I think I can't use http response the process : the user select the file format then the function send this format to celery "task.py" to collect data and send it by email as a file download link, the funcion here "in views.py " only shows pop up message say that "Please allow few minutes, the report … -
Django dj-rest-auth + react: What is the best way to activate your email when ACCOUNT_EMAIL_VERIFICATION = 'mandatory'?
I'm currently building a django & dj-rest-auth + react project and have my allauth ACCOUNT_EMAIL_VERIFICATION = 'mandatory'. Currently and by default, the email activation link can only make a GET request to dj_rest_auth.registration.views.VerifyEmailView (source code) that only accepts a POST request with the activation key as a body param: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: [example.com] Please Confirm Your E-mail Address From: webmaster@localhost To: firstlast@email.com Date: Sun, 04 Apr 2021 09:56:05 -0000 Message-ID: <161753016543.13016.12022069896332406678@DESKTOP-LFBEG3D> Hello from example.com! You're receiving this e-mail because user firstlast@email.com has given your e-mail address to register an account on example.com. To confirm this is correct, go to http://localhost:8000/users/registration/account-confirm-email/MjQ:1lSzUD:OVzw0T279ufU2FyzHhKbWo2oilnya9x9vfQLJ6WgEzw Thank you for using example.com! example.com [04/Apr/2021 02:56:05] "POST /users/registration/ HTTP/1.1" 201 18797 And I don't know how to make a POST request through a link that's embedded in an email sent by Django. My current solution is to modify the get_email_confirmation_url method by replacing the absolute_uri with my frontend react route. Then from there I'll make a POST request to VerifyEmailView so that the user doesn't have to look at my backend views. Is there a good or standard way to dynamically add my frontend domain instead of hardcoding http://localhost:5000 and https://production.com into my … -
Django Subdomains
I want to create a mutitenant site with subdomains. Meaning, users will sign up with email, password and company name. Although, I am still experimenting with the email. Upon register, they will be redirected to a subdomain like company_name.domain.com. Right now, I am using the package Django-Subdomains I have setup as specified in their doc. But I dont quite get how to set up the views. For instance, my register view is this class RegisterStaff(View): template = 'account/register.html' def get(self, request, ): register_form = StaffRegisterationForm() context = { 'register_form': register_form, } return render(request, template_name=self.template, context=context) def post(self, request): register_form = StaffRegisterationForm(request.POST) if register_form.is_valid(): staff = register_form.save() password = register_form.cleaned_data['password1'] email = register_form.cleaned_data['email'] print(dir(request)) my_user = authenticate(request, email=email, password=password) login(request, my_user, ) request.subdomain = request.user.email print(request.subdomain) return redirect('account:dashboard', subdomain=request.subdomain) else: print(register_form.errors) return HttpResponse('form is invalid') and I have my dashboard vies below. class Dashboard(View): template = 'account/dashboard.html' def get(self, request): try: staff = Staff.objects.get(email=request.subdomain) except Staff.DoesNotExist: raise Http404 Normaly, I would thought that after registration, I should be redirected to email.domain.com. But I get a 404 instead. Please help if you are familiar with this package. my Url from Django.urls import path from .views import RegisterStaff, Dashboard, LogoutUser,LoginUser app_name = 'account' … -
property field is not shown in api call in django rest framework
I am trying to add a property field to my serializer while creating Order objects creating the OrderItem objects at the same time. But it is not shown in the result while calling the post api. There is no price filed in the result as shown here. My models: class OrderItem(models.Model): #user = models.ForeignKey(User,on_delete=models.CASCADE, blank=True #orderItem_ID = models.UUIDField(max_length=12, editable=False,default=str(uuid.uuid4())) orderItem_ID = models.CharField(max_length=12, editable=False, default=id_generator) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants, on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) #total_item_price = models.PositiveIntegerField(blank=True,null=True,default=0) ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) order_item_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') @property def price(self): return self.quantity * self.item.varaints.price # return total_item_price My serializers: class OrderItemSerializer(serializers.ModelSerializer): order = serializers.PrimaryKeyRelatedField(read_only=True) price = serializers.ReadOnlyField() class Meta: model = OrderItem fields = ['id','order','orderItem_ID','item','order_variants', 'quantity','order_item_status','price'] # depth = 1 Here I have put price in the serializer field, there is no error, but it doesnt show the price in the api in postman. class OrderSerializer(serializers.ModelSerializer): billing_details = BillingDetailsSerializer() order_items = OrderItemSerializer(many=True) user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = Order fields = ['id','user','ordered_date','order_status', 'ordered', 'order_items', 'total_price','billing_details'] # depth = 1 def create(self, validated_data): user = self.context['request'].user if not user.is_seller: order_items = validated_data.pop('order_items') billing_details = validated_data.pop('billing_details') order = … -
unable to read .replit: unable to decode .replit: Near line 5 (last key parsed 'run'): Key 'run' has already been defined
so effectively I am tryinning to run a Django website that i can share the link. The issue is the RUN file with the .replit file. I need to pip install crispy forms then run the server. How can this be accomplished in the .replit file? tried the following: language = "python3" run = "pip install django-crispy-forms" run = "python manage.py runserver 0.0.0.0:3000" -
Django Redirect to previous page, if user is not allowed to access page
I have created a custom decorator to restrict access to a view based on an user's group. If a user is not allowed to access the view he/she gets redirected to my landing page '/' (in code below)... How can I redirect the user to the site he/she was coming from? I am close but I don't know how to fix this. Thank you so much Please see: def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = '' if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponseRedirect(request.META.HTTP('HTTP_REFERER', '/')) return wrapper_func return decorator Thanks a lot -
How to send veriables using redirect and use in other views
Im working on project and im sending data/veriable while redirecting flow from one view to another(first view/empty view) def index(request,a=False): if request.method=='POST': return render(request,'chart-chart-js.html',{'a':True}) return render(request,'chart-chart-js.html',{'a':a}) def login(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): if form.cleaned_data['username']=='Unknown' and form.cleaned_data['password']=='Unknown': return redirect(index,a=True) -
Apache with mod_wsgi not serving on port 80
I'm actually facing some weird issue. I have a Linux based server with two Django app installed and I want to serve them using mod_wsgi. The problem, when I set the vhost to listen to port 80, in the browser it's just showing me directories and files. When I set it to listen to 8080 it works but only if I'm behind a VPN (or proxy). Here is my httpd.conf Listen 80 <VirtualHost *:80> WSGIPassAuthorization On WSGIDaemonProcess 0.0.0.0 (my IP adress) python-home=/usr/local/apache/htdocs/env python-path=/usr/local/apache/htdocs/myapp/myapp/ request-timeout=12000 WSGIProcessGroup my_ip WSGIScriptAlias /myapp /usr/local/apache/htdocs/myapp/myapp/wsgi.py process-group=my_ip <Directory /usr/local/apache/htdocs/myapp/myapp> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> <VirtualHost *:80> WSGIPassAuthorization On WSGIDaemonProcess my_ip python-home=/usr/local/apache/htdocs/env python-path=/usr/local/apache/htdocs/myapp2/ request-timeout=12000 WSGIProcessGroup my_ip WSGIScriptAlias /myapp2 /usr/local/apache/htdocs/myapp2/myapp2/wsgi.py process-group=my_app <Directory /usr/local/apache/htdocs/myapp2/myapp2> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> Does anyone know how to figure this out ? -
login_required does not work with firebase auth
I have a login page with authenticates the user using the built in Django authentication. However when I use firebase authentication to authenticated a user, the @login_required decorator for my other pages does not allow the user to access those pages (even the user is logged in using the correct credentials). I followed a tutorial from here https://www.youtube.com/watch?v=8wa4AHGKUJM My login views.py using django authentication: email=request.POST.get('email') passw=request.POST.get('pass') user = authenticate(request, username=email, password=passw) if user is not None: login(request, user) return render(request,"pick.html") else: message="Invalid credentials. Try again." return render(request,"login.html", {"msgg":message}) My login views with firebase authentication: email=request.POST.get('email') passw=request.POST.get('pass') user=auth.sign_in_with_email_and_password(email,passw) usercheck = auth.get_account_info(user['idToken']) usercheckjson=json.dumps(usercheck['users']) userjsonload=json.loads(usercheckjson) if userjsonload[0]['emailVerified'] == False: message="Please verify your email before login!" return render(request,"login.html", {"msgg":message}) else: #login(request, user) <-- this does not work session_id=user['idToken'] request.session['uid']=str(session_id) return render(request,"pick.html") Any suggestions on how i can get this to work, or should i just use the built in Django authentication? -
Django channels + Daphne + Nginx, path not found only for wss, not ws
A summary of my question: I am deploying websocket with django channels. When I use ws (without SSL), everything works well. But when I request using wss (with nginx re-configed), it shows the error Not Found: /ws/rider/mission/ Here are some details: I have added path /ws/ for both 80 and 443 ports From the console of Daphne, I can see both requests, as shown in the figure below. Therefore, I think my Nginx is correctly forwarding both 80 and 443 requests. But from this figure, I can find that, for this same route "/ws/rider/mission/", the wss request cannot be found, but ws request runs well. Here is my aswi config application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": Oauth2AuthMiddleware( URLRouter( websocket_urlpatterns = [ url(r'ws/rider/mission/', consumers.RiderConsumer.as_asgi()), ] ) ), }) I don't know where the bug comes from, it is between Nginx to Daphne, or Daphne to Django channels or in Django channels itself. Thanks! -
AJAX return 500 Internal Server Error on POST :DJANGO
i have a program which should post formdata to another HTML page , in DJANGO , but it throws me Internal Server Error . . so here is my code : AJAX CALL: $("[name=ButtonSubmit]").click(function() { var myarrayServer = []; $(".form-check-input0:checked").each(function() { var opeartions = [] //for inner array var row = $(this).closest("tr"); //get servername var server_name = row.find("td:eq(1)").text().trim(); var components = row.find("td:eq(2)").text().trim(); var PID = row.find("td:eq(3)").text().trim(); var State = row.find("td:eq(4)").text().trim(); opeartions.push(server_name) //push in array opeartions.push(components) opeartions.push(PID) opeartions.push(State) //get checkboxes which is checked in same row row.find("input[type=checkbox]:checked:not(:first)").each(function() { opeartions.push($(this).val()) }) myarrayServer.push(opeartions) //push values in main array }); var formdataD = new FormData(); formdataD.append('myarrayServer', myarrayServer); formdataD.append('csrfmiddlewaretoken', $("[name=csrfmiddlewaretoken]").val()); $.ajax({ url: 'secondtableonDashboard', //replace with you url method: 'POST', data: formdataD, processData: false, contentType: false, success: function(data) { alert(data.message); alert("Success"); }, error:function(request, status, error){ alert(error); } }); }); So here i gave alert for formdata and myarrayserver , both gave me alert with the correct data . Views.py : if 'ButtonSubmit' in request.POST: print("Inside Button") print(list(request.POST.items())) user_lists = request.POST.getlist('myarrayServer') print(user_lists) cmddata = {'customerserver':result} return render(request,'side-menu-light-tabulator.html',cmddata) So here i am able to print "inside Button" , but rest print give me an empty list [] , I don know where i did mistake Can someone help … -
Problem sending data with ajax to django server
I'm trying to send some ajax data to my Django server but encounter an error that I have difficulties debugging : raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0). This is my script and part of my django view. function UpdateUserResponse(productId, action, count) { $.ajax({ url: "/updateitem/", method: "post", headers: { 'Content-Type':'application/json', "X-CSRFToken": csrftoken }, dataType: "JSON", body: JSON.stringify({ productId : productId, action: action, count: count }), success: response => { console.log("not relevant to this problem"); } }); } and how i try to receive the data in my view def updateitem(request) : data =json.loads(request.body) productId=data['productId'] action = data['action'] count = data['count'] Thanks a lot for your help -
How to bind a django form to an object instance
I come from DRF background so please already assume that I might be getting something wildly wrong here. I am trying to use Django Form as a sort of proxy for DRF serializers. As in, when I fetch an object, I can quickly render it back, and I can of course accept POST requests and store them. What I can't seem to find is how do I use my object instances to process them with forms. Here's my form: class ProfileForm(ModelForm): class Meta: model = UserProfile fields = ('name', 'profile_pic') The actual model: class UserProfile(models.Model): user = models.OneToOneField(CustomUser, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(upload_to='profile_image', null=True, blank=True) def __str__(self): return str(self.user) Now, in my view, I'm doing something like this: from django.forms import model_to_dict profile = request.user.userprofile form = ProfileForm(model_to_dict(profile)) return render(..., form) Is this even the right approach? Besides, the problem is that my form doesn't seem to handle the profile_pic field properly (i.e. the img src field in the from html is just __). Ideally I would want to build the form from the object instance itself, but that also doesn't work. form = ProfileForm(instance = profile) is nethier bound, nor valid form = ProfileForm(UserProfile.objects.all()[0]) is … -
How to apply django-filter after SerializerMethodField modified values?
I feel stuck with the following issue: I added django-filter to my django-rest project to allow filtering by contract's signing status field. The problem is that my contract_signing_status has only 2 possible DB values: SIGNED, NOT_SIGNED. However, I use a SerializerMethodField which internally accesses a user model from the request and returns different values, eg: "WAITING_FOR_ME", "WAITING_FOR_OTHRS". The problem is that the django-filter works on the query-set. As a result, if I set those values: "WAITING_FOR_ME", "WAITING_FOR_OTHRS" as my query params, I keep getting an empty response list, because my model does not define those values... I would like to apply django-filtering on the serializer.data, not on the query-set, because values are modified after the serializer serialized that query set. Is it possible? I thought about creating a property in my model. But properties can't accept additional arguments, like User for example. -
wagtail custom locale file
i integrate Wagtail into my Django project and my language is persian ( fa ) i use multilang in django project and wagtail admin panel words translation to persian works and is perfect but in wagtail admin panel some words not translated and i want to add this words i found this words in wagtail/admin/locale/en/LC_MESSAGES/django.po but in wagtail/admin/locale/fa/LC_MESSAGES/django.po does not exists how can i use my custom locale file for wagtail admin panel? how can i fix this? -
data isn't importing in mysqldb using django import export
I am new in Django. I am trying to use Django import-export to import excel sheet into MySQL dB table. I followed the documentation on import. while trying to Test the data import it gives error. Here are my views: from django.shortcuts import render from pathlib import Path import os from .resources import ProductsResource from tablib import Dataset def home(requests): dataimport() return render(requests,'dbapp/index.html') def dataimport(): products_resource = ProductsResource() dataset = Dataset() dirname = Path(__file__).resolve().parent.parent file_name = 'Price.xlsx' file_location = os.path.join(dirname, file_name) df = pd.read_excel(file_location, header=1, usecols='A:F') result = products_resource.import_data(dataset, dry_run=True) # Test the data import print(result.has_errors()) if not result.has_errors(): products_resource.import_data(dataset, dry_run=False) # Actually import now Resource.py: from import_export import resources from .models import Products class ProductsResource(resources.ModelResource): class Meta: model = Products Models.py: from django.db import models from django.db.models.fields import DateField class Products(models.Model): date = models.DateField(auto_now_add=False,auto_now=False) salt = models.FloatField() oil = models.FloatField() honey = models.FloatField() butter = models.FloatField() milk = models.FloatField() My csv file looks like this: Date Salt Oil Honey Butter Milk 2020-1-1 26.5 106.5 281 387.5 83 2020-1-2 26.2 106.2 279.8 386 82.4 2020-1-3 26 106 279 385 82 2020-1-4 25 105 275 380 80 2020-1-5 26.2 106.2 279.8 386 82.4 2020-1-6 26.1 106.1 279.4 385.5 82.2 output of … -
django_host raising 'accounts' is not a registered namespace error
I implemented django_hosts in my project and followed all the basics as documented here, everything seemed perfect until I started using the {% load hosts %} and {% host_url 'accounts:login' host 'accounts' %} template tags to reverse URLs just as it would normally be done with the default URL tag like {% urls 'accounts:login' %}. And now, I am getting the following errors. NoReverseMatch at /en/auth/signup/personal/ 'accounts' is not a registered namespace` I have taken a closer look at my code again and again, but I can't find any issue with it. Has anyone experienced this kind of issue before? sample HTML {% extends 'base.html' %} {% block content %} {% load hosts %} <form class="form" method="post" enctype="multipart/form-data" role="form" action="{% host_url 'accounts:login' host 'accounts' %}"> {% csrf_token %} {% bootstrap_messages %} {% bootstrap_form form show_label=False %} <button class="btn block-btn" type="submit" role="button">{% trans 'Sign in' %}</button> </form> <!--redirect--> <span class="text-center d-block"> <a href="{% url 'password_reset' %}" class="form-footer-link centered-form-link"> {% trans "Can't login?" %} </a> <span class="middot">&bull;</span> <a href="{% host_url 'accounts:personal_signup' host 'accounts' %}" class="form-footer-link centered-form-link"> {% trans "Sign up for an account" %} </a> </span> {% endblock content %} hosts.py host_patterns = patterns('', host(r'www', settings.ROOT_URLCONF, name='www'), host(r'auth', 'accounts.urls', name='accounts'), ... ) … -
Uploaded Document Version Control
I have a Django web app for uploading and sharing files. I am looking for good library that can assist with document version control. Maintain copies of the same document. Has anyone ever encountered such a use case? -
display allow or block popup location django
I want to display allow or block location button popup in a html page in Django and get the user's current location through IP that gives latitude and longitude. -
Django admin Page 404 Not Found & Error Handling page Not Working (DEBUG_PROPAGATE_EXCEPTIONS)
My Django Project is perfectly working Local PC , and after Deployment Please Help Me to Fix! I face Some problems: Don't show Django Error Handling Page. Django Admin Page Not Show. my setting & Urls & output File Here, I cannot see my Django default as like my development. urls.py File from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('frontend.urls')), path('admin/', admin.site.urls), #path('admission/', include('admission.urls')), path('user/', include('userregistration.urls')), path('study/', include('study.urls')), path('employment/', include('employment.urls')), #path('form/', include('form.urls')), ] urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) admin.site.index_title = "GSL Adminstrator" admin.site.index_header = "Global Star Admin" admin.site.site_title = "Global Star Admin" admin.site.site_header = "Global Star Admin" Settings.py file from pathlib import Path, os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'wy7o_s_pw$(71l-ta)0w1fud#7%zm3$5^n2p4ygo$an0n)ieqi' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['dev.globalstar.com.bd', 'www.dev.globalstar.com.bd'] # Application definition INSTALLED_APPS = [ 'phonenumber_field', 'dal', 'dal_select2', # 'grappelli', 'widget_tweaks', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #'admission', 'employment', #'form', 'frontend', 'study', 'travel', … -
Django ajax post throws 500 error on web host but works on localhost
I am able to send JSON data using AJAX on the local server, but, when I run the same site on the webserver, ajax post throws 500 (Internal Server Error). urls.py urlpatterns = [ path('recievejson/', views.recievejson, name='recievejson'), ] views.p @csrf_exempt def recievejson(request): if request.method == 'POST': # This condition is satisfied when hosted on localhost. import json print("DATA RECIEVED") print(request.body) else: # This condition is satisfied when onsted on web server. message = "Data not recieved" return JsonResponse({"message": 'http://domain name com/static/text/'+message}) AJAX: $.ajax({ url: "/recievejson", type: "POST", data: data, processData: false, contentType: "application/json; charset=UTF-8", success: function(data) { console.log("SUCCESS"); }, error: function(data){ console.log("fail"); } }); How to resolve this issue? -
Using Django-subdomains 'WSGIRequest' object has no attribute 'subdomain'
I am using Django-Subdomain Package and I am getting this error 'WSGIRequest' object has no attribute 'subdomain'anytime I run this view. def post(self, request): register_form = StaffRegisterationForm(request.POST) if register_form.is_valid(): staff = register_form.save() print(dir(request)) return redirect('account:dashboard', subdomain=request.subdomain) else: print(register_form.errors) return HttpResponse('form is invalid') This is my middleware in settings file: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'subdomains.middleware.SubdomainURLRoutingMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',] -
Django QuerySet retuns empty queryset
I have not been able to tell why this model querry returns an empty queryset... Here are my models class Marks(models.Model): klass = models.ForeignKey(Klass,on_delete=models.SET_NULL,null=True,blank=True) stream = models.ForeignKey(Stream,on_delete=models.SET_NULL,null=True,blank=True) mark = models.IntegerField() class Klass(models.Model): name = models.CharField(max_length=20) The view. def ResultsView(request): query = request.GET.get('klass') if query: queryset = (Q(klass__name__icontains=query)) the_Student = Marks.objects.filter(queryset).distinct() all_results = {'the_Student':the_Student,'query':query} else: all_results = {} return render(request,'exams.html',all_results ) The form template <form action="{% url 'search_marks' %}" method="GET"> <div class="input-group"> <input class="" style="flex:50%" type="text" name="klass"> <button class="btn btn-primary" type="submit"></button> </div> </form> The url path('search_m',ResultsView,name='search_marks'), I try getting the results here {% for mark in the_student %} {{ mark }} {% endfor %} When I print the_student from the view it gives <QuerySet []> When I try queryset = (Q(mark__icontains=query)) brings an answer