Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
File upload button not visible in django (visible in django admin panel though)
I don't see file upload button in my front-end part and it's coming as a drop down list but it is visible in the admin panel, I'm new to Django, can you please help me to point out what is the mistake I'm making? [Thank You in advance :)]. [1]: Front-End Image: https://i.stack.imgur.com/MWU0s.png [2]: Back-End Image: https://imgur.com/a/J3R2k1P -
DeserializationError: ['“F(view_count) + Value(1)” value must be an integer.']
I am using Django 3.2 I am using F values to increment a field value (to avoid potential race conditions). Here is a snippet of my code (section that throws exception): def __update_fields(self, interaction_type): if interaction_type == Engagement.VIEW: self.view_count = F('view_count') + 1 I get this error: DeserializationError: ['“F(view_count) + Value(1)” value must be an integer.']: (poll.poll:pk=10) field_value was 'F(view_count) + Value(1)' Here is the full stack trace: Internal Server Error: //path/to/example Traceback (most recent call last): File "/path/to/myproj/env/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1836, in to_python return int(value) ValueError: invalid literal for int() with base 10: 'F(view_count) + Value(1)' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/path/to/myproj/env/lib/python3.8/site-packages/django/core/serializers/python.py", line 144, in Deserializer data[field.name] = field.to_python(field_value) File "/path/to/myproj/env/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1838, in to_python raise exceptions.ValidationError( django.core.exceptions.ValidationError: ['“F(view_count) + Value(1)” value must be an integer.'] During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/path/to/myproj/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/path/to/myproj/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/path/to/myproj/env/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/path/to/myproj/env/lib/python3.8/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/path/to/myproj/env/lib/python3.8/site-packages/django/views/generic/detail.py", line 107, in get context = self.get_context_data(object=self.object) File … -
VScode unittest test discovery settings for django app
I have a django app with some unittests. I want to run\debug them in VScode v.1.59.1. My ./vscode/settings.json looks like this: { "python.testing.unittestArgs": [ "-v", "-s", "./routes/tests", "-p", "test*.py" ], "python.testing.pytestEnabled": false, "python.testing.nosetestsEnabled": false, "python.testing.unittestEnabled": true, } When I try to run\discover tests I have this output: ImportError: Failed to import test module: test_utils ... django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. When I try to run tests in regular django way with command: python manage.py test the tests working fine. Please help me setup my VScode to run django unittests. P.S: I can not install pytest, this should be done without installation of any new modules. -
django.db.utils.ProgrammingError: relation "django_content_type" does not exist raised by psycopg2
I accidently removed django_content_type while migrating databse to postgreSQL to solve the following error: django.db.utils.IntegrityError: duplicate key value violates unique constraint (base, product) already exists it was raised when i tried load data from datadump.json to postgreSQL database Is there any way to create this table again I used command DROP TABLE public.django_content_type CASCADE; now i can't make the dumpdata.json it giving the following error django.db.utils.ProgrammingError: relation "django_content_type" does not exist and its raised by psycopg2 package I have reinstalled django, psycopg2 and started a new django project and its still giving the same error whenever i tried to migrate or create dumpdata.json for backup I tried this query to create django_content_type table CREATE TABLE public.django_content_type ( id integer NOT NULL DEFAULT nextval('django_content_type_id_seq'::regclass), app_label character varying(100) COLLATE pg_catalog."default" NOT NULL, model character varying(100) COLLATE pg_catalog."default" NOT NULL, CONSTRAINT django_content_type_pkey PRIMARY KEY (id), CONSTRAINT django_content_type_app_label_model_76bd3d3b_uniq UNIQUE (app_label, model) ) WITH ( OIDS = FALSE ) TABLESPACE pg_default; this query also giving error in djangoshell ERROR: relation "django_content_type_id_seq" does not exist -
Django - __init__() got an unexpected keyword argument 'headers'
I am trying to download a CSV when a button is clicked, however, I am getting the error: __init__() got an unexpected keyword argument 'headers this is my view: def download_file(request): response = HttpResponse( content_type='text/csv', headers={'Content-Disposition': 'attachment; filename="somefilename.csv"'}, ) return response this is the trackback: Traceback: File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "/Users/matthewkaye/Eflux/Argus/app/views.py" in download_file 74. response = HttpResponse( File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/http/response.py" in __init__ 289. super().__init__(*args, **kwargs) Exception Type: TypeError at /Download Exception Value: __init__() got an unexpected keyword argument 'headers' -
Problem with referencing auth_user table in Django with raw query
I need to make an inner join on my tables and I need the users last name and first name from the auth_user table whose are added to a project. Projects are collected in another table (Project) that is connected to a Profile model with which I extended my User model. Yet I'm using SqLite3 so I wrote a query that works well in SqLite Viewer: SELECT username, projekt_id FROM 'auth_user' INNER JOIN stressz_profile ON stressz_profile.user_id = auth_user.id WHERE projekt_id=1 I adopted the query to Django like this: resztvevok = Profile.objects.raw('SELECT username, projekt_id FROM auth_user AS resztvevok INNER JOIN stressz_profile ON stressz_profile.user_id = auth_user.id WHERE projekt_id=1') But when I refresh the browser it says: no such column: auth_user.id models.py class Profile(models.Model): def __str__(self): return str(self.user) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) projekt = models.ForeignKey(Projekt, on_delete=models.CASCADE, default=3) ... -
getting error while posting data of uid and token ( 'WSGIRequest' object has no attribute 'post' )
I created class based view to access uid and token . Here I create one web page which have one button of activate user. I am sending one uid and token to user email . now I want to post that uid and token when user click on button. I create this code in view for post uid and token. But getting error on posting (WSGIRequest' object has no attribute 'post) views.py class ActivationView(View): def get (self, request, uid, token): print('get called in activate_user') return render(request, 'activate.html') def post (self, request, uid, token): print('UID : ', uid) print('Token : ', token) payload = json.dumps({'uid': uid, 'token': token}) print("payload : " , payload) protocol = 'https://' if request.is_secure() else 'http://' web_url = protocol + request.get_host() + '/' post_url = web_url + ACTIVATION_BASE_ROUTE print('post_url : ' + post_url) response = request.post(post_url, data = payload) return HttpResponse(response.text) activate.html <form action="" method="post"> {% csrf_token %} <td ><button type="submit">Click Here For Activate Account</button></td> </form> How can I post it on same page ? -
django database TypeError
i am trying to make manytomanyfield so everything going well but when i created Department and assign user (Ids) i get error Field 'id' expected a number but got <Id: luka>. from django.db import models # Create your models here. class Id(models.Model): first_name = models.CharField(max_length=100, null=True) last_name = models.CharField(max_length=100, null=True) date_of_birth = models.CharField(max_length=100, null=True) date_of_expire = models.CharField(max_length=100, null=True) date_of_issue = models.CharField(max_length=100, null=True) CHOICES = [('Male', 'Female'), ('Female', 'Male')] gender = models.CharField(max_length=30, choices=CHOICES) # gender = models.CharField(max_length=10) address = models.TextField(null=True) country = models.CharField(max_length=30,null=True) city = models.CharField(max_length=30,null=True) card_no = models.CharField(max_length=30,null=True) personal_number = models.CharField(max_length=30,null=True) image = models.ImageField(default='defaut.jpg', upload_to='document_pics') def __str__(self): return self.first_name class Departments(models.Model): name = models.CharField(max_length=30, null=True) users = models.ManyToManyField(Id) def __str__(self): return self.name -
Preventing user from creating new Tags
I am building a BlogApp and I am trying to implement a feature so user cannot create new tags And can only use existing tags, So I am checking the form at the time of submit If blog post tags is in existing tags than Save the Post But if tags are not in existing tags than show an Error. For Example:- Existing tags are health, books and if user typed one of them then post will save And If user typed playing, health than it will show an error. But When i save the form with existing tags than it is showing error every time. models.py from taggit.managers import TaggableManager class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30, default='') description = models.CharField(max_length=30, default='') tags = TaggableManager() views.py from taggit.models import Tag def new_blog_post(request): existingTags = Tag.objects.all() if request.method == 'POST': form = BlogPostForm(request.POST, request.FILES) if form.is_valid(): blog_tags = form.cleaned_data['tags'] new_post = form.save(commit=False) new_post.post_owner = request.user if blog_tags in existingTags: new_post.save() else: messages.error(request,'You cannot create a New Tags') return redirect('qa:questions') else: form = BlogPostForm() context = {'form': form} return render(request, 'new_blog_post.html', context) I have also tried by looping the tags query like :- for extTags in existingTags: if blog_tags … -
Django - Model Form with ManyToManyField - how to calculate field?
I have this code in my views.py: from django.shortcuts import render from .helpers import * from .forms import OrderForm def create_order(request): if request.method == 'POST': form = OrderForm(request.POST) if not request.POST._mutable: request.POST._mutable = True if form.is_valid(): obj = form.save(commit=False) obj.total_price = calculate_total_price_obj(obj) obj.save() else: form = OrderForm() return render(request, 'create_order.html', {'form': form}) I have this in my helpers.py: def calculate_total_price_obj(obj) -> float: """ Calculate the total_price of the order. This function has to be called after the Order has been created and saved. """ prices_of_ordered_foods = obj.ordered_foods print(prices_of_ordered_foods) return sum(prices_of_ordered_foods) What I'm trying to achieve is: Get the form the user sent. Calculate field total_price based on the prices of chosen meals/foods by the user when he was filling up the forms (this is a ManyToManyField in my models.py). After calculation is performed, save the form. (Calculation is a simple sum() method.) However, this does not work. I am getting this error: <MyOrderObject> needs to have a value for field "id" before this many-to-many relationship can be used. Any ideas how to fix it? Thank you -
Unexpected result while using two matplotlib chart at the same time
I am using matplotlib for doing chart for my web project. There is two view functions. One for Pie chart and other for Bar chart. I get the desire chart while calling each chart one at a time. but while I tried to calling both function at the same time. I got unexpected result. Like both bar chart and pie chart produce identical figure, or one or both unfinished chart. I have added my code bellow. view.py from .utils import draw_piechart,draw_barchart # # Pie Chart def piechart(request): products = Product.objects.all() draw_piechart(products) return render(request,'store/piechart.html') def barchart(request): draw_barchart() return render(request,'store/barchart.html') utils.py import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt import numpy as np # from random import random, randint import random # Pie Chart def draw_piechart(products): # Pie chart, where the slices will be ordered and plotted counter-clockwise: # labels = 'Sale', 'Purchase', 'Test' labels = [] for i in products: if i.category not in labels: labels.append(i.category) sizes = [random.randint(10,30), random.randint(30,50)] # explode = (0.1, 0) # only "explode" the 2nd slice (i.e. 'Hogs') explode = None fig1, ax1 = plt.subplots(1) ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. plt.savefig('media/piechart.png',dpi=100, … -
Queries from Django unittests to Postgres are arbitrarily not being performed while staying on active mode
I'm developing ETLs with Django ORM and while running unittests either from my local env or from jenkins the query sometimes just stays active in the DB without being completed. I'm not always able to recreate the issue. I'm using Django 3.1.7 and the test are running within a Django "TestCase", so each test is running within a transaction. Im using a google cloud hosted Postgres (Postgres 12) DB server. When I run the ETL not in unittests everything runs smoothly. When run the generated query separately it work just fine and runs very fast. models.py definition for the tables: class DiseaseTarget(models.Model): id = models.AutoField(primary_key=True, db_index=True) gene = models.ForeignKey(Gene, on_delete=models.CASCADE, related_name='disease_target_gene', db_index=True) disease = models.ForeignKey(Disease, on_delete=models.CASCADE, related_name='disease_target_disease', db_index=True) dev_stage = models.TextField() class Meta: managed = True db_table = 'disease_target' unique_together = (('gene', 'disease'),) class Gene(models.Model): entity = models.OneToOneField(Entity, on_delete=models.CASCADE, primary_key=True, related_name='genes', db_index=True) symbol = models.TextField(null=True, db_index=True) class Meta: managed = True db_table = 'gene' class Entity(models.Model): id = models.AutoField(primary_key=True, db_index=True) entity_id = models.TextField(db_index=True) TYPES = [ ('cellnode', 'cell'), ('gene', 'gene'), ('geneset', 'geneset') ] type = models.TextField(choices=TYPES, db_index=True) name = models.TextField(default=entity_id) description = models.TextField(blank=True, null=True) class Meta: managed = True db_table = 'entity' index_together = [ ("id", "type"), ] unique_together = … -
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.