Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Frawork: Where to put logic that modifies database?
I have a Django project in which I use the Django Rest Framework (DRF). As I'll share this project with another person, I wanted to make sure the person that is going to pull it for the very first time would not encounter any issue, so this is what I did to simulate this situation: Cloning the repo in a new project folder on my computer. Creation of the DB through the commands makemigrations and migrate. django.db.utils.OperationalError: no such table: bar_reference error message pops up. sqlite3.db file not created. Impossible to run the rest of the code to try it out. Here is the file containing the code causing problem, in one of my view: from rest_framework import viewsets from rest_framework import permissions from rest_framework.permissions import AllowAny from ..models.reference import Reference from ..models.stock import Stock from ..models.bar import Bar from ..serializers.reference import * class MenuViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] references = Reference.objects.all() bars = Bar.objects.all() for reference in references: ref_id = reference.id quantity = 0 for bar in bars: bar_id = bar.id stocks = Stock.objects.filter(ref_id=ref_id, bar=bar_id) for stock in stocks: quantity += stock.stock if quantity == 0: reference.availability = "outofstock" reference.save() else: reference.availability = "available" reference.save() queryset = Reference.objects.order_by('id') serializer_class = … -
Django,saving multiple objects with foreign key, using forms
I have this three model's with relationship 1-N: class Pavimento(models.Model): name = models.CharField("Name", max_length=200) def __str__(self): return self.name class Intervencao(models.Model): ...... class Pavimentacao(models.Model): intervencao = models.ForeignKey(Intervencao, related_name='IntervencaoObjects', on_delete=models.CASCADE) pavimento = models.ForeignKey(Pavimento, on_delete=models.CASCADE, verbose_name="Pavimento") date = models.DateField(blank=True, null=True, verbose_name="Date") def __str__(self, ): return str(self.intervencao) With forms i want to add more than one Pavimentacao to my Intervencao. i already put this working but only save 1 each time , and i want to add 2 or 3 simultaneous. Forms class TabletForm2(forms.ModelForm): class Meta: model=Intervencao fields = __all__ class TabletFormPavimentos(forms.ModelForm): class Meta: model=Pavimentacao fields = __all__ My view @login_required(login_url='/login') def project_detail_chefe(request, pk): instance = Intervencao.objects.get(id=pk) form = TabletForm2(request.POST or None, instance=instance) form2 = TabletFormPavimentacao(request.POST or None, instance=instance) if request.method == "POST": if form.is_valid() and form2.is_valid(): instance_form1 = form.save() instance_form2 = form2.save(commit=False) instance_form2.intervencao = instance_form1 instance_form2.save() return redirect('index') else: form = TabletForm2(request.POST) form2 = TabletFormPavimentacao(request.POST) context = { 'form':form, 'form2':form2, } return render(request, 'tablet/info_chefes.html', context) -
Django is not creating a new user
The problem is in my views.py file, there I am using 2 views at the same time. First one created I and it's solving signup problem and the second is ready django view from django.contrib.auth.views.LoginView, and Login is working successfully, but registration is not ;( that was after adding login view. Here is the code from django.shortcuts import render, redirect from django.contrib.auth import views as auth_views from django.contrib.auth.forms import AuthenticationForm from django.contrib import messages from django.http import HttpResponse from .forms import UserRegisterForm from django.contrib.auth.decorators import login_required def index(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if 'signup' in request.POST: if form.is_valid(): form.supervalid() form.save() username = form.clened_data.get('username') messages.success(request, f'Dear {username} you have been created a new account!') return redirect('main') elif 'login' in request.POST: log_view = auth_views.LoginView.as_view(template_name='main/index.html') log_view(request) else: form = UserRegisterForm() formlog = AuthenticationForm(request) return render(request, 'main/index.html', {'form': form, 'formlog': formlog}) I see the signup form generated in my HTML, but its not working -
Store migration hacks/modifications separately to migration files
I have a Django project with around 1000 migration files. And that project is distributed to 30 vendors and their production servers. The problem is that manage.py migrate takes around 15 minutes on each server. But, in general, it could be solved using "Migrations zero" (combine all migrations per app with squashmigrations or something) to reduce amount of code and files. And that's probably the best way to go. But, that 30 projects are not always migrated/synced with newest migration files (now its very expensive to keep them always updated). So last applied migration on particular project can be very old, so we can not just squash to one single init migration for all projects. And one of the ideas we came up with is not to share migration files at all. But make manage.py makemigrations on each project's server. But, the next problem is that migrations can store some "hacks/modifications") So, to remove migration files from git, we nevertheless have to store hacks somewhere. So, is there a practice to store "hacks/modifications" of migrations separately from migration files? Maybe, somehow in models? Thx for advices -
Not able to perform post request django+react
#accounts.models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from words import models as word_models # Create your models here.class UserProfile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) last_visited_word = models.ForeignKey(word_models.Word, default=4760, on_delete = models.CASCADE) def create_user_profile(sender, instance, created, **kwargs): if created: profile, created = UserProfile.objects.get_or_create(user=instance) post_save.connect(create_user_profile, sender=User) #words/models.py from django.db import models from django.conf import settings # Create your models here. class Word(models.Model): word = models.TextField(blank=True, null=True) meaning = models.TextField(blank=True, null=True) #accounts/serializers.py: from rest_framework import serializers from .models import UserProfile class UserSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = '__all__' #accounts/views.py: @api_view(['POST']) #@authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def userprofile_create_view(request, *args, **kwargs): user_id = request.data.get('user') try: instance = UserProfile.objects.get(user_id=user_id) except UserProfile.DoesNotExist: instance=None serializer = UserSerializer(instance, data=request.data) if serializer.is_valid(raise_exception=True): # create or update data serializer.save() return Response(serializer.data) So Basically I have to update the last_visited_word of the user when the user visits that particular id. I am not able to do the "post" method to update last_visited_word. Api calling is done using axios. I am using React as my frontend. -
How can i get publish files from PyCharm IDE?
i've a project that has been completed but i want to try it on my local IIS to see if it works fine. I've never deployed any website except some ASP.Net projects that written in visual studio. I've used PyCharm since i've been working on django, i got no idea how to get files for publishing. In visual studio you just right click > publish and you get the folder but how can i do this in PyCharm? -
Passing user input to external link in django
I am trying to create a simple django site that would send information to another site with the requests.post function (I'm assuming that this is a correct method, but maybe there is a better way). So far I have a simple .html file created using bootstrap <div class="form-group"> <label for="exampleFormControlInput1">text_thing</label> <input type="text" class="form-control" placeholder="text_thing" name="text_thing"> </div> <div class="form-group"> <label for="exampleFormControlInput1">number_thing</label> <input type="number" class="form-control" placeholder="number_thing" name="number_thing"> </div> <button type="submit" class="btn btn-secondary">Send data</button> </form> and my views.py from django.shortcuts import render, redirect import requests def my_view(requests): if requests.method == "POST": text_thing= request.GET.get('text_thing') number_thing= request.GET.get('number_thing') post_data = {'text_thing', 'number_thing'} if text_thing is not None: response = requests.post('https://example.com', data=post_data) content = reponse.content return redirect('home') else: return redirect('home') else: return render(requests, 'my_view.html', {}) I want the site to do following: render itself allowing the user to input something in both fields, and after pressing the button to be redirected to another site - in this case 'home' and for the input to get sent to example.com. With this moment the page renders correctly but after pressing the button nothing happens and external site receives no data. -
DRF - Custom Field Json
I created a custom field in my model for calculating "statistics" Models.py class Risk(models.Model): [...] def risk_completion(self): total = self.controls.count() total_completion = self.controls.filter(status="NP").count() response_data = { 'total_controls': total, 'total_controls_planned': total_completion } return JsonResponse(response_data) serializers.py class RiskSerializer(serializers.ModelSerializer): [...] total = serializers.CharField(source='risk_completion') class Meta: model = models.Risk fields = ( [...] 'total', ) But DRF returns : "total": "<JsonResponse status_code=200, \"application/json\">" If i'm not using JsonResponse() DRF returns a string : "total": "{'total_controls': 3, 'total_controls_planned': 2}" How can I return "real" Json ? Thanks, -
NoReverseMatch error when using reverse function
I am trying to redirect from one view to another and I get the following error: NoReverseMatch at /challenges/1/answer/ Reverse for 'results' with arguments '(1,'test')' not found. 1 pattern(s) tried: ['challenges\/(?P<challenge_id>[0-9]+)\/results\/$'] I have the following code in views.py: def answer(request, challenge_id): challenge = ... result = "test" return HttpResponseRedirect(reverse('challenges:results', args=(challenge.id, result))) def results(request, challenge_id, result): Here's urls.py path('<int:challenge_id>/', views.detail, name='detail'), path('<int:challenge_id>/results/',views.results, name='results'), path('<int:challenge_id>/answer/',views.answer, name='answer'), My understanding is that 'reverse' in an HttpResponseRedirect would redirect to results if I pass the 'result' in args? Thanks in advance! -
From javascript to server
I have this code which allows you to upload an image onto the canvas and mark out segments on the canvas. When the canvas is double clicked, the coordinates of the segments would be added to an array. Is it possible to write this array segmentList into a JSON file or send it to a django server? Also is there anywhere that i could read up on this? Thanks in advance. $("#imageCanvas").click(function(e) { var x = e.offsetX var y = e.offsetY // Adding 'X' and 'Y' values to the respective list xList.push(x); yList.push(y); var coods = document.getElementById("coods"); coods.innerHTML = 'X: ' + x + ' Y: ' + y; }) $('#imageCanvas').on('dblclick', function() { first = new Segmentation(); xList.pop() yList.pop() first.X = xList; first.Y = yList; segmentList.push(first); if(first.X == "" && first.Y == "") { alert("No points seleected!") } else if(first.X.length < 3 && first.Y.length < 3) { alert("Please select at least more than 3 points!") } else { for( i=0; i< first.X.length; i++) { if(i<first.X.length-1) { console.log(first.X) context.beginPath(); xpos = first.X[i]; console.log(first.X[i]) ypos = first.Y[i] var xpos1 =first.X[i+1] var ypos1 =first.Y[i+1] } if(i==first.X.length-1) { xpos = first.X[i] ypos = first.Y[i] var xpos1 =first.X[0] var ypos1 =first.Y[0] } context.moveTo(xpos, ypos) context.lineTo(xpos, … -
Making my Django Views into a DjangoRestFramework API Endpoint
I have a payment verification View which utilizes some parameters like the secret key, and some other authentication parameters. I would like to make the view into an API endpoint whereby i can just enter the parameter and the it returns the response. P.S: I am also utilizing an external API which has the response, all i have to do is send the required parameters and then if they are correct, it returns the response. Views.py def verify_paystack_payment(request): url = "https://api.paystack.co/transaction/verify/262762380" payload = { "email": "email@yahoo.com", "amount": "10000", "currency": "NGN", "reference": "262762380", "metadata": { "custom_fields": [ { "display_name": "Mobile Number", "variable_name": "mobile_number", "value": "+2348012345678" } ] } } files = {} headers = { 'Authorization': 'Bearer **MY SECRET KEY**', 'Content-Type': 'application/json' } response = requests.request("GET", url, headers=headers, data= payload, files=files) return render(request, "transaction/pay.html") -
Django - How to identify if an url path is from admin site
In my Django project, I am modifying the request body for PUT and POST requests. I do not want to do those processes for the URL path from the Django admin site. Is there any better way to identify if an URL path is from the Django admin site? I am doing the following thing right now. from django.utils.deprecation import MiddlewareMixin from django.contrib import admin from django.urls import resolve class ProcessRequestMiddleware(MiddlewareMixin): """ This middleware appends new payload in request body """ def process_view(self, request, view_func, *view_args, **view_kwargs): path = request.path resolved_path = resolve(path) print(resolved_path.app_name) if resolved_path.app_name == 'admin': # Do something -
Invalid byte sequence for encoding "UTF8": 0xff
I want to copy all my data from txt to PostgreSql via command: COPY employees FROM 'C:/Users/Public/staff.txt' WITH (FORMAT csv); But getting error as in title. Here is my example from staff.txt: 1,0XSUJ0F,Jax,Teller,John,15.01.1944,02.12.1968,02.12.1988,Vice-president,3500 And my employee table has number, fin, name, surname, patronimic, birthdate, contractstart, contractend, position and salary columns. -
Django + Tempus Dominus - Submit django form without submit button
I have a functioning datepicker on my django app called tempus dominus. I am having some trouble trying to set this datepicker to submit without having to click on a submit button. Their documentation is horrible but I finally figured at least part of it, it seems that I have to trigger one of their custom events (change.datetimepicker). Below you will find my implementation... My js skills are quite rusty so probably the problem lies somewhere there... my forms.py class MyForm(forms.Form): date_from = forms.DateField( required=True, widget=DatePicker( options={ 'minDate': '2018-01-20', 'maxDate': '2020-10-20', }, ), initial='2020-08-01', ) date_to = forms.DateField( required=True, widget=DatePicker( options={ 'minDate': '2018-01-20', 'maxDate': '2020-10-20', }, ), initial='2020-10-19', ) my template <div class="col" id="form_div"> <form method="post" action="." id="datetimepicker" class="form-inline justify-content-center"> {% csrf_token %} {{ form.as_p}} <input type="submit" id="submit" value="enviar" style="width:70px" /> </form> </div> my js file $("#datetimepicker").on("change.datetimepicker", function () { $( "#datetimepicker" ).submit(); }); Any help is appreciated! -
How display Inline checkboxes using django cripsy form?
I have Article with many categories. MODEL.py: class Article(Created, HitCountMixin): title = models.CharField(max_length=120) category = models.ManyToManyField(ArticleCategory, related_name='articles') I made Form to Edit Article: FORMS.py class EditArticleForm(forms.ModelForm): title = forms.CharField( label="Tytuł", max_length=120, help_text="Tytuł newsa", widget=forms.TextInput(attrs={"class": "form-control form-control-lg pr-5 shadow p-1 mb-1 bg-white rounded"}), required=True) class Meta: model = Article fields = ('title', 'image', 'category', 'snippet', 'body') widgets = { 'category': forms.CheckboxSelectMultiple() } labels = { 'category': 'Kategorie', } Also I made template to display this form. I used django cripsy-forms: HTML template <form method="post" enctype='multipart/form-data'> {% csrf_token %} {{ form.media }} {# {% crispy form %}#} {# {{ form|crispy }}#} {{ form.title|as_crispy_field }} {{ form.image|as_crispy_field }} {{ form.category|as_crispy_field }} <-- HOW DISPLAY THIS INLINE? {{ form.snippet|as_crispy_field }} {{ form.body|as_crispy_field }} <button type="submit" class="btn btn-outline-primary">EDIT</button> How can I display category checkboxes inline? -
Django Models - Relationship between siblings through a child
How can I list MyModelB objects for each MyModelA, when thier relations are not direct, but through MyModelC like below. name = models.CharField(max_length=50) class MyModelB(models.Model): name = models.CharField(max_length=50) class MyModelC(models.): name = models.CharField(max_length=50) my_model_a = models.ForeignKey(MyModelA, on_delete=models.CASCADE) my_model_b = models.ForeignKey(MyModelB, on_delete=models.CASCADE)``` -
How to allow the user to crop their profile image in django
I am trying to use django-image-cropping to allow users to crop their profile images before uploading them. Following the docs, I have installed it with pip along with easy_thumbnails and have added both to my installed apps and adjusted the thumbnail processors. settings.py: INSTALLED_APPS = [ 'easy_thumbnails', 'image_cropping', ] from easy_thumbnails.conf import Settings as thumbnail_settings THUMBNAIL_PROCESSORS = ( 'image_cropping.thumbnail_processors.crop_corners', ) + thumbnail_settings.THUMBNAIL_PROCESSORS I have also added an ImageRatioField to my Profile model which also contains the image I want to be cropped. models.py: from django.db import models from image_cropping import ImageRatioField class Profile(models.Model): image= models.ImageField(blank=True, null=True, default='profile_pics/default.png', upload_to='profile_pics') cropping = ImageRatioField('image', '300x300') I then integrated ImageCroppingMixin to my ModelAdmin. admin.py: from django.contrib import admin from image_cropping import ImageCroppingMixin class ProfileAdmin(ImageCroppingMixin, admin.ModelAdmin): pass admin.site.register(Profile, ProfileAdmin) My users can update their profiles via a modal which is rendered from ProfileModelForm... forms.py: class ProfileModelForm(forms.ModelForm): class Meta: model = Profile fields = ('first_name', 'last_name', 'image') ...and my_profile_view. views.py: def my_profile_view(request): profile = Profile.objects.get(user=request.user) form = ProfileModelForm(request.POST or None, request.FILES or None, instance=profile) if request.method == 'POST': if form.is_valid(): form.save() context = { 'profile': profile, 'form': form, } return render(request, 'users/my_profile.html', context) Here is the modal in my template: <button data-toggle="modal" data-target="#update" type="submit">Edit Profile</button> <div … -
How to do a translator in an invented language?
I am currently coding my first website, which is a translator in an invented language. You input a random phrase and it should get translated in the invented language. Here's the code for the translation: class TranslatorView(View): template_name= 'main/translated.html' def get (self, request, phrase, *args, **kwargs): translation = "" for letter in phrase: if letter.lower() in "a": if letter.isupper(): translation = translation + "U" else: translation = translation + "u" elif letter.lower() in "t": if letter.isupper(): translation = translation + "A" else: translation = translation + "a" elif letter.lower() in "c": if letter.isupper(): translation = translation + "G" else: translation = translation + "g" elif letter.lower() in "g": if letter.isupper(): translation = translation + "C" else: translation = translation + "c" return render(request, 'main/translator.html', {'translation': translation}) def post (self, request, *args, **kwargs): phrase = request.POST.get('text', 'translation') translation = phrase context = { 'translation': translation } return render(request,self.template_name, context) Template where you input the phrase: {% extends "base.html"%} {% block content%} <form action="{% url 'translated' %}" method="post">{% csrf_token %} <div class="form-group"> <center><h2 class = "display-3">TRANSLATE YOUR DNA CHAIN</h2></center> <br> <br> <textarea class="form-control" name='text' id="exampleFormControlTextarea1" rows="6"></textarea> <br> <button type='Submit' class= "btn btn-primary btn-lg btn-block">Translate</button> </div> </form> {% endblock content %} Template where … -
redirect, can't leave login page
in my views.py I have this function for login, def login_view(request, *args, **kwargs): form = AuthenticationForm(request, data=request.POST or None) if form.is_valid(): user_ = form.get_user() login(request, user_) **return redirect("/")** context = { "form": form, "btn_label": "Login", "title": "Login" } return render(request, "accounts/auth.html", context) however when i try to change the redirect , i only get errors, what should I put in the redirect? i've tried everything like return redirect("/tweets/list.html") and return redirect("public/index.html") both are locations of file names in the templates folder. I am getting the error, "Page not found (404)". The only address that did redirect was when I put https://www.google.com/ thnx -
Insert foreign key using django marshmallow
serializer.py class ClientSerializer(Schema): id = fields.Integer() name = fields.String(required=True, validate=lambda x: len(x) > 0) created_at = fields.DateTime() updated_at = fields.DateTime() class ProjectSerializer(Schema): id = fields.Integer() name = fields.String(required=True, validate=lambda x: len(x) > 0) project_type = EnumField(ProjectType, by_value=True) status = EnumField(ProjectStatus, by_value=True) client = fields.Nested(ClientSerializer(), dump_only=True) views.py project_serializer = ProjectSerializer(data=request.data) project_serializer.is_valid(raise_exception=True) Request { "name": "Test 1", "client": "Test Client" } models.py class Project(TenantBaseModel): name = models.TextField() project_type = EnumChoiceField(ProjectType, choice_builder=attribute_value) status = EnumChoiceField(ProjectStatus, choice_builder=attribute_value, default=ProjectStatus.CREATED) client = models.ForeignKey(Client, on_delete=models.PROTECT) I have already created a Client with the name "Test Client" using Django admin. I've tried passing the ID but nothing seems to work instead of the client name. I get the following error, {'client': [ErrorDetail(string='Unknown field.', code='invalid')]} -
Bootstrap base navs in django for loop
I am trying to use base navs of bootstrap in django using for loop to display the summary and profile of book based on the book id. I am getting "Could not parse the remainder: '()' from 'book.objects.all()'" error. Please let me know if there is any other way to fix this. Can anyone please hint me how to go ahead? book_review.html:- {% extends 'books/base.html' %} {% block content %} <div class = "container"> <ul class = "nav nav-tabs" id = "myTab" role = "tablist"> <li class = "nav-item"> <a class = "nav-link active" id = "summary-tab" data-toggle = "tab" href = "#summary" role = "tab" aria-controls = "summary" aria-selected = "true">Summary</a> </li> <li class = "nav-item"> <a class = "nav-link" id = "profile-tab" data-toggle = "tab" href = "#profile" role = "tab" aria-controls = "profile" aria-selected = "false">Profile</a> </li> <li class = "nav-item"> <a class = "nav-link" id = "relatedbooks-tab" data-toggle = "tab" href = "#relatedbooks" role = "tab" aria-controls = "relatedbooks" aria-selected = "false">Related Books</a> </li> </ul> <div class = "tab-content" id = "myTabContent"> <div class = "tab-pane fade show active" id = "summary" role = "tabpanel" aria-labelledby = "summary-tab"><br><br> {% for booksummary in book.objects.all() %} {{booksummary.summary}} {% … -
How to send extra data to serializers in django?
I have these models class Patient(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Doctor(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Visit(models.Model): patient = models.ForeignKey( 'Patient', on_delete=models.CASCADE, ) doctor = models.ForeignKey( 'doctor.Doctor', on_delete=models.CASCADE, ) date = models.DateField(auto_now=False, auto_now_add=False) time = models.TimeField(auto_now=False, auto_now_add=False) title = models.CharField(max_length=100) detail = models.TextField() And this serializer: class VisitSerializer(serializers.ModelSerializer): class Meta: model = Visit fields = '__all__' And I queried patient and doctor from db in views and want to send them to serializer: @api_view(['POST', ]) @permission_classes((IsAuthenticated, )) def add_visit_view(request, doctor_pk): try: patient = Token.objects.get(key=request.auth.key).user doctor = Doctor.objects.get(pk=doctor_pk) except Patient.DoesNotExist: return Response(data={'error': 'patient does not exist.'}, status=status.HTTP_404_NOT_FOUND) except Doctor.DoesNotExist: return Response(data={'error': 'doctor does not exist.'}, status=status.HTTP_404_NOT_FOUND) user = request.user if patient != user: return Response({'error': 'user and patient do not match'}, status=status.HTTP_400_BAD_REQUEST) context = { 'doctor': doctor, 'patient': patient } serializer = VisitSerializer(data=request.data, context=context) data = {} if serializer.is_valid(): patient = serializer.save() data['message'] = 'visit added successfully' else: data = serializer.errors return Response(data) I know I have to send extra data using context field but how to set them in serializer I overwrited create method like this: def create(self, validated_data): visit = Visit( patient=self.context['patient'], doctor=self.context['doctor'], date=self.validated_data['date'], time=self.validated_data['time'], title=self.validated_data['title'], detail=self.validated_data['detail'] ) visit.save() return visit But when I send request it says … -
Chart of price changes in Django
I want to save the new price and update date every time I change the price of the product, I created a new model for this and every time this change is saved in my model through the signal. I have a problem, if I change the name or number or ... of the product, these changes will be recorded in my model, I want the changes to be saved only when I change the price because the duplicate prices in the price change chart Occurs. my product model: class Product(models.Model): name = models.CharField(max_length=300) update = models.DateTimeField(auto_now=True) unit_price = models.PositiveIntegerField(default=0) create = models.DateTimeField(auto_now_add=True) .... my chart model : class Chart(models.Model): name = models.CharField(max_length=100, blank=True, null=True) create = jmodels.jDateTimeField(blank=True, null=True) update = jmodels.jDateTimeField(blank=True, null=True) unit_price = models.PositiveIntegerField(default=0, blank=True, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='pr_update') my signal : def product_post_saved_receiver(sender, instance, created, *args, **kwargs): product = instance variations = product.pr_update.all() if variations.count() < 100: Chart.objects.create(product=product, name=product.name, create=product.create, unit_price=product.unit_price, update=product.update) post_save.connect(product_post_saved_receiver, sender=Product) -
How to add django-wiki to Wagtail
I want to add django-wiki to my wagtail app, so I can modify with the editor like any webpage that I already have in wagtail. I do not know if that if possible. -
How to set SameSite None value in django settings
I tried to add samesite=none in the Django settings file. In the cookie is set samesite=none value but the Django app is not redirecting page. how to fix this issue. Settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django_cookies_samesite.middleware.CookiesSameSite', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'cp.middleware.ViewName', 'cp.middleware.GetCompany', 'cp.middleware.TimezoneMiddleware' ] SESSION_COOKIE_SAMESITE = 'None' How to solve this issue. If my question is could not understand. can you please check this link(https://community.shopify.com/c/Shopify-APIs-SDKs/SameSite-Cookie-with-Python-Django-and-the-Embedded-App-SDK/m-p/660233#M44775) Someone asked a question this question I will be asking and he has given some solution that also I tried but it's not working for me.can you please give some other solution. My Djanog Version: 2.0.2 My Python Version: Python 3.6.4