Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nonetype check in django conditional expressions
Let's say we have two models, as below: class DefaultDescription(models.Model): first_attr = models.IntegerField() second_attr = models.CharField(max_length=20) description = models.CharField(max_length=100) class SomeEntity(models.Model): first_attr = models.IntegerField() second_attr = models.CharField(max_length=20) # and some other unimportant attributes... @property def description(self): try: return DefaultDescription.objects.get(first_attr=self.first_attr, second_attr=self.second_attr).description except DefaultDescription.DoesNotExist: return '' What I want to do is to write a single query for SomeEntity to fetch all of the descriptions. As you can see, the description property will run a queryset, which means a queryset for each entity. So I've tried some queryset like this: class DescriptionAnnotationQS(models.QuerySet): def annotate_descriptions(self): self.annotate( desc=models.Case( models.When( DefaultDescription.objects.filter( first_attr=models.F('first_attr'), second_attr=models.F('second_attr')).exists(), then=models.Value(DefaultDescription.objects.get( first_attr=models.F('first_attr'), second_attr=models.F('second_attr')).description)), default=models.Value('') ) ) I used Case and When to check if there wasn't any default description for the entity. But still I get DoesNotExist exception! I thought then section will not be executed unless the condition returns True. Is there any way to annotate SomeEntity with description with none type check? P.S: I get this problem from a legacy code which I'm not allowed to establish relations between models. -
Please how do I fix this SMTPConnectError Error?
I am trying to send an email to a user to verify his/her account via an activation link, however when I try to register a user I get the error below. I tried using the send_mail method but it still gives the same error. Please any help will be much appreciated. My Error Traceback (most recent call last): File "C:\Users\Donald\PycharmProjects\to_doApp\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Donald\PycharmProjects\to_doApp\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Donald\PycharmProjects\to_doApp\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\Donald\PycharmProjects\to_doApp\store\accounts\views.py", line 44, in register send_email.send() File "C:\Users\Donald\PycharmProjects\to_doApp\venv\lib\site-packages\django\core\mail\message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "C:\Users\Donald\PycharmProjects\to_doApp\venv\lib\site-packages\django\core\mail\backends\smtp.py", line 102, in send_messages new_conn_created = self.open() File "C:\Users\Donald\PycharmProjects\to_doApp\venv\lib\site-packages\django\core\mail\backends\smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "C:\Users\Donald\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 258, in __init__ raise SMTPConnectError(code, msg) Exception Type: SMTPConnectError at /accounts/register/ Exception Value: (421, b'service not available (connection refused, too many connections)') My views.py @csrf_exempt def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] phone_number = form.cleaned_data['phone_number'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] username = email.split('@')[0] user = Account.objects.create_user(first_name=first_name, last_name=last_name, email=email, username=username, password=password) user.phone_number = phone_number # USER ACTIVATION WITH TOKEN TO EMAIL ACCOUNT current_site = get_current_site(request) … -
how to activate virtual env in vs code?
I cant activate virtual env in vs code. I tried same code in the cmd console is work but not in the vs code terminal. "D:\python\djangoapp\djangovenv\Scripts\activate.bat" I write this code. I am using windows 10 pro -
how to validate access token and redirect user if expired to refreshtoen view in simple jwt authentication with django rest framework
How can i redirect user to obtain new access token in refresh token view if access token is expired ? i implemented cookie based authentication with simple jwt library in django rest framework. refresh token and access token are finely generated. But i have to verify the token for example if a user logged in, he recieved an access token . and when he is trying to add a new post. i have to firstly verify if the access token is not expired. if not expired then he could add the post, otherwise i will regnerate a new access token based on his refresh token already received. Views.py class LoginView(APIView): def post(self, request, format=None): data = request.data response = Response() email = data.get('email', None) password = data.get('password', None) user = authenticate(email=email, password=password) if user is not None: if user.is_active: data = get_tokens_for_user(user) response.set_cookie( key = settings.SIMPLE_JWT['AUTH_COOKIE'], value = data["access"], expires = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'], secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'], httponly = settings.SIMPLE_JWT['AUTH_COOKIE_HTTP_ONLY'], samesite = settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE'] ) csrf.get_token(request) response.data = {"Success" : "Login successfully","data":data} return response else: return Response({"No active" : "This account is not active!!"}, status=status.HTTP_404_NOT_FOUND) else: return Response({"Invalid" : "Invalid email or password!!"}, status=status.HTTP_404_NOT_FOUND) authenticate.py from rest_framework_simplejwt.authentication import JWTAuthentication from django.conf import settings … -
Redirect route from ajax using class based view subclasses in Django
I'm curios and just got started learning about class based views in Django and I'm testing it with AJAX. The idea is to get the data from the object (1/get-report) and redirect from AJAX to url which will be rendered from subclass (show_report route below). This is what I have: urls.py path("<int:pk>/get-report", ShowReportForDevice.as_view(), name="daily-report"), path("show-report/", ShowGraphReport.as_view(), name="show-report"), views.py # Parent class class ShowReportForDevice(DetailView): model= ModbusDevice #queryset = ModbusDevice.objects.all() template_name= None checked_vars=[] dev_id=-1 def get(self, request, *args, **kwargs): if request.is_ajax(): # Data from client I want to be visible in the child class (methods) self.checked_vars= request.GET.getlist('myvars[]') #myvars= kwargs.get('myvars[]') # None self.dev_id= request.GET.get('dev_id') # response created: data={} data['redirect']='/show-report' data['success']=True return JsonResponse(data, status=200) # Child class class ShowGraphReport(ShowReportForDevice): template_name= 'modbus_app/report2.html' data={} # Q1: Do I need to overrided this method if I only need parent class attributes? # Q2: Is "context" variable parent attribute ? This function doesn't get called, but "get" is called def get_context_data(self, **kwargs): context = super(ShowGraphReport, self).get_context_data(**kwargs) context.update({ 'foodata': 'bardata', }) print(self.dev_id) print(self.checked_vars) return context # I must override in order to render template def get(self, request, *args, **kwargs): # Q3: How to get the "context" variable here? print(self.dev_id) # not updated still -1 print(self.data) # not updated still … -
DRF Django - make routable reverse foreign key relationship data
I have the following models # filename - stocks.models class Stock(models.Model): ticker = models.CharField(max_length=10, unique=True, primary_key=True) exchange = models.CharField(default="", max_length=10) name = models.CharField(default="", max_length=255) slug = models.SlugField(default="", editable=False) def save(self, *args, **kwargs): value = self.ticker self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) class Meta: verbose_name = "stock" verbose_name_plural = "stocks" ordering = ["ticker"] # filename - prices.models from viewflow.fields import CompositeKey class StockPrice(models.Model): id = CompositeKey(columns=["ticker_id", "date"]) ticker = models.ForeignKey( "stocks.Stock", on_delete=models.CASCADE, related_name="stocks" ) date = models.DateTimeField(default=now) open = models.FloatField() high = models.FloatField() low = models.FloatField() close = models.FloatField() adj_close = models.FloatField() volume = models.FloatField() the following view class StockViewSet(viewsets.ModelViewSet): queryset = Stock.objects.all() queryset = queryset.prefetch_related("stocks") serializer_class = StockSerializer lookup_url_kwarg = "ticker" lookup_field = "ticker__iexact" # override create method to include many=True def create(self, request, *args, **kwargs): serializer = self.get_serializer( data=request.data, many=isinstance(request.data, list) ) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response( serializer.data, status=status.HTTP_201_CREATED, headers=headers ) and the following routers router = routers.SimpleRouter() router.register(r"stocks", stock_views.StockViewSet, basename="stocks") stockprice_router = routers.NestedSimpleRouter(router, r"stocks", lookup="stocks") stockprice_router.register(r"price", price_views.StockPriceViewSet) urlpatterns = [ path("", include(router.urls)), path("", include(stockprice_router)) ] the router is from drf-nested-routers. How can I set up a url such as localhost:8000/stocks/appl/price/ that will show the reverse foreign key data ( models.StockPrice ) for specifically that stock aapl. … -
Django REST Framework : How to make a custom Validator to validate a combination of several fields at once?
I need to make a custom validator as below. But I can't find any way to retrieve the values of several fields, on which I need to check a condition. class MyCustomValidator(): def __call__(self, field_1, field_2): if condition_on_field_1_and_field_2 is True: message = 'my custom message' raise serializers.ValidationError(message) I saw in the Documentation that there is a way to provide context to a validator. But it seems to provide only one "serializer_field". Is there any way to retrieve more than one serializer field ? How would you do it? -
How to configure HTTPS for Django server on IIS 10
My client is developed using Vue and server using Django. We've hosted this on IIS 10. As for the SSL certificate we got from GoDaddy. I was successfully able to configure to the client. However when I run the app, I'm getting the following error. Mixed Content: The page at 'https://xxx.yyy.com/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://x.x.x.x:xxxx/yyyy/'. This request has been blocked; the content must be served over HTTPS. What I understand is that we need to configure the Django server to allow HTTPS. Need assistance on how to achieve the same. Thanks!! -
'PolymorphicQuerySet' object has no attribute 'provisioning_set'
I have some tables : class Site(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE, null=False) site_type = models.CharField(max_length=3, choices=SITE_TYPES, default=AIRCRAFT,) tailnumber = models.CharField(max_length=40, null=True, unique=True) customer_name = models.CharField(max_length=100, null=True) class Terminal(PolymorphicModel): created_at = models.DateTimeField(auto_now_add=True) site = models.ForeignKey(Site, on_delete=models.CASCADE, null=False) tracker = FieldTracker() class Provisioning(PolymorphicModel): terminal = models.ForeignKey(Terminal, on_delete=models.CASCADE, null=True) usergroup = models.ForeignKey(Usergroup, on_delete=models.CASCADE, null=False) threat_monitoring = models.BooleanField(null=False, default=False) I run a query: asset = Site.objects.get(id=site_id) In the debugger I get: terminal_set which return all related tables of the Terminal model so far good.... In the same terminal_set is in the provisoning_set , I try to query this object site.terminal_set.model.provisioning_set site.terminal_set.provisioning_set.model.first() This is the exact path! Why it response with 'PolymorphicQuerySet' object has no attribute 'provisioning_set' -
Geting a view based on pk using url pattern
Hay. I have a little trouble getting URL with the passed argument (pk). I get error in which I get post_edit that is to do with another app of the website so as a pattern it tried to use: NoReverseMatch at /questions/question/5/ Reverse for 'post_edit' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['blog/post/(?P[0-9]+)/edit/$'] Why doesn't it pass pk in questions_list.html in a for loop? urls.py from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('', views.questionMain_view, name='questionMain_view'), path('postQ/', views.postQ_view, name='postQ_view'), path('all/', views.displayQ_view, name='displayQ_view'), path('question/<int:pk>/', views.question_detail_view, name='question_detail_view'), ] questions_list.html {% extends 'questions_page/base_questions.html' %} {% load i18n %} {% block title %} {% translate 'Questions Main' %} {% endblock %} {% block content %} <h1>{% translate 'Questions display' %}</h1> <br> {% for question in questions %} <div> <div class="date"> {{ question.published_date }} </div> <h1><a href="{% url 'question_detail_view' question.pk %}">{{ question.title }}</a></h1> <p>{{ question.text|linebreaksbr }}</p> </div> {% endfor %} {% endblock %} questions_detail.html {% extends 'questions_page/base_questions.html' %} {% load i18n %} {% block title %} {% translate 'Questions detail' %} {% endblock %} {% block content %} <h1>{% translate 'Questions detail' %}</h1> <br> <div> {% if question.published_date %} <div class="date"> {{ question.published_date }} </div> … -
how to print data in Django views.py not in template?
Buddies i am new to django and i know how to get the data from the database and send to the template. But i am in a situation where i need to print the data from the database in views.py file order = Order.objects.get(user=request.user, ordered=False) context['object']=order return render(request,"Orderview.html",context) this order variable contains title,quantity,price of the product {% for order_item in object.items.all %} <tr> <td>1</td> <td><strong>{{ order_item.item.title }}<</strong><br>{{order_item.item.description }}</td> <td class="text-center">{{ order_item.quantity }}</td> <td class="text-right" id="price" >{{ order_item.item.price }}</td> <td class="text-right" id="discount ">{{ order_item.item.discount_price }}</td> <td class="text-right" id="subtotal_price">{{ order_item.item.price|subtract:order_item.item.discount_price }}</td> </tr> {% endfor %} this is how im able to send all the details to template **but i want to print all this details to the views.py console ** -
Django - How to use 'create' and 'update' together in a single Form/URL/View?
TrimType's Create and Update will be implemented together by modal in Car's DetailView. Car's DetailView TrimType's CreateView Modal TrimType's UpdateView Modal models.py : class Car(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, null=False, blank=False) class TrimType(models.Model): id = models.AutoField(primary_key=True) car = models.ForeignKey(Car, on_delete=models.SET_NULL, blank=True, null=True) typeName = models.CharField(max_length=50, blank=False, null=False) urls.py : app_name = 'brand' urlpatterns = [ ... url(r'^car/(?P<car_id>\d+)/$', car_views.CarDetailView.as_view(), name='car_detail'), # TrimType_id is transmitted by GET method. ... ] forms.py : class TrimTypeForm(forms.ModelForm): class Meta: model = TrimType fields = ('car', 'typeName') typeName = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control'}), label='TrimType' ) car_detail.html : <div class="col-8"> <div class="text-right mt-3 mb-3"> <select class="form-control" id="slct_trim_type"> <option value="0">*TrimType*</option> {% for trimType in trimType_list %} <option value="{{ trimType.id }}" data-car-idx="{{ car.id }}" {% if trimTypeID == trimType.id %}selected{% endif %}>{{ trimType.typeName }}</option> {% endfor %} </select> </div> </div> <div class="col-4"> <div class="text-right mt-3 mb-3"> <a id="btn_trimtype_add" class="btn btn-primary btn-icon waves-effect waves-themed" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo" title="" data-original-title="add"></a> <a id="btn_trimtype_modify" class="btn btn-info btn-icon waves-effect waves-themed" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo" title="" data-original-title="modify"></a> <a id="btn_trimtype_delete" class="btn btn-danger btn-icon waves-effect waves-themed" data-toggle="tooltip" title="" data-original-title="delete"></a> </div> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h3 class="modal-title">*TrimType* UpdateView</h3> <form method="post" class="form-horizontal" … -
Building an offline web system and updating the new versions remotely after entering data
I wanna create an offline web system that is working on a local server. the user can enter data offline and it will be saved locally. Then, the data will be synced to an online server whenever the internet is available. let me explain the steps a little bit more: 1- User can sign up to an account on a website. 2- After login the user can download an app to his/her device, which containing an offline web app with local database. 3- The user will use the local system to enter his data and organize it offline. 4- whenever the internet is available the data will be synced immediately. 5- if there is a new version of the system or the database the user can update the system without effecting on his entered data. so, my questions are: what is the best technologies(languages, DBs, etc.) to build such a system? how I can update the version and database without effecting the data? I have good experience on python, django, pyqt, etc. is python and its frameworks capable of building such a system. Thank you. -
Django pandas code work on local - not on a remote server (“KeyError”)?
I'm submitting a file through Django form and reading it with pandas which working fine on my local machine but ever since I deployed my code on remote I'm getting "KeyError" here is the code where I'm reading file file = request.FILES['titles_file'] global global_file global_file = pd.read_csv(file, header=0, encoding='unicode_escape') global_file.dropna(subset=['ASIN'],inplace=True) and the error I'm getting my csv file looks like this I have tried sep and skipinitialspace = True but no use -
In Dajngo how to perform crud operation with filefield and charfield with class based views
when I try to get the values in the get_initial() for filefields I am not able to do it so please any one can help me this. can I update few charfield data without re-saving pdf(if possible) How to handle removal of already existing files as of now I am able delete using os.remove, i am confused , I have tried to google it not finding proper solution I am posting it here views.py class SocietyView(FormView): template_name = 'add.html' form_class = Society def post(self, request, *args, **kwargs): try: c = {} c.update(csrf(request)) s_form = Society(request.POST, request.FILES) print(s_form) if not s_form.is_valid(): variables = {'form': s_form } messages.error(request, 'Invalid data in form') return render(request, self.template_name, variables ) a_req_file = request.FILES['a_file'] board_members_file = request.FILES['board_members'] by_laws_file = request.FILES['by_laws'] ammendments_file = request.FILES['ammendments'] fs = FileSystemStorage() s_id = s_form.cleaned_data['s_id'] name = s_form.cleaned_data['name'] soc_type = s_form.cleaned_data['soc_type'] address = s_form.cleaned_data['address'] contact = s_form.cleaned_data['contact'] election = s_form.cleaned_data['election'] # board_members = board_members_file # a_file = a_req_file.name # by_laws = by_laws_file # ammendments = ammendments_file if s_id == 999: (entry, created) = models.Society.objects.update_or_create(name= name, soc_type=soc_type, address = address, election=election, board_members = board_members_file, contact= contact, a_file=a_req_file, by_laws=by_laws_file, ammendments=ammendments_file) else: (entry, created) = models.Society.objects.update_or_create(id=s_id, defaults={ 'name': name, 'soc_type':soc_type,'address': address,'election':election , 'board_members': board_members_file, 'contact': … -
Django Python Database Table Link Handling
I am currently trying to create a trial balance with data that comes from 3 Tables in my Sage 200 MSSQL Database, the data links between 4 rows in the tables. For example: [PostGL].[AccountLink] links to [Accounts].[AccountLink] & [Accounts].[iAccountType] links to [GLAccountTypes].[idGLAccountType] I need to find a way to link these 3 tables with the relevant links and fetch the following data to be printed to the trial balance: [PostGL] = Debit & Credit [GLAccountTypes] = Description [Accounts] = Account Number Here is my current code: Views.py: susAcc = list('161','162','163','164','165','166','167','168','112') def home(request): return render(request , 'main/home.html') def Kyletrb(request): postGL = ("SELECT AccountLink , Debit , Credit FROM [Kyle].[dbo].[PostGl] WHERE AccountLink <> ?") cursor = cnxn.cursor(); cursor.execute(postGL, susAcc); arrPostGL = [tup[0] for tup in cursor.fetchall()] accTypes = "SELECT idGLAccountType, cAccountTypeDescription FROM [Kyle].[dbo].[_etblGLAccountTypes]" cursor = cnxn.cursor(); cursor.execute(accTypes); arrAccTypes = [tup[0] for tup in cursor.fetchall()] accounts = "SELECT AccountLink ,Master_Sub_Account , iAccountType FROM [Kyle].[dbo].[Accounts]" cursor = cnxn.cursor(); cursor.execute(accounts); arrAccounts = [tup[0] for tup in cursor.fetchall()] return render(request , 'main/Kyletrb.html' ) Kyletrb.html: <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous"> {% extends "main/base.html"%} {% block content%} <h1 class = 'img-container'>Kyle Database Trial Balance</h1> <style> .img-container { text-align: center; } </style> <div class="img-container"> <img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAoHCBUSExQSFRUXGBcXHBkZHBoXGRcdHBgaIBgZGCAeHRoaICwjHSApHhgaJDYkKS0vMzQ0HCQ4PjowPS0yMzIBCwsLDw4PHRISHTIpIioyNDIyMjIyNTIvMj0vMzI3NDI0MjI9LzIyMjIyNToyMjI0Mi80MjI0MjIyMjIyMjIyMv/AABEIAKoBKQMBIgACEQEDEQH/xAAcAAEAAgIDAQAAAAAAAAAAAAAABgcDBQECBAj/xABMEAACAgEBAwYHDQQIBgMBAAABAgADEQQFEiEGEzFBUWEHFSJxgdHSFCMyQlJTY3KCkZKToWKiscEzQ1RzdKOysyQ0RGSDwxcltBb/xAAYA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aD1qcgz3RAjWq1TrbpUuXDrbhbEB3LA1difYbLDKn0EySzgicwEREBERAREQEREBMHuuv5afiX1zPPL7gpP9VX+BfVAxZ0+9zmat/o3/I3sfW6Zzv0YC5qwDvAZTAbO9kDtzxz2zv4vp+ar/AvqjxfT81X+BfVCd1jVtOrMwNQZ/hEbgLfWPX6Z0K6bKk8zlQAp8jKgdAXsA6sTP4vp+ar/AvqjxfT81X+BfVBuum/QMca/JJYcU4Mc5I7DxPHvM6r7nDGwGoOelhubx87dMy+L6fmq/wL6o8X0/NV/gX1Qbro9lDcWao8N3iUPDOccerIziA9AO8Gr3sk5yuckAE57SAPunfxfT81X+BfVHi+n5qv8C+qEbdFegHeDVg5JyCmcnGTntOBnzRW9C8VNY4Y4FBwznHDqyczv4vp+ar/AAL6o8X0/NV/gX1QbYXXTMoRuZKg5CncIB7QDwHTObRp3KluaYr8EtuHd82eiZfF9PzVf4F9UeL6fmq/wL6oTusedOc8auO9n4HHe+F9/X2zrjTZ3/ed7GN7yM4xjGenGOHmmbxfT81X+BfVHi+n5qv8C+qDddA9HDjXwG6OKcF4eSOwcBw7pzztOAu9XurjAyuBjowOrGBidvF9PzVf4F9UeL6fmq/wL6oRt1NlJJJavLDBOV8oceB7RxPDvmJU0wQ1jmQh4lBubpPT8Ho6hM/i+n5qv8C+qPF9PzVf4F9UJ3WOs6dcbpqGAVGNwYUnJHDqzxxOVegYwaxgbowU4L8kd3dO/i6n5qv8C+qPF1PzVf4F9UG3FFtKKFRq1UdAUqAPQJk92V/OJ+JfXOni+n5qv8C+qPF9PzVf4F9UIZ1cMMggg9Y4iZJjrrCjCgADoAAAHoEyQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQERED//Z "> </div> <br> … -
How to keep field value unchanged when foreign key object updated in Django - Django?
Currently im working on an Ecommerce project in Django where i have a Order model which has Foreign key relation with Product. So all the product details are fetched from product model. Now im facing issue with the same. Whenever I make any change to Product object its getting updated in all the related Order objects too even for orders placed in past. Is it possible to keep past order's product values unchanged whenever Product object is updated in future? Please help. Below are the codes for your reference. Product Model class Product(models.Model): measurement_choices = (('Liter', 'Liter'), ('Kilogram', 'Kilogram'), ('Cloth', 'Cloth'), ('Shoe', 'Shoe')) name = models.CharField(max_length=200) sku = models.CharField(max_length=30, null=True) stock = models.CharField(max_length=10, null=True) measurement = models.CharField(choices=measurement_choices, max_length=20, null=True) description = models.CharField(max_length=10000) price = models.DecimalField(max_digits=7, decimal_places=2) discounted_price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) image = models.ImageField(upload_to='product/images', default='product.png', null=True, blank=True) image_one = models.ImageField(upload_to='product/images', null=True, blank=True) image_two = models.ImageField(upload_to='product/images', null=True, blank=True) image_three = models.ImageField(upload_to='product/images', null=True, blank=True) image_four = models.ImageField(upload_to='product/images', null=True, blank=True) image_five = models.ImageField(upload_to='product/images', null=True, blank=True) tags = models.ManyToManyField(Tags) category = models.ForeignKey(Category,on_delete=models.SET_NULL,null=True,blank=True) sub_category = models.ForeignKey(SubCategory, on_delete=models.SET_NULL, null=True,related_name='+') status = models.CharField(max_length=20, choices=(('Active', 'Active'), ('Inactive', 'Inactive'))) brand = models.ForeignKey(Brand,on_delete=models.PROTECT,blank=True, null=True) offer = models.ForeignKey(Offer, on_delete=models.CASCADE, null=True, blank=True) color = models.ForeignKey(Color , blank=True, null=True , on_delete=models.PROTECT) size_type … -
How to make custom page under admin
Django has user authentification for /admin by default Is it possible to use this auth system for my custom page?? At first try I set routing just under the admin/ However it is in vain. (I guess of course...) urls.py path('admin/help', views.help), views.py def help(request): context = {} return render(request, 'help.html',context) is it possible to use django auth system for custom page?? Or my idea is completely wrong?? -
When I click button,it redirects me wrong directions
I am new on Python Django.I need your help in one situation.As you see from my screenshot,when I clicked edit button it redirects me to "show/update/15" but it should be "update/15" I added the error page and code parts which you can need. web page error show.html urls.py views.py(update part) -
Django: 'TypeError: 'HttpResponseForbidden' object is not callable
I am building a portal for jobs. I get an error if I try to login, access the admin page, register or access any page: 'TypeError: 'HttpResponseForbidden' object is not callable Here is the model,views and templates: model_1 #models from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE from PIL import Image class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pic') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 and img.width > 300: output_size=(300,300) img.thumbnail(output_size) img.save(self.image.path) Views_1 from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth import authenticate from django.http import request, HttpResponse from django.contrib import messages from .forms import * from .models import * from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required # Create your views here. def register(request): if request.method == 'POST': form = CompRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') return redirect('Login') else: form = CompRegisterForm() return render(request, 'Users/register.html', {'form': form}) @login_required def profile(request): if request.method == 'POST': u_form = CompUpdateForm(request.POST, instance=request.user) p_form = ProfilePicForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('Profile_Page') else: u_form = CompUpdateForm(instance=request.user) p_form = ProfilePicForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, … -
why url is not working after add foreignkey field to model?
I'm creating a blog application and I added a category for its blog posts.When adding a new category it's can be can be done without any problem.But the problem is I can't find posts for specific catgory in and gets a error like Field 'id' expected a number but got 'health' but before I update field category charafield to forenkeyfied its work without any problem. here is my code my code class Post(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = SummernoteTextField(blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) image = models.ImageField(upload_to='images',null=True, blank=True) category = models.ForeignKey('blog.category', on_delete=models.SET_NULL, null=True, blank=True) class category(models.Model): name = models.CharField(max_length=80) def __str__(self): return self.name views.py def CategoryView(request, cats): category_posts = Post.objects.filter(category=cats.replace('-', ' ')) return render(request, 'categories.html', {'cats':cats.replace('-', ' '), 'category_posts':category_posts}) forms.py class PostForm(forms.ModelForm): category = forms.ModelChoiceField(queryset=category.objects.all().order_by('name')) class Meta: model = Post fields = ('title', 'category','author', 'content', 'image','status') -
How to list all channel_name in a group?
I saw how to get the list of all channel_name in a group in channels 2 but I use channels 3 (3.0.4) Do you know how to get it? -
How to create some restrictions for users?
I want to split my application into modules. So each user will have permission to enter certain pages. There are pages such as; Add new user See user list User Performance Assigned customers ... on the menu. For example some users can see one of them and other users can see 2 of them etc.. Should I create an attribute as models.BooleanField for each one and if it is true, user can see otherwise cannot see. I have at least 10 function like this in my menu, I'm not sure it will be the most efficient way. How can I handle this problem? Is there a better way? -
How to edit output of elasticsearch shown in the rest framework and can we show the output in a custom page?
In the views file I have used Django DSL drf for filtering the data and I think this library shows the output in REST Framework This is my views.py from django.shortcuts import render from django.shortcuts import render from django.http import JsonResponse import requests import json from django_elasticsearch_dsl_drf.viewsets import DocumentViewSet from .documents import * from .serializers import * from django_elasticsearch_dsl_drf.filter_backends import (FilteringFilterBackend, OrderingFilterBackend, CompoundSearchFilterBackend) from .models import * def index(request): data_preperation() return JsonResponse({'status': 200}) class PublisherDocumentView(DocumentViewSet): document = Document serializer_class = NewsDocumentSerializer lookup_field = 'first_name' fielddata = True filter_backends = [ FilteringFilterBackend, OrderingFilterBackend, CompoundSearchFilterBackend ] search_fields = ( 'title', 'content', ) multi_match_search_fields = ( 'title', 'content', ) filter_fields = { 'title': 'title', 'content': 'content', } ordering_fields = { 'id': None, } ordering = ('id',) This is my documents.py from django_elasticsearch_dsl import (Document, fields, Index) from .models import ElasticDocuments PUBLISHER_INDEX = Index('elastic_demo') PUBLISHER_INDEX.settings( number_of_shards=1, number_of_replicas=1 ) @PUBLISHER_INDEX.doc_type class Document(Document): id = fields.IntegerField(attr='id') fielddata = True title = fields.TextField( fields={ 'raw': { 'type': 'keyword', } } ) content = fields.TextField( fields={ 'raw': { 'type': 'keyword', } }, ) class Django(object): model = ElasticDocuments this URL is showing the output in REST Framework page path('search/', PublisherDocumentView.as_view({'get': 'list'})), My question is how I can change … -
JQuery: Select options not getting shortlisted based on radio button selection by using a passed Django variable
I want to provide the functionality to shortlist (reduce) the options inside select on the basis of the value of the radio button that is selected I am currently doing this using a PlugIn in JQuery that looks like this - jQuery.fn.filterOn = function (radio, values) { return this.each(function () { var select = this; var options = []; $(select).find('option').each(function () { options.push({ value: $(this).val(), text: $(this).text() }); }); $(select).data('options', options); $(radio).click(function () { var options = $(select).empty().data('options'); var haystack = values[$(this).attr('id')]; $.each(options, function (i) { var option = options[i]; if ($.inArray(option.value, haystack) !== -1) { $(select).append( $('<option>').text(option.text).val(option.value) ); } }); }); }); }; I used this plugin from here - https://stackoverflow.com/a/878331/11827709 You just pass a dictionary to this PlugIn and it shortlists the select options for you If I pass the dictionary hardcoded to this function like this - $(function () { $('#config').filterOn('input:radio[name=core]', { 'A': ['A1', 'A2', 'A3'], 'B': ['B1', 'B2', 'B3'], 'C': ['C1', 'C2', 'C3', 'C4', 'C5', 'C6'] }); }); The shortlisting works fine Like if I select 'A' in the radio button I can only see A1, A2, and A3 in the select menu But if I replace it with a variable that I pass from a …