Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why celery doesn't get the task in django?
i'm new in celery there is a simple task that I want to use celery in Django but in celery log there isn't any message to get task. these are my codes: celery.py: from __future__ import absolute_import, unicode_literals from celery import Celery app = Celery('kia', broker='redis://localhost:6379/0') app.conf.update( result_serializer='json', accept_content = ['application/json'], task_serializer = 'json' ) app.autodiscover_tasks() tasks.py: import section . . . logger = get_task_logger('__name__') @task(name="send_sms_task") def send_sms_task(text, phone_number): logger.info("sms sented") return sms(text, phone_number) views.py: import section . . . @api_view(['GET',]) @permission_classes((AllowAny,)) def TestSMS(request): if request.method == 'GET': x = send_sms_task.apply_async(["something", "somethingelse"]) data= {"OK"} return Response(data) sms.py: def send_sms(text,phone_number): print("an api service that work correctly") finally this is my tree project: ├── account │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── permisions.py │ ├── serializers.py │ ├── sms.py │ ├── tasks.py │ ├── urls.py │ ├── utils.py │ └── views.py ├── db.sqlite3 ├── project │ ├── celery.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py function in sms.py work without celery but when I try to use celery nothing happens in celery log in addition in 2 case(with celery and without it) I get 200 … -
Django repeated forms
I have a form with a dropdown select option with possible options of 1,2,3,4 or 5. Based on the user select option 'x', I render same form repeated 'x' many times. Upon submit, I try to fetch the data using following in my view userprofileForm(request.POST) but this fetches just the last entry or most recent entry and not all the 'x' entries. Here is the rough HTML for my rendered form. In this instance the user selects option 2 so the form has a div repeated 2 times. <form ... > <div> <label...> <input...> </div> <div> <label...> <input...> </div> </form> Upon hitting submit button, the view for registeration is triggered and like I explained above in the beggining doing userprofileForm(request.POST) does not fetch both the 2 entries but just the last one. How can this be fixed so I have all form data of both the divs and how do I access it? -
How to pass search input value in output
I have search bar that renders the list of elements that user whats to find. I'd like to pass the input value to output html so if user is searching for article 1 then I want to display above the list the query name. I tried to put query, lookup but it doesn't work. views.py def search_qa_results(request): query = request.GET.get('q') qa_list = QA.objects.filter(title__icontains=query) if query is not None: lookups = Q(title__icontains=query) qa_list = QA.objects.filter(lookups) context = { 'qa_list': qa_list } return render(request, 'search/search_qa.html', context) index.html <form action="{% url 'search_qa_results' %}" method="get" id="search"> {% csrf_token %} <div class="searchbar" id="autocomplete"> <input name="q" type="text" placeholder="Type your question" class="search_input"> <a href="{% url 'search_qa_results' %}" class="search_icon"><i class="fas fa-search"></i></a> <ul class="autocomplete-result-list"></ul> </div> </form> search_results.html {% extends 'base.html' %} <title>{% block title %}Q&A results{% endblock %}</title> {% block content %} <link rel="stylesheet" type="text/css" href="/static/search_qa.css"> <div class="d-flex justify-content-start"> Search results for my question: {{WHAT TO PUT HERE?}}</div> <div class="container h-100 pb-4"> <div class="d-flex justify-content-end h-100 pb-4"> {% for qa in qa_list %} <div class="card text-dark bg-light mb-3 text-left"> <a href="{{ qa.get_absolute_url }}"> <h5 class="card-header">Q: {{qa.title}}</h5> <div class="card-body"> <div class="card-title text-justify">A: {{ qa.answer }}</div> </div> <div class="card-footer"> <small class="text-muted">Published: {{qa.publish}}</small> </div> </a> </div> {% empty %} <p>No results</p> {% … -
Django SESSION_EXPIRE_AT_BROWSER_CLOSE doesn't work
I would like to log out user if browser is closed. I added SESSION_EXPIRE_AT_BROWSER_CLOSE = True to my settings.py and the following function to my base.html file but it doesn't work. $(document).ready(function(){ $(window).on("beforeunload", function(e) { $.ajax({ url: logout_view, method: 'GET', }) }); }); What am I missing and how to solve it? I am using Django 3.2. -
Input Tag and spaces in Strings
model.py class Cartrecord(models.Model): cartid=models.AutoField(primary_key=True) cart_user=models.ForeignKey(User,on_delete=models.CASCADE) json_data=models.CharField(max_length=500,default="0") def __str__(self): return self.cart_user.username views.py param_cart=Cartrecord.objects.get(cart_user=request.user) params['cart']=param_cart params['cart_length']=len(param_cart.json_data) return params html <input id="cart_data" type="text" value={{cart.json_data}}> <input id="cart_length" type="hidden" value={{cart_length}}> enter code here cart.json_data is supposed to be printed as {"product7":{"0":1,"1":"USB cable","2":"250"},"product9":{"0":1,"1":"Sony Tv","2":"40000"},"product10":{"0":1,"1":"LG Refrigerator","2":"30000"},"product4":{"0":1,"1":"mobie","2":"10000"},"product6":{"0":1,"1":"bag","2":"1000"}} Instead im getting this {"product7":{"0":1,"1":"USB I have tried it with different sets of json data, but each time the string got sliced when it meets the space But later i have tried the same thing using textarea by replacing input tag, <textarea id="cart_data" type="text">{{cart.json_data}}</textarea> And i got my json string properly Can someone explain this behavior? -
How to Preview and Edit, Login the django model form after finishing the user signup in django?
models.py class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) mobile_number = models.IntegerField(blank=False, null=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] customer = models.BooleanField(default=False) vendor = models.BooleanField(default=False) id = models.AutoField(primary_key=True, editable=True) userid= models.CharField(max_length=100, unique=True, null=True) objects = UserManager() def __str__(self): return self.email forms.py class VendorCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ['email','first_name','last_name','mobile_number'] def save(self, commit=True): user = super().save(commit=False) user.vendor = True if commit: user.save() return user views.py def VendorSignup(request): vendorform = VendorCreationForm() if request.method == 'POST': vendorform = VendorCreationForm(request.POST) vendordetailform = VendorAdminDetailsForm(request.POST, request.FILES) if vendorform.is_valid(): new_user = vendorform.save() new_user.is_active = False new_user.save() return redirect('vendor_preview') else: vendorform = VendorCreationForm() return render(request, 'vendor/signup.html', {'vendorform': vendorform}) def VendorPreview(request): details = CustomUser.objects.filter(id=request.user.id) return render(request,'vendor/preview.html', {'details':details}) My template: signup.html <div class="container"> <h1>VENDOR SIGNUP</h1><br> <form method="POST" action="{% url 'vendor_signup' %}" enctype='multipart/form-data'> {% csrf_token %} {{ vendorform.email|as_crispy_field}} {{ vendorform.first_name|as_crispy_field}} {{ vendorform.last_name|as_crispy_field}} {{ vendorform.mobile_number|as_crispy_field}} {{ vendorform.password1|as_crispy_field}} {{ vendorform.password2|as_crispy_field}} <button type="submit" class="btn btn-dark" value="Submit">Submit</button>&ensp; <a href="{% url 'login' %}">Already a Vendor?</a> </form> </div> preview.html <caption>Please, Check your details.</caption> <table class="table table-hover table-bordered mt-3"> <thead> <tr> <th scope="col">Email Address</th> <th scope="col">First Name</th> <th scope="col">Last Name</th> <th scope="col">Mobile Number</th> </tr> </thead> <tbody> {% if details %} {% for data in details %} <tr> <td>{{data.email}}</td> … -
how export filtered data in django
I am using class based view to such for data and I want to export the output from search. The output is from two dates search. I use below code: class expenses_list(ListView): model = EXPENSES template_name = 'cashes/expenses_list.html' paginate_by=10 def get_queryset(self): filter_val1=self.request.GET.get("filter1","") filter_val2=self.request.GET.get("filter2","") order_by=self.request.GET.get("orderby","-date_of_operation") if filter_val1!="" and filter_val2!="": reqo=EXPENSES.objects.filter(Q(created_at__range= [filter_val2,filter_val1])).order_by(order_by) else: reqo=EXPENSES.objects.filter().order_by(order_by) return reqo def get_context_data(self,**kwargs): context=super(expenses_list,self).get_context_data(**kwargs) context["filter1"]=self.request.GET.get("filter1","") context["filter2"]=self.request.GET.get("filter2","") context["orderby"]=self.request.GET.get("orderby","id") context["all_table_fields"]=EXPENSES._meta.get_fields() return context and I have this as interface enter image description here the following export code is not working as the value of date fields are empty value def exporexpensescsv(request,**kwargs): filter_val1=request.GET.get("filter1") filter_val2=request.GET.get("filter2") print(filter_val1) print(filter_val2) response=HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=expenses' + str(datetime.datetime.now())+'.csv' writer = csv.writer(response) writer.writerow(['Categoty','Beneficiary','Description','Operation Date','Amount','Account Number','Paymrnt Date','Status']) expes = EXPENSES.objects.filter(Q(created_at__range=[filter_val1,filter_val2])) # expes = EXPENSES.objects.all() for exp in expes: writer.writerow([exp.category,exp.beneficiary,exp.description, exp.date_of_operation,exp.amount,exp.account_number,exp.payment_date, exp.status]) return response but when I want to export with expes = EXPENSES.objects.all() it works well. Assist to be able to export the filtered data. -
Django - Вывод формы вопрос|вырианты ответов [closed]
помогите пожалуйста, нужно сделать вопросник(вопрос и варианты ответы) Сделал простую связанную модель: class Questions_set(models.Model): title = models.CharField(max_length=500, verbose_name='Вопрос') def __str__(self): return self.title class Meta: verbose_name = 'Вопросы' verbose_name_plural = 'Вопрос' class Answers_set(models.Model): title = models.CharField(max_length=500, verbose_name='Вопрос') correct = models.BooleanField(verbose_name='Правильный ответ') key_questions_set = models.ForeignKey(Questions_set, on_delete=models.CASCADE, related_name='question') Заполнил таблицы.Как вывести в шаблон вопрос и варианты ответов к нему в форме или это не через форму решается?Спасибо -
how to successfully upload BLOB images to django ImageField
I am using django rest framework(version 3.12.2) for my backend, and React/Next js in my front end. my goal is pretty straightforward, I want to upload BLOB images via POST request to django. but unfortunately I receive this error message {"photo_main":["The submitted data was not a file. Check the encoding type on the form."]} has anyone ever encountered this problem and was able to solve it? the model class Recipe(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) author = models.ForeignKey(get_user_model() , on_delete=models.CASCADE, null=True, related_name='author') photo_main = models.ImageField(upload_to='media/', blank=True) title = models.CharField(max_length=150) description = models.TextField(blank=True) the view class RecipeCreate(CreateAPIView): permission_classes = (permissions.IsAuthenticated, ) queryset = Recipe.objects.all() serializer_class = RecipeCreateSerializer def perform_create(self, serializer): '''save the the current logged in user as the author of the recipe''' serializer.save(author=self.request.user) I'll appreciate every help that I can get, thanks in advance -
Django reverse returns the error 'view_name' is not a valid view function or pattern name
Here is my view: class OrganizationViewSet(AbstractEntityViewSet): serializer_class = OrganizationSerializer permission_classes = [IsAuthenticated] model = serializer_class.Meta.model queryset = model.objects.all() I registered it as follows: router.register(r"organizations", OrganizationViewSet, basename="organizations") Now, I am trying to use build_absolute_url as follows: HttpRequest().build_absolute_uri(reverse('organizations', args=(self.parent_organization.slug,))), It returns the following error: File "C:\Samir\Pro\near_shop\venv\lib\site-packages\django\urls\base.py", line 86, in reverse return resolver._reverse_with_prefix(view, prefix, *args, **kwargs) File "C:\Samir\Pro\near_shop\venv\lib\site-packages\django\urls\resolvers.py", line 694, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'organizations' not found. 'organizations' is not a valid view function or pattern name. The basename on the router is "organizations", then why it can't find it? -
How to save shipping information when proceed with payment in Django Razorpay gateway?
I am trying to submit the data in the database whenever a customer pays with Razorpay Payment gateway, but I am able to click on the Razorpay payment gateway button and the amount is reflected in my Razorpay test account. But shipping data is not stored in my database, Please help me to solve this issue. Here is my views.py file... def place_order(request,total= 0,quantity = 0): cart = Cart.objects.get(cart_id = _cart_id(request)) cart_items = CartItem.objects.filter(cart = cart, status = True) # cart_items = CartItem.objects.filter(user= current_user) cart_count = cart_items.count() if cart_count <= 0: return redirect('login') tax= 0 grant_total = 0 for item in cart_items: total += (item.product.sale_price * item.quantity) quantity += item.quantity tax = (3*total)/100 grant_total = total+tax if request.method == "POST": order_number = request.POST.get('order_number') full_name = request.POST.get('full_name') mobile = request.POST.get('mobile') email = request.POST.get('email') address_line1 = request.POST.get('address_line1') address_line2 = request.POST.get('address_line2') country = request.POST.get('country') state = request.POST.get('state') city = request.POST.get('city') order_note = request.POST.get('order_note') tax = request.POST.get('tax') grant_total = int(request.POST.get('order_total'))*100 status = request.POST.get('status') amount = int(request.POST.get('amount')) * 100 # Create Rezorpay Client client = razorpay.Client(auth=('rzp_test_ertermiaBf1212','ertgghg56Qp27UYlPEsghtedfes')) # Create Order callback_url = 'http://'+ str(get_current_site(request))+"/payment/handlerequest/" response_payment = client.order.create(dict(amount=amount, currency="INR") ) order_id = response_payment['id'] order_status = response_payment['status'] if order_status == 'created': order = Order( order_number = order_number, full_name … -
Why does my Javascript code returns object object?
I am new to jquerry. I tried getting/summing some items from my django views in jquerry. this is whhat I have $(document).ready(function() { var sch = $('#sch-books'); var gov = $('#gov-books'); var total = sch.val() + gov.val(); $('#total').text("Total : " + total); }); My template has these <div id="sch-books" class="h6 mb-1">School copies - <b>{{ s_books.count }}</b></div> <div id="gov-books"class="h6 mb-1">Govt copies - <b>{{ g_books.count }}</b></div> <div id="total"></div> It displays Total : May someone help me get it right.. -
Database queries to 'new-database' are not allowed in this test
I have added a new database in my django project. Now I have run into issues with my test cases. I am keep getting this error message for every single of my test cases: Database queries to 'new-database' are not allowed in this test I have searched for this issue and the common solution comes down to adding databases = '__all__' or databases = {'default', 'new_database'} to the TestCase class But the problem is that now we have a lot of these test cases in my django application and a lot of corresponding TestCase based classes. So it does not fill right (specifically from the scale point of view) to add this databases = '__all__' declaration or whatever to every single class. Do we have any other and more proper solution for this issue? (After all why django needs to make transaction to new_database in all other test cases every single time that does not seem needed at all?) -
django foreign key mismatch - "question_question" referencing "question_subject"
Hi there is this problem I have can anyone solve this ? here is my django model class Question(models.Model): user = models.ForeignKey(User,on_delete=models.SET_NULL,null=True) title = models.CharField(max_length=255,null=True,blank=False) content = models.TextField(null=True,blank=False) subject = models.ForeignKey(Subject,on_delete=models.SET_NULL,null=True,related_name="subject_question") topicTag = models.ManyToManyField(TopicTag, related_name='questionTopic', blank=True) image = models.ImageField(blank=True, null=True) createdAt = models.DateTimeField(auto_now_add=True) votes = models.ManyToManyField(User, related_name='questionUser', blank=True, through='QuestionVote') answer_count = models.IntegerField(default=0,null=True,blank=True) difficulty = models.ForeignKey(Difficulty,on_delete=models.SET_NULL,null=True,related_name="difficulty") id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.title and here is the error code django.db.utils.OperationalError: foreign key mismatch - "question_question" referencing "question_subject" -
What do I need to do if I want to use database data conditionally in Django templates?
I am working on an ecommerce store in Django. I want to know that how do I use the database data passed to templates using render() method, conditionally through JavaScript or AJAX or JSON? For example, let's say I have a following models.py: from django.db import models class Suit(models.Model): title = models.CharField(max_length = 100, verbose_name = "Title") img = models.FileField(upload_to = 'suit-products/', null = True, verbose_name = "Picture") def __str__(self): return f"{self.title}" class Buttoning(models.Model): title = models.CharField(max_length = 100, verbose_name = "Title") img = models.FileField(upload_to = 'buttonings/', null = True, verbose_name = "Picture") def __str__(self): return f"{self.title}" and following views.py from django.shortcuts import render def index(request): suit_prods = Suit.objects.all() buttoning = Buttoning.objects.all() context { "suit_prods": suit_prods, "buttoning": buttoning } return render(request, "index/index.html", context) and following index.html (template): {% for element in suit_prods %} <li> <a href="#"> <div id="menu"> <img src="{{ element.img.url }}" /> <span>{{ element.title }}</span> <span></span> </div> </a> </li> {% endfor %} Now what I want is, if the clicked element in the list items in index.html has the title as "two_piece_suit" then show items of {{ buttoning }} as a list, otherwise pass. If I explain it more using some JS syntax, then I want following kind of … -
Chart.js 3.6.0 is not working on Weebpack 5.62.1?
I have a Django project. And after some security updates, I did some major dependencies upgrade. Everything was fix and working excepting the Chart.js that is not loaded in Webpack. After few days of working hard, I decided to bring the problem here. To clarify from start, these are one critical error and a minor error (can be ignored). charts are not loading - CRITICAL Uncaught ReferenceError: Chart is not defined My solution: To load Chart.js CDN before code <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.min.js"></script> Multiple charts using same canvas - MINOR (temporary ignored) Uncaught Error: Canvas is already in use. Chart with ID '0' must be destroyed before the canvas can be reused. My solution: to use only a js bundle file So let's go over my code! The next files are really big so I will try to bring the important sections. If you need extra info, let me know. These are my dependencies upgrades: # from pip (requirements.txt) Django==3.0.7 >> 3.0.14 django-webpack-loader==0.7.0 >> 1.4.1 # from npm (package.json) "bootstrap": "^4.5.3", >> "^5.1.3", "chart.js": "^2.9.4", >> "^3.6.0", "jquery": "^3.4.1", >> "^3.6.0", "popper.js": "^1.16.0", >> "^1.16.0", "webpack": "^4.44.2", >> "^5.62.1", "webpack-bundle-tracker": "^0.4.3", >> "^1.4.0", "webpack-cli": "^3.3.10" >> "^4.9.1" This is webpack config … -
session id changing after login, so how to preserve session id created before logged in
e-commerce website on django, i am creating a cart either user logged in or not via session_id. For example guest can add an item to it's cart. And cart that created by the session id. Then let's say guest decides to login. So I want to move the guest's cart to logged in user's cart. But when user logged in, session_id is changes. And I can't find the old session id. How can I preserve session id that created before logged in. or is there a better way to accomplish this task. -
Django form - custom user
I created a custom user in django as it follows: class Customer(AbstractBaseUser): ... in my form I imported the class: from account.models import Customer class PostForm(forms.ModelForm): ... client_code = forms.ModelChoiceField(queryset=Customer.objects.all(), required=True, widget=forms.Select( attrs={ 'class':'form-select form-select-sm', 'aria-label':'Default select example', })) ... I run the server and this error is shown: AttributeError: type object 'Customer' has no attribute 'objects' The project structure is: account -- models.py -- forms.py ... post -- models.py -- forms.py ... -
ManagementForm data is missing or has been tampered Django FormTools Wizard
views.py FORMS = [("customer", CustomerModelForm), ("supplier", SupplierModelForm), ("brand", BrandMasterModelForm)] TEMPLATES = {"customer": "add_customer.html", "supplier": "supplier_master", "brand": "add_brand.html"} class MultiStepWizard(SessionWizardView): def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self, form_list, **kwargs): form_data = [form.cleaned_data for form in form_list] return render(self.request, "dashboard_inventory.html", {"data":form_data}) urls.py path('manage_sales/', MultiStepWizard.as_view(FORMS), name="MultiStepWizard") forms.py class CustomerModelForm(forms.ModelForm): class Meta: model = Customer fields = ('name','address','contact','email','state','gstin','pan') class SupplierModelForm(forms.ModelForm): class Meta: model = Supplier fields = ('name','address','city','manager','contact') widgets = { 'name':forms.TextInput(attrs={'class': 'form-control'}), 'address':forms.TextInput(attrs={'class': 'form-control'}), 'city':forms.TextInput(attrs={'class': 'form-control'}), 'manager':forms.TextInput(attrs={'class': 'form-control'}), 'contact':forms.TextInput(attrs={'class': 'form-control'}), } class BrandMasterModelForm(forms.ModelForm): class Meta: model = BrandMaster fields=('brand_name', 'suppliername') widgets={'brand_name':forms.TextInput(attrs={'class': 'form-control'}),'suppliername':forms.Select(attrs={'id':'choicewa','class': 'form-control','required': 'true'}), } Hi everyone, m trying to use formtool to save multistep forms with my own templates. But I am getting error "ManagementForm data is missing or has been tampered Django FormTools Wizard" while saving first form, then unable to proceed further. Please help. -
Hot to get string in template?
view.py queryset = a:1,2,3|b:1,2,3 # this is category return render(request, 'project/company_ad_write.html', {"data":queryset}) filter.py @register.filter(name='get_category') def get_category(str): str = str.split('|') return str What I want. {{data.category|get_category['0']}} result a:1,2,3 and again str = str.split(':') result a and 1,2,3 Do you have any idea? -
DRF-simple-JWT: New user registered but not able to login
I am able to create a New User using the "register" endpoint. I can the user being created on the admin page as well. When I try to get an access token for the newly created user I get the error "detail": "No active account found with the given credentials". I am correctly passing the valid credentials so I don't know what the problem might be. Here I have demonstrated the same. Here goes the code: serializers.py from rest_framework import serializers from .models import CustomUser from django.contrib.auth.hashers import make_password class RegisterUserSerializers(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('email', 'password') extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance def validate_password(self, value: str) -> str: """ Hash value passed by user. :param value: password of a user :return: a hashed version of the password """ return make_password(value) views.py from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.permissions import AllowAny from .serializers import RegisterUserSerializers from rest_framework_simplejwt.tokens import RefreshToken class CustomUserCreate(APIView): permission_classes = [AllowAny] def post(self, request): reg_serial = RegisterUserSerializers(data=request.data) if reg_serial.is_valid(): newUser = reg_serial.save() if newUser: context = { "message": f"User … -
how do I check validation error in django
I am trying to validate fields which are filtered by user. if in filtered data have entered any special character then I wish to print validation error in backend. I am getting Invalid data in output if I pass special characters by url. but getting below error invalid data.. Internal Server Error: /sites/live-data/ UnboundLocalError at /sites/live-data/ return render(request, 'live-data.html', {'sites': sites.json(), 'categories': categories.json()}) UnboundLocalError: local variable 'sites' referenced before assignment here is the code Validations.py def validateAlphanumeric(alphanumeric): alphanumeric_pattern = re.compile(r"^[0-9a-zA-Z]*$") validate_alphanumeric = RegexValidator(alphanumeric_pattern, 'Only alphanumeric characters are allowed.') try: validate_alphanumeric(alphanumeric) return True except ValidationError: return False views.py def liveData(request): ip = request.session['ip'] label = "" category = "" status = "" ordering = "" try: ordering = request.GET['order_by'] except: pass try: category = request.GET['category'] status = request.GET['status'] except: pass if not request.user.is_staff: label = request.session['label'] site_url = ip+"/sites/list/" category_url = ip+"/setup/category/list/" if Validations.validateAlphanumeric(category) and Validations.validateAlphanumeric(status): print("valid.") headers = { 'authorization': "Bearer *****", } params = { 'label': label, 'category': category, 'status': status, 'ordering': ordering } sites = requests.request("GET", site_url, headers=headers, params=params) categories = requests.request("GET", category_url, headers=headers) else: print("invalid data..") return render(request, 'live-data.html', {'sites': sites.json(), 'categories': categories.json()}) -
Redirect within a class based view
I'm working with a FormView. In order to access the page, the user has to pass a certain test. Otherwise, they'll be logged out and redirected. Where within this CBV is the best place to put the redirect logic? Thanks! -
Django Images arent showing in HTML template using Dropzone JS
I'm using the dropzone.js on my django project for editing image i send image on submit button my view function show the data but i'm not able to show the on the html template that i have taken from the user. Predefined {'context':context} is visible but when i append it inside my if condition it run successfully but show not appearance on the html template def index(request): allimg = [] userimg1 = "" userimg = "" if (request.method == 'POST'): i=0 img=[] while(request.FILES.get('file['+str(i)+']')!=None): img1=( request.FILES.get('file['+str(i)+']')) print(img1) img.append(img1) i=i+1 for image in img: imgsize=image.size/1024 userimg = Picture(image=image,name=image.name) userimg.save() print(userimg.image.name) # width = int(request.POST.get('imgwidth')) rot = rotater('media/' + userimg.image.name, 90) userimg1 = EditPicture(editimage=rot,name=image.name) userimg1.save() allimg.append([userimg,userimg1]) return render(request, 'imgeditor/Homepage.html',allimg) return render(request, 'imgeditor/Homepage.html') <body> <div class="container"> <form action="/imagerotate/" method="POST" class="dropzone" enctype="multipart/form-data" name="dropZone" id="myDropzone"> {% csrf_token %} <div class="fallback"> <input name="file" type="file" multiple> </div> </form> <button type="submit" value="Submitbtn" id="submit-all" class="btn btn-primary">Submit</button> </div> <div class="container"> {%for userimg,userimg1 in allimg%} <img src="media/{{ userimg.image }}" width=100px height="=100px"> <img src="media/{{ userimg1.editimage }}" width=100px height="=100px"> {% endfor %} </div> </body> <script> Dropzone.autoDiscover = false; const myDropZone = new Dropzone("#myDropzone", { paramName: 'file', autoProcessQueue: false, clickable: true, maxFilesize: 5, params: {}, uploadMultiple: true, parallelUploads: 10, maxFiles: 10, addRemoveLinks: true, // acceptedFiles: … -
Django rest framework: many to many through model write-able
I have a Order model and Item model. Each order consist of multiple Items. I connect the relationship with through model called OrderItem. Below is my code Models: class Order(models.Model): PAYMENT_TYPES = [ ('COD', 'Cash On Delivery'), ('STRIPE', 'Stripe Credit/Debit'), ('PAYPAL', 'Paypal') ] STATUSES = [ (1, 'Process'), (2, 'Completed'), (3, 'Hold') ] number = models.CharField(max_length=255) total = models.FloatField(null=True) credits_issued = models.FloatField(null=True) paid = models.FloatField(null=True) expected_delivery = models.DateTimeField(null=True) payment_type = models.CharField(max_length=255, choices=PAYMENT_TYPES, null=True) date = models.DateTimeField(default=now) status = models.CharField(max_length=2, choices=STATUSES) note = models.CharField(max_length=255, null=True) ordered_by = models.ForeignKey(User, on_delete=models.CASCADE) location = models.ForeignKey(Location, on_delete=models.CASCADE) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) items = models.ManyToManyField(Item, through='OrderItem', related_name='orders') class Meta: app_label = 'InventoryApp' db_table = 'order' class Item(models.Model): STATUSES = [ (1, 'Active'), (0, 'Inactive') ] DEFAULT_STATUS = 1 name = models.CharField(max_length=255) quantity = models.IntegerField(null=True) last_bought_price = models.FloatField(null=True) order_by = models.DateTimeField(null=True) file_name = models.CharField(max_length=255, null=True) status = models.CharField(max_length=2, choices=STATUSES) category = models.ForeignKey(ItemCategory, on_delete=models.CASCADE) class Meta: app_label = 'InventoryApp' db_table = 'item' class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField() price = models.FloatField() class Meta: app_label = 'InventoryApp' db_table = 'order_item' unique_together = [['order', 'item']] I wanna know how to make serializers for through model which is writeable. I have written serializers but …