Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to format & show required content in log file(logger) whenever any changes is happening in model objects
I am trying to implement logger functionality to my Django Application. In my App, I am having 6 different Models(from frontend users can change their Shift Timing/delete or upload new user's records from the .xls file). I want to create a log file so that I can monitor which user is logined and what action he performed(e.g update /delete/upload/download). Please find the below code I am using in my settings.py which is giving me a huge log without proper format. (However, I can see the action details in the generated log file but the structure is not user-friendly). settings.py import logging # DataFlair #Logging Information LOGGING = { 'version': 1, # Version of logging 'disable_existing_loggers': False, #########formatter######################### #disable logging 'formatters': { # 'console': { # 'format': '%(name)-12s %(levelname)-8s %(message)s' # }, 'file': { 'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' } }, #########################Handlers ################################## 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'Apple3.log', }, }, ################################ Loggers ################################# 'loggers': { 'django': { 'handlers': ['file',], 'level': 'ERROR', 'propagate': True, 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG') }, }, } Please find the few lines from the log file. Traceback (most recent call last): File "/Users/shaileshyadaav/PycharmProjects/first/venv/lib/python3.7/site-packages/django/template/base.py", line 849, in _resolve_lookup (bit, current)) # missing attribute django.template.base.VariableDoesNotExist: Failed … -
Using Jquery select radio otpions from dictionary
I have a HTML template which has Multichoice Question with options and Essay type questions. The user's answers are saved in model called Sitting in user_answers field as sitting.user_answers = {"424": "1527", "319": "adadadf", "203": "786", "437": "1572", "383": "1429"} The first number is the question_id and and second is the answer_id(selected option) or answer itself (incase essay type question). I am able to display the questions in one template using the following code: views.py if self.sitting.get_first_question() is False: questions= MCQuestion.objects.filter(question_ptr_id__in=self.sitting._question_ids()).prefetch_related('answer_set__question') essayquestions= Essay_Question.objects.filter(question_ptr_id__in=self.sitting._question_ids()) answerdetails = Sitting.objects.filter(id=self.sitting.id) print(answerdetails) return render(self.request, 'dashboard/exam-review.html', {'questions': questions,'essayquestions': essayquestions,'form': True}) Template {% for question in questions %} <div class="row mt-2 mb-4 shadow-1" style="background: #ececec"> <div class="col-md-10"> <input type=hidden name="question_id" value="{{ question.id }}" class="question_id"> <div class="panel-heading"> <p class="panel-title mb-2 mt-2" > <li style="list-style-type: none;" class="mb-1 mt-1"><strong> {% autoescape off %}{{ question.content }}{% endautoescape %} </strong></li> {% if question.figure %} <div class="row mb-1"> <img src="{{ question.figure.url }}" alt="{{ question.content }}" /> </div> {% endif %} {% if question.questionmarks %} <div class="row ml-1" > <p style="font-size:0.8rem"><b>Marks :</b> {{ question.questionmarks }}</p> </div> {% endif %} </div> <div class="panel-body "> <ul class="mb-2" style="list-style-type: none;"> {% regroup question.answer_set.all by get_content_display as answer_list %} {% for answers in answer_list %} <span>{{ section.grouper }}</span> … -
Using some variable in Django CASE WHEN condition
I am having something like: value = Func(Now(), F('reg_date'), function='DATEDIFF') # days since registration exp = Case( When(value__gt=150, then=Value(1.5)), When(value__gt=90, then=Value(1.3)), default=0 ) User.object.aggregate(score=Avg(exp)) You can se here the value is not a field from the model, and I want to perform the check on it. Is there a way I can perform the check inside the When condition on non-model fields? Actually, I want to perform the following SQL Query: select AVG( CASE WHEN DATEDIFF(now(), reg_date) > 150 THEN 1.5 WHEN DATEDIFF(now(), reg_date) > 90 THEN 1.3 ELSE 0 END) as score from users_user; -
Django search by lat, lon and name of a business
I am trying to search for location using latitude, longitude and the name of the business. How do I use multiple parameters in objects.filter ? My current code can search by lat and lon. I want to search by name of business for a given lat and lon. Here is my code: businesss = Business.objects.filter(location__dwithin=(ref_location, 50000))\ .annotate(distance=GeometryDistance("location", ref_location))\ .order_by("distance") -
Request.user on Django Model forms
I have a ledger account table that consist of ledger accounts of all the companies. The user in logged into a specific company and hen he selects an account to use on a form only the accounts that company must be available for the user. for this purpose I use the request.user to determine the user. I however get an error "request does not exist". I understand why it is not available on the forms.py as there is no request executed. Is there a way that I can make request.user available of the form. Models.py class tledger_account(models.Model): id = models.AutoField(primary_key=True) description = models.CharField(max_length=30, unique=True) gl_category = models.CharField(max_length=30, choices=category_choices, verbose_name='category', db_index=True) note = models.CharField(max_length=25, blank=True, default=None) active = models.BooleanField(default=True) company = models.ForeignKey(tcompany, on_delete=models.PROTECT, db_index=True) forms.py class SelectAccountForm(forms.ModelForm): date_from = forms.DateField(widget=forms.SelectDateWidget(years=year_range)) date_to = forms.DateField(widget=forms.SelectDateWidget(years=year_range)) select_account = forms.ModelChoiceField(queryset=tledger_account.objects.filter( company = request.user.current_company)) class Meta: model = ttemp_selection fields = ['select_account', 'date_from', 'date_to'] -
Django Simple History INSERTS rather than UPDATES when reverting a model
I'm reverting a model instance as specified in the docs: # In a DRF ViewSet, although I don't think that should matter... instance = self.get_object() # Find the historical record I want desired_record = instance.history.first().prev_record # Get the instance from it (I removed code handling the edge case of no prior history, for question clarity) desired_instance = desired_record.instance # EDIT, I have also tried # desired_instance = instance.history.most_recent() # which exhibits the same problem on save # Include a changelog comment desired_instance._change_reason = "Reverted to previous" # Update the instance desired_instance.save() However, this produces the error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "projects_configuration_pkey" DETAIL: Key (id)=(9ffc4e31-e714-4258-95dd-a196a70bf301) already exists. The model (in app projects) looks like: class Configuration(models.Model) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created = models.DateTimeField(editable=False, auto_now_add=True) modified = models.DateTimeField(auto_now=True) name = models.CharField(blank=False, null=False, max_length=60) The same problem occurs when I use the instance.history.as_of(<datetime>) method. DSH seems to be attempting to insert a new record rather than update the existing one to a former state. What's going on here? -
Djoser simpleJWT AUTHORIZATION forbidden(403) whie sending JWT <token> to auth/users/me/
I am using DJOSER and simple jwt for authentication and authorization. when I send a post request for authentication to endpoint http://localhost:8000/auth/jwt/create/ it response with access and refresh token, and again when i pass the Authorization:JWT <access_token> to https://localhost:8000/auth/users/me/ it gives 403 forbidden with "detail": "Authentication credentials were not provided." have my settings like DJOSER = { 'LOGIN_FIELD': 'email', 'SEND_CONFIRMATION_EMAIL': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'ACTIVATION_URL': 'activate/{uid}/{token}', 'PERMISSIONS': { 'activation': ['rest_framework.permissions.AllowAny'], 'password_reset': ['rest_framework.permissions.AllowAny'], 'password_reset_confirm': ['rest_framework.permissions.AllowAny'], 'set_password': ['djoser.permissions.CurrentUserOrAdmin'], 'username_reset': ['rest_framework.permissions.AllowAny'], 'username_reset_confirm': ['rest_framework.permissions.AllowAny'], 'set_username': ['djoser.permissions.CurrentUserOrAdmin'], 'user_create': ['rest_framework.permissions.AllowAny'], 'user_delete': ['djoser.permissions.CurrentUserOrAdmin'], 'user': ['djoser.permissions.CurrentUserOrAdmin'], 'user_list': ['djoser.permissions.CurrentUserOrAdmin'], 'token_create': ['rest_framework.permissions.AllowAny'], 'token_destroy': ['rest_framework.permissions.IsAuthenticated'], }, 'SERIALIZERS': { 'user_create': 'accounts.serializers.UserCreateSerializer', 'user': 'accounts.serializers.UserSerializer' } } SIMPLE_JWT = { 'AUTH_HEADER_TYPES': ('JWT',), } REST_FRAMEWORK = { 'DEFAULT_AUTHENTICAITON_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated' ), } serializers from djoser.serializers import UserCreateSerializer, UserSerializer from django.contrib.auth import get_user_model from rest_framework import serializers User = get_user_model() class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User fields = ('id', 'email', 'first_name', 'last_name', 'password') user model from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin ) class UserManager(BaseUserManager): def create_user(self, email, first_name, last_name, password=None, is_staff=False, is_admin=False, is_active=True): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have password") if not first_name: raise … -
Custom encoder ignored by django JsonResponse
I am building an app using Django Rest Framework (Versions : django 3.1, djangorestframework 3.11.1, python 3.7) I want to override the encoder used in JsonResponse. An oversimplification of my problem: from django.http import JsonResponse from django.core.serializers.json import DjangoJSONEncoder class CustomEncoder(DjangoJSONEncoder): def default(self, o): return o + 10 response = JsonResponse({"data": 1}, encoder=CustomEncoder) What I expect from response.getvalue() is '{"data": 11}' but instead I get '{"data": 1}'. What am I doing wrong ? -
How to set default inner serializer data in django-rest?
I have two simple serializers class UserSerializer(Serializer); name = serializers.CharField(required=False, default='Mile') age = serializers.IntegerField(required=False, default=25) class AccountSerializer(Serializer): account_id = serializers.UUIDField(required=False, default=uuid4()) user = UserSerializer() And i want to set the default user in AccountSerializer if it is not specified. For example, account = AccountSerializer(data={'account_id': uuid.UUID('e623429d-b1d1-4238-91b8-03e6f5ec58f1')}) account.is_valid() account.data { 'account_id': 'e623429d-b1d1-4238-91b8-03e6f5ec58f1', 'user': { 'name': 'Mike', # user must be default 'age': 25 } } And i also want to set my own values in 'user fields' and leave the other fields by default For example, account = AccountSerializer(data={'account_id': uuid.UUID('e623429d-b1d1-4238-91b8-03e6f5ec58f1'), 'user': {'name': 'Julie'}}) account.is_valid() account.data { 'account_id': 'e623429d-b1d1-4238-91b8-03e6f5ec58f1', 'user': { 'name': 'Julie', # user name must be 'Julie' but age by default 'age': 25 } } How should i implement this? Please note that I am not going to save the model to the database! I just need to check the incoming json and set the fields to default if not set -
cannot generate token s for other users, only able to generate token for admin in Django rest framework
Im new to Django Rest framework and working with token authentication but the problem is Im only able to generate token for admin/superuser not for other users on save. I would like to generate tokens for other users on register but cant figure out how to do it. I am getting this error ValueError: Cannot query "k@hotmail.coml": Must be "User" instance. I would really appreciate if someone could help me resolve it. models. py file. from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token # Create your models here. class Task(models.Model): title= models.CharField(max_length=200) complete= models.BooleanField(default=False) created= models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True,) last_login = models.DateTimeField(verbose_name='last login', auto_now_add=True) is_admin = … -
Can a Docker remote host keep its files synced with your local machine? Django project that needs auto-reloading
I'm considering the purchase of one of the new Macbook M1's. Docker Desktop is apparently unworkable with their Rosetta 2 engine, and all of my development efforts rely on Docker desktop, and a local development environment that auto-reloads when files are changed. I haven't done much with Docker remote hosts, but I see that this could be a stop-gap solution until Docker rewrites its engine. Google is failing me... can you keep files on your local machine synced up with your Docker remote host? -
URL is changing after my image is update in django
When I add an image, the URL of the image is fully visible but when I update, it is half past this is my models.py from django.db import models # Create your models here. class ImageUpload(models.Model): get_image = models.FileField(upload_to='gallery/new/',null=True) this is my views.py from django.shortcuts import render,redirect from upload.models import ImageUpload # Create your views here. def add_image(request): if request.method == "POST": image = request.FILES['myimage'] save_image = ImageUpload(get_image=image) save_image.save() return redirect('/') else: image_data = ImageUpload.objects.all() return render(request,'add_image.html',{'image_data':image_data}) def update_image(request, id): if request.method == "POST": image = request.FILES['myimage'] save_image = ImageUpload.objects.filter(id=id).update(get_image=image) return redirect('/') else: image_data = ImageUpload.objects.filter(id=id) return render(request,'update_image.html',{'image_data':image_data}) this is my urls.py from django.urls import path from upload.views import add_image, update_image app_name = 'upload' urlpatterns = [ path('', add_image, name="add_image"), path('update_image/<id>/', update_image, name="update_image"), ] this is my settings.py static and media configuration STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] STATIC_ROOT = BASE_DIR.parent / "static_cdn" MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / "media" this is my project urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('upload.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) this is my add_image.html <form action="{% … -
Getting irrevelant errors in my background task functions
I have a Django application and I'm using django-background-tasks library in it. When I run my background functions, I'm getting irrelevant errors. I'm getting an error such as below even if I send the arguments to that function. Traceback (most recent call last): File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/background_task/tasks.py", line 43, in bg_runner func(*args, **kwargs) TypeError: optimize_task() missing 2 required positional arguments: 'optimization_outputs' and 'model_names Here is the function calling; optimize_task(customer_name, request.user.id, known_map, bounds, optimization_features, optimization_outputs, model_names, verbose_name = verbose) I'm getting not just this error, but irrelevant errors like this and that. How can I fix this issue? -
How To Post List String for Django Rest Framework
class ArticleTagViewSerializer(serializers.ModelSerializer): class Meta: model = ArticleTags fields = ('id','tag') def create(self, validated_data): return ArticleTags.objects.create(**validated_data) class ArticleViewSerializer(serializers.ModelSerializer): tags_set = ArticleTagViewSerializer(source='posttags',required=False,many=True) class Meta: model = Article fields = ('id','caption','tags_set') def create(self, validated_data): return Article.objects.create(**validated_data) Hey guys,what i want to do is save List 's one by one when they are sent as post request like this { "caption": "Caption", "tags_set": [ { "id": "9d7b305d-939b-48ea-bea0-2e386f4bd8ff", "tag": "Tag1" }, { "id": "18f76a4c-f29d-4c99-ae0d-d03d1b00d070", "tag": "Tag2" } ], } I know that i have to create such a create() function like this: def create(self, validated_data): tags = ???? articleinit = Article.objects.create(**validated_data) for tagtinit in list(tags): m2 = ArticleTags(article=articleinit , tag= taginit ) m2.save() return articleinit but how do i request the tags such that create function works as intended? -
How to edit empty field directly on list in django admin
I have a problem with editing empty fields directly in the list in the django admin panel, it's about the name field. I set list_editable to name, but now it is possible to edit all fields, not empty ones. Do I need to overwrite something? models.py class Person(models.Model): name = models.CharField(max_length=255, blank=True) numer = models.IntegerField() text = models.TextField() def __str__(self): return str(self.numer) admin.py @admin.register(Person) class PersonAdmin(admin.ModelAdmin): ordering = ['numer'] list_display = ['numer', 'name'] list_editable = ['name'] -
'str' object has no attribute 'makefile' I had this error when i run the page?
I had this problem and I dont know whats the meaning of makefile is ?!! thanks for ur help this url page code : from django.contrib import admin from django.urls import path from tiketing.views import movie_list urlpatterns = [ path('admin/', admin.site.urls), path('tiketing/movie/list/', movie_list) ] and this is my view page code def movie_list(request): movies = Movie.objects.all() response_text = '\n'.join('{}:{}'.format(i, movie) for i, movie in enumerate(movies, start=1) ) return HTTPResponse(response_text) -
how to call a template passing a new parameter, but the template should have parameters that was passed to it when it was called by different view
1: i have a template shop.html. view.py ---> i have passed multiple parameters to the page like def shop(request): context {'parameter1 parameter2 parameter3 parameter4 parameter5 '} return render(request, 'shop.html', context) 2: now i am calling the same template, but this time with different view i want to pass another parameter i.e parameter6 but this time. i dont want to write the queries again to pass parameter1 to 5 that i passed in def shop(); 3: how can i pass additional parameter to the template using another view view.py ---> def add_value(request): query = xxxxxxxxxxxxxxx return render(request, 'shop.html', {query:query}) 4: when i would go to shop.html again. i should get all the parameters passed to shop.html by def shop() and def add_value() plz help. thanks you -
AttributeError: object has no attribute "object_list"
I'm trying to bring an old django app up to date but hitting an error I am unable to figure out. After upgrading django from 1.5 to 1.8, I'm suddenly getting the error AttributeError: MonthlyStatementPdf has no attribute object_list. The code in question is class MonthlyStatementPdf(BaseTableView): table_class = MonthlyStatementTable template_name = 'reports/monthly_statement_pdf.html' permission_required = 'core.view_reports' def get_context_data(self, **kwargs): context = super(MonthlyStatementPdf, self).get_context_data(**kwargs) context['summary'] = self.request.session.get('monthly_statement', {}).get('summary', 0) context['merchant'] = self.request.session.get('monthly_statement', {}).get('merchant') context['period'] = self.request.session.get('monthly_statement', {}).get('period', timezone.now()) if context['merchant']: context['discount_rate'] = context['merchant'].discount_rate / 100 return context def get_queryset(self): return self.request.session.get('monthly_statement', {}).get('daily_totals', []) def get(self, request, *args, **kwargs): context = self.get_context_data(object_list=self.get_queryset()) pdf_file = generate_pdf(request, context, self.template_name) response = HttpResponse(pdf_file, content_type='application/pdf') response['Content-Disposition'] = 'filename="MonthlyStatement.pdf"' return response I have no prior experience with django, or python for that matter, but obviously it is an error with how object_list is being passed to get_context_data in the get method. I tried referencing the answer to this similar question, which seems to make sense. If I understand correctly, this code is trying to pass object_list from get to get_context_data, which proceeds to call the super method, but object_list is actually set from inside the get method somewhere up the chain of inheritance (django generic list view, it … -
DRF: problem with permissions of no staff members
I'm having problems with the permissions with Django Rest Frameworks. I have 2 settings file, one for dev and the other for production. In the production file I have this permission class 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ) It works when you use the token authentication but this is the problem: If I go in as a normal user (not even a staff member) I receive this when I try to go to http://myapp/drf/ (this is the link of my django rest framework) I receive this error: AttributeError at /drf/ 'TokenAuthentication' object has no attribute 'has_permission' Not even sure if that's fine but the true problem comes when I try to access some of the elements, for example: http://myapp/drf/clients Then any user can see all the clients with no restriction. It is like these restrictions only works for the root of django rest framework. What can I do? -
Carousel item position changes everyday!! (Django , materialize)
My Carousel/Carousel-Item dimensions are not fitting in nicely on the page. I left it at 1800px yesterday and there was no gap between navbar and carousel item. now there is. (gap) Not sure where i'm going wrong. When i reduce the carousel size to 900 px it cuts off lines from the carousel item as described below. carousel item over extending past carousel's height, hence misses lines Here's the html code in my django template. {% load staticfiles %} {% load static %} {% load index %} <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1"/> <link rel="stylesheet" href="{% static 'style.css' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <nav> <div class="container nav-wrapper"> <div class="flex-container"> <h class="brand-logo center"><b>Today's Q/A</b></h> <ul id="nav-mobile" class="Center"> <li><a href="/"></a></li> </ul> </div> </div> </nav> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <script> $(document).ready(function(){ $('.carousel').carousel(); }); autoplay() function autoplay() { $('.carousel').carousel('next'); setTimeout(autoplay, 4500); } </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> {#<section class="black">#} <style> html, body{ background-color: #FEDCC8; } .flex-container { display: flex; flex-direction: row; flex-wrap: wrap; justify-content: space-evenly; } </style> <div class="flex-container"> <div class="container-fluid"> <a class="btn waves-effect waves-light" href="/random_naturemetal_link">Cute Cat Pic <3 <i class="large material-icons left">sentiment_neutral</i> <i class="large material-icons right">sentiment_very_satisfied</i> </a> </div> <div class="container-fluid"> <a class="btn waves-effect waves-light" href="/random_cozy_link"> C O Z Y … -
Why can't I use the same variable again in Django? [duplicate]
In my views.py I have a function dataPrint(), which returns page, and dictionary categories_zipped. But when I try to use this dictionary in my skills.html file using Django syntax {% for category in categories_zipped %} it works only for the first time, when I try to use it later, it does not work. (I'm not getting any errors, the second use, just returns nothing, as shown on the images below) def dataPrint(request): categories = [ 'all', 'javascript', 'html', ] categories_menu = [ 'All', 'JS', 'HTML', ] return render(request, 'skill/skills.html', {'categories_zipped': zip(categories, categories_menu}) skills.html {% for category in categories_zipped %} <a class="link-icon" href="/skills/{{category.0}}"> <img class="small-icon" src="{% static '/skillsgraph/img/' %}{{category.0}}.svg" alt="{{category.0}}'.svg'" /> <span class="icon-title">{{category.1}}</span> </a> {% endfor %} <select name="category" class="link-list"> {% for cat in categories_zipped %} <option value="{{ cat.0 }}">{{ cat.1 }}</option> {% endfor %} </select> It renders only for the first time and renders only the first thing. If I change order (put select before a), it works only for select, but not for a's. -
How to inherit a model object instead of the model class
For some reasons, I want my Boolean Fields in my class Items(models.Model) to have a foreign key in my class ItemsGotten(models.Model). Here's my code for better understanding... Items(models.Model): title=models.Charfield(max_length=180) description=models.Textfield(max_length=180) paper=models.BooleanField(default=False, blank=True) skin=models.BooleanField(default=False, blank=True) ItemsGotten(models.Model): user=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) paperitem = models.ForeignKey(???) skinitem = models.ForeignKey(???)``` I know that you can simply get the value of the whole model class e.g paperitem = models.ForeignKey(Items). But that's not what I want to achieve, I want to get only the object from the Items model. e.g skinitem = models.ForeignKey(Items.skin). Thanks -
How to capture values in checked checkboxes using Django
I am creating a web application that will serve as a grocery store. The way I set it up is so the customer can come onto the website, click on the items that they would like to purchase, and then click a submit button to purchase those items. The problem I am running into is having a views.py function to take the information of which products were selected and subtracting 1 from the quantity of the database. When I say print(products) in my views.py, it returns "[]" in my terminal. This means that the values in my checked checkboxes are not being captured. Can anyone help me solve this? """models.py""" class Post(models.Model): title = models.CharField(max_length=100) Price = models.DecimalField(max_digits=4, decimal_places=2,default=1) Sale = models.DecimalField(max_digits=4, decimal_places=2,default=1) quantity = models.IntegerField(default=1) author = models.ForeignKey(User, on_delete=models.CASCADE) category = TreeForeignKey('Category',null=True,blank=True, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) views.py class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' def inventory(request): products = request.POST.getlist('products') a = Post.objects.filter(title=products).update( quantity=F('quantity')-1 ) return redirect('blog-home') urls.py path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('inventory', views.inventory, name='inventory'), home.html {% extends "blog/base.html" %} {% block content %} {% for post in posts %} {% if post.quantity > 0 %} <input type="checkbox" … -
Django pdfkit.from_string gives wkhtmltopdf OS error for large html string while converting to pdf
I am facing this issue and searched a lot for this, but found no solution. I am using pdfkit in my django application to generate invoices. I create a template in django and then render it with my data in an html string and then pass that rendered html string to pdfkit. When I generate 100 - 110 pages it prints pdf successfully. More than these pages, like 140 or 150 it gives an OS error content loaded unsuccessfully. from django.template.loader import get_template import pdfkit class CourierInvoice(View): def get(self, request, *args, **kwargs): options = { 'page-size': 'A4', 'dpi': 400, 'disable-smart-shrinking': '' } context = { ... //Data goes here for html ... } template = get_template("bulk_courier_invoices.html") html = template.render(context) # Renders the template with the context data. try: pdf = pdfkit.from_string(html, False, options) except: return HttpResponse("Some Error Occurred Try printing with less pages") response = HttpResponse(pdf, content_type='application/pdf') filename = "CourierInvoices_" + datetime.today().strftime('%d-%m-%Y') + ".pdf" content = "attachment; filename=" + filename response['Content-Disposition'] = content return response -
Get anchor tag from Django request URL
I have a Django template filter where I'm trying to check the request URL to see whether it includes an anchor tag or not. For example, I want to check if the request URL is: /mypath/mypage/my-slug/ or /mypath/mypage/my-slug/#myanchor If it is the latter, I want to get the anchor tag ID. Currently, the anchor tag seems to be stripped from the request information: request.path, request.build_absolute_uri() and so on. I can only get /mypath/mypage/my-slug/. The URL pattern for the page in question is: re_path(r'^(?P<product_slug>[\w-]*)_(?P<pk>\d+)/$', self.detail_view.as_view(), name='detail') I can see the regex looks for the line end after the last slash, which suggests the anchor is being excluded, but I can easily retrieve GET params from the URL and I expected this to be straightforward too. It feels like I am missing something pretty obvious.