Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Insert data from SQL file in Django DB
I'm working on a Django Project, and I have all my datas in .sql files. I want to insert all of them in my Database. Can I use the python shell to do it ? Or should I use another method ? -
How to remove some items form queryset depending on @property?
I don't know how to remove results from a queryset without using .exclude(). I want to filter the result if the argument is_active is passed as a parameter of my search based on the result of the property is_active. My model with the calculated property 'is_active': class Discount(models.Model): name = models.CharField(_("name"), max_length=255) date_start = models.DateField(_("Date start"), null=True, blank=True) date_end = models.DateField(_("Date end"), null=True, blank=True) [...] @property def is_active(self): if self.date_start and self.date_end: return self.date_start <= date.today() <= self.date_end return True My viewset: class DiscountViewSet(viewsets.ModelViewSet): """ A simple ViewSet for listing or retrieving discounts. """ permission_classes = [CustomDjangoModelPermission] filter_backends = [DjangoFilterBackend] filter_fields = '__all__' def get_serializer_class(self): if hasattr(self, 'action') and self.action in ['list', 'retrieve']: return DiscountListSerializer return DiscountSerializer def get_queryset(self): if self.request.user.is_staff: return Discount.objects.all().prefetch_related('products') \ .prefetch_related('machines').prefetch_related('categories') else: return Discount.objects.all().prefetch_related('products') \ .filter(machines__site__client__in=self.request.user.profil.client.all()) \ .prefetch_related('machines').prefetch_related('categories') @swagger_auto_schema(manual_parameters=[height, width], responses={200: DiscountListSerializer}) def list(self, request): height = self.request.query_params.get('height') width = self.request.query_params.get('width') queryset = self.get_queryset() queryset = self.filter_queryset(self.get_queryset()) active_filter = request.data.get('is_active') if active_filter: for item in qs: if not item.is_active: ???? // remove item if height and width: for discount in queryset: if discount.menu_photo: discount.menu_photo = generate_thumbnail(discount.menu_photo, width, height) if discount.standby_photo: discount.standby_photo = generate_thumbnail(discount.standby_photo, width, height) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, … -
Issue with CSS file in Django
Trying to load a css file into my base.html file. When I load the webpage, it is not updating the webpage with the css styling I loaded. Everything is running as expected, 0 issues when I activate it in terminal. -
How to add multiple forms in one page using django formset
Using Django formset, you can add multiple forms at once on one page. However, two problems arose. Googling for a few days doesn't solve it. [forms.py] from django import forms from django.forms import modelformset_factory, ModelForm, DateTimeInput, Select from .models import Supporting SupportingModelFormset = modelformset_factory( Supporting, fields=('date', 'student', 'kinds', 'post_hour', 'teacher', 'comment', 'technician'), extra=1, widgets={'date': forms.DateTimeInput(format=('%Y-%m-%d %H:%M'), attrs={'name': 'date', 'id': 'date', 'autocomplete': 'off', 'class': 'form-control col-sm-12 date'}), 'student': forms.Select(attrs={'id': 'student', 'name': 'student', 'class': 'chosen'}), 'kinds': forms.Select(attrs={'id': 'kinds', 'name': 'kinds'), 'post_hour': forms.TextInput(attrs={'type': 'text', 'class': 'form-control col-sm-3', 'name': 'post_hour', 'placeholder': 'hr'}), 'cteacherrc': forms.TextInput(attrs={'type': 'text', 'class': 'form-control col-sm-12', 'name': 'teacher'}), 'comment': forms.TextInput(attrs={'class': 'form-control position-relative', 'name': 'comment', 'rows': '4'}) } ) [views.py] def add_supporting(request): if request.method == 'GET': formset = SupportingModelFormset(queryset=Supporting.objects.none()) elif request.method == 'POST': formset = SupportingModelFormset(request.POST) if formset.is_valid(): for form in formset: form.save() return redirect('supporting_list') return render(request, 'supporting/add.html', {'formset': formset}) [supporting/add.html] <form class="form-horizontal" method="POST" action=""> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="row form-row spacer mt-4"> <div class="form-group row"> <label>{{form.date.label}}</label> <div class="input-group"> {{form.date}} </div> </div> <div class="form-group row"> <label>{{form.student.label}}</label> <div class="input-group"> {{form.student}} </div> </div> <div class="form-group row"> <label>{{form.kinds.label}}</label> <div class="input-group"> {{form.kinds}} </div> </div> <div class="form-group row"> <label>{{form.post_hour.label}}</label> <div class="input-group"> {{form.post_hour}} </div> </div> <div class="form-group row"> <label>{{form.teacher.label}}</label> <div … -
How to put the product price with a ManyToManyField between Sellers and Products Table
I want a product price between two table Sellers and Products. Here are my models- class Products(models.Model): name = models.CharField(max_length=60) price= models.IntegerField(default=0) category= models.ForeignKey(Category,on_delete=models.CASCADE,default=1 ) description= models.TextField(blank=True, null= True) image= models.ImageField(upload_to='uploads/products/') def __str__(self): return self.name class Sellers(models.Model): name = models.CharField(max_length=60) products = models.ManyToManyField(Products) description= models.TextField(blank=True, null= True) image= models.ImageField(upload_to='uploads/sellers/') def __str__(self): return self.name Where to put the product price for each seller? -
FilterSelectMultiple | Django Form | widget | Django Template - Not able to see the form, return NoReverseMatch Error
I am trying to build a form, taking input through a FilterSelectMultiple field from Group model My urls.py looks like from django import views as django_views urlpatterns = [ # some other patterns url(r'^jsi18n/', django_views.i18n.JavaScriptCatalog.as_view(), name='javascript-catalog'), ] forms.py looks like from django import forms from django.contrib.auth.models import Group from django.contrib.admin.widgets import FilteredSelectMultiple class MyForm(forms.Form): """Form for assigning groups to new users.""" options = [(group_name, group_name) for group_name in Group.objects.all()] # other fields groups = forms.MultipleChoiceField(required=False,widget=FilteredSelectMultiple("Groups", is_stacked=False),choices=options) class Media: css = { 'all': ('/static/admin/css/widgets.css',), } js = ('/admin/jsi18n',) def __init__(self, *args, **kwargs): """Init.""" super(MyForm, self).__init__(*args, **kwargs) template looks like {% extends base.html %} {% block head %} {% load staticfiles %} some stuff {% endblock head %} {% block content %} <script type="text/javascript" src="{% url 'jsi18n' %}" > </script> {{ form.media }} <form enctype="multipart/form-data" method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Submit</button> </form> {% endblock content %} But I am getting error - NoReverseMatch Reverse for 'jsi18n' not found. 'jsi18n' is not a valid view function or pattern name -
Why is my Python for loop running out of memory?
I have a for loop in Python/Django to iterate over a long list of users and create recommendations for them using a saved tensorflow model: def create_recommendations_for_users(): user_ids = User.objects.values_list("id", flat=True) retrieval_model = tf.saved_model.load("tensorflow_models/model") ranking_model = tf.saved_model.load("tensorflow_models/ranking_model") for user_id in user_ids: create_recommendations_for_user(user_id, retrieval_model, ranking_model) def create_recommendations_for_user(user_id, retrieval_model, ranking_model): _, items = retrieval_model([user_id]) for item_id in items[0]: item_id = item_id.numpy() rating = ranking_model.ranking_model( (tf.constant([user_id]), tf.constant([item_id])) ).numpy() Recommendation.objects.create(user_id=user_id, item_id=item_id, rating=rating) The issue is that calling create_items_for_users is causing a memory leak. Why would this happen? items is scoped to the create_items_for_user function, so wouldn't this be garbage collected, as would item_id and rating, each time it gets run? user_ids is a long list of integers, but doesn't grow over time and isn't all that large. I'm not storing a growing list of results anywhere. Why would these functions cause a memory leak? -
Populating a hidden field after form save
I am very new to Django and I wanted some guidance on building this. I have a form that works well right now, but I want to change a functionality. There is a hidden field that doesn't show on the form but is in the model, I want to be able to populate that hidden field based on an entry on the form. I've tried overriding the clean method in the view but that wasn't working. Any guidance would be appreciated, thanks! -
Django Import Export Strip White Space & Additional Condition
I'm using the Django Import and Export plugin and in my Admin.py I need to solve two problems. The excel file I'm uploading has white space at the end of the cells, I need to remove that. This import is uploading test scores, there is no test id in the import to determine if its a different test. However, there is a test date field. I need to be able to get the date field before the import of each row and analyze it to determine if this is an update of the current test data or make a new record signaling this was a different test. I appreciate the help. Here is my admin.py class MindResource (resources.ModelResource): state_province = fields.Field(column_name='state_province', attribute='state_province',widget=ForeignKeyWidget(Student, 'state_province')) def import_row(self, row, instance_loader, **kwargs): # OVERRIDE ERROR TO IMPORT RECORDS (STOPS FAILURE OF IMPORT) import_result = super(MindResource, self).import_row(row, instance_loader, **kwargs) if import_result.import_type == RowResult.IMPORT_TYPE_ERROR: # COPIES VALUES TO DISPLAY ON THE REPORT import_result.diff = [row[val] for val in row] # ADD COLUMN WITH ERROR MESSAGE import_result.diff.append('Errors: {}'.format([err.error for err in import_result.errors])) # CLEAR ERRORS AND MARK TO SKIP import_result.errors = [] import_result.import_type = RowResult.IMPORT_TYPE_SKIP return import_result class Meta: model = Mind clean_model_instances = True import_id_fields = … -
Django Abandoned/Unused Models
I have a models.py file with 6-10 unused models on a Django Project. What do you do with these unused models? Do you delete them (and migrate them out)? Do you just push them to the side and ignore them? -
Present Python variable in HTML Template in Django
I have a value extracted from JIRA API showing a total for a particular project. When I print the value, I can see the correct values and these are clearly being stored in the variable. # Emergency Changes Query jira_emergency_changes = jira.search_issues('labels = new-emerging-audit AND resolution = Unresolved').total # Open Issues Query jira_open_issues = jira.search_issues('project = UTILITY AND status = Open').total # Open JIRA Ticket Total Query jira_open_tickets = jira.search_issues('project = "UTILITY" AND status not in (Closed, Completed, Resolved) ORDER BY created DESC').total I want to add these values to a template page in a <p> tag, but no matter what method I try, it just doesn't render. Could some advice? :) -
ssl error with copying file in s3 server?
I tried to collect static files on the S3 Server for my Django project with the command : python manage.py collectstatic But It failed because of SSLError : During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\botocore\httpsession.py", line 414, in send chunked=self._chunked(request.headers), File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\connectionpool.py", line 756, in urlopen method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2] File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\util\retry.py", line 507, in increment raise six.reraise(type(error), error, _stacktrace) File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\packages\six.py", line 769, in reraise raise value.with_traceback(tb) File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\connectionpool.py", line 706, in urlopen chunked=chunked, File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\connectionpool.py", line 382, in _make_request self._validate_conn(conn) File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\connectionpool.py", line 1010, in _validate_conn conn.connect() File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\connection.py", line 421, in connect tls_in_tls=tls_in_tls, File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\util\ssl_.py", line 450, in ssl_wrap_socket sock, context, tls_in_tls, server_hostname=server_hostname File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\urllib3\util\ssl_.py", line 493, in _ssl_wrap_socket_impl return ssl_context.wrap_socket(sock, server_hostname=server_hostname) File "C:\Users\Anthony\AppData\Local\Programs\Python\Python37\lib\ssl.py", line 423, in wrap_socket session=session File "C:\Users\Anthony\AppData\Local\Programs\Python\Python37\lib\ssl.py", line 870, in _create self.do_handshake() File "C:\Users\Anthony\AppData\Local\Programs\Python\Python37\lib\ssl.py", line 1139, in do_handshake self._sslobj.do_handshake() urllib3.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1091) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\Anthony\Documents\website_django\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute … -
django get related names for object
we can access to an object's all field by __dict__ class Profile(models.Model): chips = models.PositiveIntegerField(default=0) user = models.OneToOneField(User, on_delete=models.CASCADE) desc = models.CharField(max_length=255, default='', blank=True, null=True) image = models.ImageField(default='profile/default.jpg', upload_to='profile') active = models.BooleanField(default=False) points = models.PositiveIntegerField(default=0) createTime = models.DateTimeField(default=now, editable=False) email = models.EmailField(blank=True, null=True) Profile.objects.all()[0].__dict__ """ { '_state': <django.db.models.base.ModelState object at 0x7fe6d9632390>, 'id': 1, 'chips': 100000, 'user_id': 1, 'desc': None, 'image': 'profile/default.jpg', 'active': False, 'points': 100010, 'createTime': datetime.datetime(2022, 3, 13, 13, 45, 57, 513699, tzinfo=<UTC>), 'email': None } """ But does not include reference from ForeignKey, OneToOneField and ManyToManyField, that was defined on other models that has a related name. for example class Article(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="articles") # __dict__ of Profile object does not include articles is there a way I can get all callable attributes of database from the model. thanks very much. -
Django - Update a model field through a form
I have this model which represents the values users submit through a form when making an applying for sponsorship. class ApplicationData(models.Model) : class Status(models.TextChoices): REJECTED = 'Rejected' PENDING = 'Pending' ACCEPTED = 'Accepted' """Define table for Applications in database""" user = models.ForeignKey(User, on_delete=models.DO_NOTHING) organisationName = models.CharField(max_length=200, null=True, blank=True) projectTitle = models.CharField(max_length=200, null=True, blank=True) CH_OSCR_number = models.CharField(max_length=20, unique=True, blank=True, null=True, ) projectDesc = models.TextField(max_length=300, null=True, blank=True) userGroupDesc = models.TextField(max_length=300, null=True, blank=True) learningOpp = models.TextField(max_length=300, null=True, blank=True) keyPartnersWork = models.TextField(max_length=300, null=True, blank=True) projImpactClimate = models.TextField(max_length=300, null=True, blank=True) projSupportLocBus = models.TextField(max_length=300, null=True, blank=True) proContribution = models.TextField(max_length=300, null=True, blank=True) length = models.IntegerField(null=True, blank=True) application_complete = models.BooleanField(default=False) date_of_application = models.DateField(null=True, blank=True) reviewed = models.BooleanField(default=False) app_status = models.TextField(choices = Status.choices, default = Status.PENDING) On the system there are 3 different user types. Once an applicant submits an application the staff users can view the submitted application details on a dedicated page. What I'm trying to do is to add a form on that page where the staff will have the ability to change the status of the application (app_status on the model). Here are my efforts: Here the is the form to update the field. class UpdateAppStatus(forms.ModelForm): class Meta: model = ApplicationData fields = ('app_status',) labels … -
How to have a ManyToManyField with two tables Sellers and Products
I have a Products Table class Products(models.Model): name = models.CharField(max_length=60) price= models.IntegerField(default=0) How to proceed with ManyToManyField between Sellers and Products -
TypeError: cannot use a string pattern on a bytes-like object python3
I have updated my project to Python 3.7 and Django 3.0 Here is code of models.py def get_fields(self): fields = [] html_text = self.html_file.read() self.html_file.seek(0) # for now just find singleline, multiline, img editable # may put repeater in there later (!!) for m in re.findall("(<(singleline|multiline|img editable)[^>]*>)", html_text): # m is ('<img editable="true" label="Image" class="w300" width="300" border="0">', 'img editable') # or similar # first is full tag, second is tag type # append as a list # MUST also save value in here data = {'tag':m[0], 'type':m[1], 'label':'', 'value':None} title_list = re.findall("label\s*=\s*\"([^\"]*)", m[0]) if(len(title_list) == 1): data['label'] = title_list[0] # store the data fields.append(data) return fields Here is my error traceback File "/home/harika/krishna test/dev-1.8/mcam/server/mcam/emails/models.py", line 91, in get_fields for m in re.findall("(<(singleline|multiline|img editable)[^>]*>)", html_text): File "/usr/lib/python3.7/re.py", line 225, in findall return _compile(pattern, flags).findall(string) TypeError: cannot use a string pattern on a bytes-like object How can i solve my issue -
Signing up users returning no attribute action error
I have an API handling the login and signup process (Django to React front end). While users can login, receiving an access and refresh token when I point towards the signup endpoint I get the error 'RegisterApi' object has no attribute 'action' Here is a breakdown of my code api.py: from rest_framework import generics, permissions, mixins from rest_framework.response import Response from .serializers import RegisterSerializer, UserSerializer from django.contrib.auth.models import User from rest_framework.permissions import AllowAny #Register API class RegisterApi(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "message": "User Created Successfully. Now perform Login to get your token", }) #allow for anonymous signup def get_permissions(self): if self.action == 'create': return [AllowAny()] else: return super().get_permissions() def get_authenticators(self): if self.action == 'create': return [] else: return super().get_authenticators() serializers.py from django.contrib.auth.models import User from rest_framework import serializers #added more imports based on simpleJWT tutorial from rest_framework.permissions import IsAuthenticated from django.db import models from django.contrib.auth import authenticate from django.contrib.auth.hashers import make_password #changed from serializers.HyperLinked to ModelSerializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User #removed url from fields fields = ['username', 'email', 'password'] extra_kwargs = { 'password': {'write_only': True}, } def create(self,validated_data): user = User.objects.create_user(validated_data['username'], … -
Django custom admin filter: get filtered queryset before the current filter itself is applied
I have a classic admin.SimpleListFilter. I would want to get the current filtered/displayed queryset, but before my own filter is applied, so I can show the result count for each of my filter lookups. The current code below always shows total counts of each lookup, not respecting eventual other selected filters. class ByAssignementStatusFilter(admin.SimpleListFilter): title = _('Assignement Status') parameter_name = 'status__exact' def lookups(self, request, model_admin): choices = [] qs = model_admin.get_queryset(request) # qs.count() is always the unfiltered amount for key, label in Assignement.STATUS_CHOICES: count = qs.filter(assignement__status=key).count() label = f"{label} ({count})" choices.append((key, label)) return choices def queryset(self, request, queryset): if self.value() is not None: return queryset.filter(assignement__status=self.filter_value) else: return queryset -
How to deserializer two Models in django?
i'm sending two serializer models to api.py file... it is sending successfully but how to de-serializer both models in api.py views.py from django.http import HttpResponse, response from api.serializer import ResultsDNSerializer, ClassesExamMaxMarksSerializer, ResultSerializer, BlogPostsSerializer from rest_framework.renderers import JSONRenderer def ShowStudentResultAPI(request, id,eid): # Here id is Unique id of ResultDelcareNotice's Model and eid is ePunjabID of student Result_Delcare_Data = ResultsDeclareNotice.objects.filter(ID=id).first() Get_SessionCode = Result_Delcare_Data.SessionCode Get_AnnResultCode = Result_Delcare_Data.AnnResultCode Get_MonthCode = Result_Delcare_Data.MonthCode # Here AnnualResults is Model and here just we are fetching data stu_Data = AnnualResults.objects.get(SessionCode=Get_SessionCode,AnnResultCode=Get_AnnResultCode,MonthCode=Get_MonthCode,EID=eid) ResultDataTerm1 = AnnualResults.objects.filter(SessionCode=Get_SessionCode,AnnResultCode=Get_AnnResultCode,MonthCode=Get_MonthCode,EID=eid).first() StudentClassTerm1 = ResultDataTerm1.ClassCode Class_MaxMarksData = ClassesExamMaxMarks.objects.get(SessionCode=Get_SessionCode, ClassCode=StudentClassTerm1,AnnResultCode=Get_AnnResultCode) serializer = ResultSerializer(stu_Data) json_data = JSONRenderer().render(serializer.data) serializer_class_marks = ClassesExamMaxMarksSerializer(Class_MaxMarksData) json_data_class_marks = JSONRenderer().render(serializer_class_marks.data) Serializer_list = [json_data, json_data_class_marks] return HttpResponse(Serializer_list) import requests URL = "http://localhost:8000/api/result/1/4474239/" req = requests.get(url = URL) data = req.text print(data) -
Django ORM filter model where all relation have value equals to
Lets say that I have two models: class Worker(models.Model): name = models.CharField(max_length=100) class Task(models.Model): worker = models.ForeignKey(Worker) name = models.CharField(max_length=100) I would like to retrieve all workers where ALL tasks are called "dig". But I dont want workers that have only one Task called "dig". I've tried using filter and exclude with Q, like this: Worker.objects.filter(task__name='dig').exclude(~Q(task__name='dig')) But it didn't work, it don't remove those that have only one task like that. I could iterate over worker and tasks to find it, but is there any way to make this query using only orm? -
Django for each form input has its error message below it
I want to add error message for each input not all messages below each others if there is more than one message any help ? context = { 'error': False } if not email: messages.add_message(request, messages.ERROR, "Enter an Email", extra_tags='not_email') context['error'] = True I tried using extra_tags but also it viewed all the messages -
Django channels + Postgresql: Real-Time Database Messaging
I am currently developing an app with Django and PostgreSQL. Often, new information is sent to database (sometimes one time a day, sometimes over 30000 times a day). I have an UI (vue.js) and I want to see the data from the database showing to the client in real time. Currently I am using Django Channels. I implemented websocket and used psycopg2 library to listen to notifications from postgresql triggers. My consumer looks like this: class WSConsumer(WebsocketConsumer): def connect(self): self.accept() #the whole table is sent to the client after the connection self.send(json.dumps(ClientSerializer(Client.objects.all(), many=True).data)) #connecting to database conn = psycopg2.connect(dbname='...', user='...') conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) curs = conn.cursor() curs.execute("LISTEN update_clients_table;") #then I listen to any new data in this table and send it to the client while True: if select.select([conn],[],[],5) == ([],[],[]): print("Timeout") else: conn.poll() while conn.notifies: notify = conn.notifies.pop(0) print("Got NOTIFY:", notify.pid, notify.channel, notify.payload) message = notify.payload self.send(message) def disconnect(self): self.close() This is an example of handling changes in 1 table. I have 20 tables in total, and around 100 clients that can connect to the websocket. My question: is it a good way of building real-time app with Django and PostgreSQL? Is it simple, convenient, secure? Are there other ways to build … -
Could not parse the remainder: '(0,10)' from 'range(0,10)' with python
I have a problem with my template especially at the line: {% for j in range(0,10) %} I get the error: Could not parse the remainder: '(0,10)' from 'range(0,10)' -
how do I save form data from a different url template
how do I not save the form data until the transaction is done which is in a different URL, if the shipping form and the payment options were to be in the same URL then there wouldn't be this problem but it's not so how do I go about this? thx! views.py def checkout(request): if request.method == 'POST': form = ShippingForm(request.POST) if form.is_valid(): new_shipping = form.save(commit=False) new_shipping.customer = customer new_shipping.order = order #how do I not save the data until the transaction is successful new_shipping.save() return redirect('store:checkout_shipping') else: form = ShippingForm() else: form = ShippingForm() context = {"form": form} return render(request, 'shop/checkout.html', context) def checkout_payment(request): return render(request, 'shop/checkout_payment.html', context) urls.py path('checkout', views.checkout, name="checkout"), path('checkout_payment', views.checkout_payment, name="checkout_payment"), forms.py class ShippingForm(forms.ModelForm): address_one = forms.CharField(max_length=200) address_two = forms.CharField(max_length=200) -
Django favourite permission
how to configure permissions to receive favorites only of the user who added, and the favorites of other users could not be read models.py class Task(models.Model): user_info = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, name='userInfo') title = models.CharField(max_length=100) text = models.TextField(max_length=10000) class Favourite(models.Model): task_id = models.ForeignKey(Task, on_delete=models.CASCADE, blank=True, null=True, related_name='favourites',name='taskId') user_info = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, name='userInfo') views.py class FavouriteUserView(generics.ListAPIView): serializer_class = FavouriteReceivingSerializer pagination_class = MyCursorPagination permission_classes = (IsAuthor,) def get_queryset(self): return Favourite.objects.filter( userInfo_id=self.kwargs.get('pk')).select_related('userInfo').order_by('userInfo_id') permissions.py class IsAuthor(BasePermission): def has_permission(self, request, view): if request.method in SAFE_METHODS: return True return request.user and request.user.is_authenticated def has_object_permission(self, request, view, obj): return obj.userInfo == request.user