Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django cannot display model fields to template
I have a model from a package I would like to retreive fields from for the user to my template but am struggling to get this to work as I have done with user model previously: models class DeviceManager(models.Manager): def devices_for_user(self, user, confirmed=None): devices = self.model.objects.filter(user=user) if confirmed is not None: devices = devices.filter(confirmed=bool(confirmed)) return devices class Device(models.Model): user = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), help_text="The user that this device belongs to.", on_delete=models.CASCADE) name = models.CharField(max_length=64, help_text="The human-readable name of this device.") confirmed = models.BooleanField(default=True, help_text="Is this device ready for use?") objects = DeviceManager() class Meta: abstract = True def __str__(self): try: user = self.user except ObjectDoesNotExist: user = None return "{0} ({1})".format(self.name, user) view from django_otp.models import Device def account(request): user = request.user device = Device.objects.all() context = {"user": user, "device": device} return render(request, 'account.html',context) template {{ device.name }} {{ device.confirmed}} I am getting the folowing error: AttributeError: Manager isn't available; Device is abstract I have also tried to change device = Device.objects.all() # To device = DeviceManager.objects.all() But the produces the following error: AttributeError: type object 'DeviceManager' has no attribute 'objects' Help is much apprecaietd in displaying the content from model to my template. Thanks -
Python Requests with Django Rest Framework - 'detail': 'Authentication credentials were not provided'
I've got a tiny function that just looks to get a response from my DRF API Endpoint. My DRF settings look like this: "DEFAULT_AUTHENTICATION_CLASSES": [ # Enabling this it will require Django Session (Including CSRF) "rest_framework.authentication.SessionAuthentication" ], "DEFAULT_PERMISSION_CLASSES": [ # Globally only allow IsAuthenticated users access to API Endpoints "rest_framework.permissions.IsAuthenticated" ], I'm using this to try and hit the endpoint: def get_car_details(car_id): headers = {"X-Requested-With": "XMLHttpRequest"} api_app = "http://localhost:8000/" api_model = "cars/" response = requests.get(api_app + api_model + str(car_id), headers=headers) json_response = response.json() return json_response I keep getting 'detail': 'Authentication credentials were not provided' Do I need to generate a CSRF token and include it in a GET request? The only time this gets hit is when a user goes to a view that requires they are logged in. Is there a way to pass that logged-in user to the endpoint?? -
Django Rest Framework API is being called twice
I am using Django Rest Framework to make a custom backend that does the web3 login flow. However, it is calling my authenticate function twice. And I can't figure out why. my token view: #expects public_address, nonce and token if user is currently signed in @api_view(["POST"]) def get_token(request): logger.debug(request.data) public_address = request.data["public_address"] web3 = Web3Backend() logger.debug(web3) logger.debug('running authenticate from token endpoint') user, token = web3.authenticate(request) logger.debug(user) logger.debug(token) if token: return JsonResponse({'token': token}) else: return Response({'message': 'Missing token'}, status=400) Authenticate Function: def authenticate(self, request, **kwargs): logger.debug(request); public_address = request.data.get('public_address', None) nonce = request.data.get('nonce', None) curr_token = request.data.get('token', None) Web3User = get_user_model() if public_address: if curr_token: #TODO: decode token and check if public_address is the same as the user calling it and if not expired #TODO: if yes then just return true and token token =jwt.decode(curr_token, SECRET_KEY, algorithms="HS256") #TODO: convert into datetime and make sure the current datetime is not pass this expiry = datetime. strptime(token['expiry'],'%y-%m-%d') now = datetime.date.today() logger.debug(expiry) logger.debug(now) if(token['user'] == public_address and expiry < now): logger.debug('JWT still valid') return True, curr_token else: return AuthenticationFailed() #TODO: decode the JWT and check if the user is the proper user try: #TODO: database check; will want to switch to JWT tokens in … -
How can I integrate jquery timepicker in my django project
Here is the jquery timepicker code: $('.timepicker').timepicker({ timeFormat: 'h:mm p', interval: 60, minTime: '10', maxTime: '6:00pm', defaultTime: '11', startTime: '10:00', dynamic: false, dropdown: true, scrollbar: true }); Here is my forms.py from django import forms from bootstrap_datepicker_plus import TimePickerInput from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'content','chamber','address','fees','days','hours','review'] widgets = { 'hours': forms.DateField(widget=forms.DateInput(attrs={'class':'timepicker'})) } Here is my models.py class Post(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField('Doctor\'s Name',max_length=100) content = models.CharField('Specialty',max_length=100) chamber = models.CharField('Chamber\'s Name',max_length=200) address = models.CharField('Address',max_length=100) fees = models.IntegerField(default=0) days = MultiSelectField(choices= DAYS_OF_WEEK) hours = models.TimeField() review = models.TextField() liked = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name='liked') date_posted = models.DateTimeField(default=timezone.now) objects = PostManager() class Meta: ordering = ('-date_posted', ) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', kwargs={'pk': self.pk}) I am new to django and jquery how can I add a timepicker in my hours field? Where I put my mouse on right side of hours field it changes shape. But no event is triggered when pressed. Here no timepicker comes When I inspect this comes -
'int' object is not iterable when count the number of rows in database in Django
I have database created in Django. File models.py class Guest(models.Model): first_name = models.CharField(max_length=30, verbose_name='First name') last_name = models.CharField(max_length=30, verbose_name='Last name') middle_name = models.CharField(max_length=30, verbose_name='Middle name', blank=True, null=True) date_of_birth = models.DateField(verbose_name='Birthday') address = models.CharField(max_length=50, verbose_name='Address', default='VP 5/7') city = models.CharField(max_length=30, verbose_name='City') email = models.CharField(max_length=50, verbose_name='Email',blank=True, null=True) phone = models.CharField(max_length=20, verbose_name='Phone number', default='897777777') passport = models.CharField(max_length=15, default='C5555555') def __str__(self): return "First name: {}, Last name: {}".format(self.first_name, self.last_name) File views.py class GuestListView(generics.ListAPIView): serializer_class = GuestSerializer def get_queryset(self): queryset = Guest.objects.all() params = self.request.query_params city = params.get('city', None) if city: queryset = queryset.filter(city__startswith=city).count() return queryset File serializers.py class GuestSerializer(serializers.ModelSerializer): class Meta: model = Guest fields = "__all__" I run url like: http://127.0.0.1:8000/guests/all/?city=Kazan I got a error: 'int' object is not iterable How to fix that? -
How to query image path with right if condition from Django template?
In Django I have a box model. Each box has some images related to that box. from django.db import models from products.models import Product # Create your models here. class Box(models.Model): boxName = models.CharField(max_length=255, blank = False) boxDescription = models.TextField() boxPrice = models.DecimalField(max_digits=9, decimal_places=0, default=0) boxSlug = models.SlugField(max_length = 255, unique = True, help_text = "Unique text for url created from box name") boxCreatedAt = models.DateTimeField(auto_now_add=True) boxUpdatedAt = models.DateTimeField(auto_now=True) product = models.ManyToManyField(Product) def __str__(self): return self.boxName class Meta: db_table = 'boxes' ordering = ['-boxName'] class BoxImage(models.Model): image = models.ImageField() imageMetaKeyWords = models.CharField("Meta keywords for SEO", max_length = 255, help_text = "Comma delimited words for SEO") imageMetaDescription = models.CharField("Meta description", max_length = 255, help_text = "Content for image meta tag description") defaultImage = models.BooleanField(default= False) box = models.ForeignKey(Box, on_delete=models.CASCADE, related_name="images") In the views.py I need put all the boxes in the context so that they can be passed to the template from django.shortcuts import render from django.views import View from index.views import createNavContent from box.models import Box # Create your views here. class MainShop(View): def __init__(self): context = createNavContent() self.context = context.context def get(self, request, *args, **kwargs): self.context['title'] = 'Dimsum Box Shop' self.context['boxes'] = Box.objects.filter().all() return render(request, template_name='mainShop.html', context = self.context) … -
React axios patch overwrites manytomany field instead of adding to element
My react code is patching the model field group and completely erasing the original content within the group. I realize it might be my serializer or my view set but i can not find any examples of this being done through google search any help would be greatly appreciated. Request Handler handleJoin = (e, group) => { e.preventDefault(); axios.get('http://127.0.0.1:8000/core/current_user/', { headers: { Authorization: `JWT ${localStorage.getItem('token')}` } }) .then((user) => { let group_data = new FormData(); group_data.append('user', user.data.id); group_data.append('group', group.id); for (var value of group_data.values()) { console.log(value); } axios.patch(`http://127.0.0.1:8000/core/usergroup/${user.data.id}/`, group_data,{ headers: { Authorization: `JWT ${localStorage.getItem('token')}`, 'Content-Type': 'application/json', }, }) .then((res) => { console.log(res.data); }) .catch((err) => { console.log(err); }); }) .catch((err) => { console.log(err); }); } Model Serializer class UserGroupSerializer(serializers.ModelSerializer): groups = GroupSerializer(many=True, read_only=True,) class Meta: model = UserGroup fields = '__all__' Model Viewset class UserGroupDetail(APIView): def patch(self, request, pk): usergroup = UserGroup.objects.get(pk=pk) serializer = UserGroupSerializer(instance=usergroup, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
AttributeError: 'WindowsPath' object has no attribute 'endswith' when using runmodwsgi Django command
Windows 10, Python 3.8.10, Apache 2.4.51, Django 3.2.8, mod_wsgi 4.9.0 When I try to run the Apache server using python manage.py runmodwsgi, I get this output: Successfully ran command. Server URL : http://localhost:8000/ Server Root : C:/Users/Me/AppData/Local/Temp/mod_wsgi-localhost-8000-Me Server Conf : C:/Users/Me/AppData/Local/Temp/mod_wsgi-localhost-8000-Me/httpd.conf Error Log File : C:/Users/Me/AppData/Local/Temp/mod_wsgi-localhost-8000-Me/error_log (warn) Operating Mode : daemon Request Capacity : 5 (1 process * 5 threads) Request Timeout : 60 (seconds) Startup Timeout : 15 (seconds) Queue Backlog : 100 (connections) Queue Timeout : 45 (seconds) Server Capacity : 20 (event/worker), 20 (prefork) Server Backlog : 500 (connections) Locale Setting : en_US.cp1252 Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\mod_wsgi\server\management\commands\runmodwsgi.py", line 134, in handle options = mod_wsgi.server._cmd_setup_server( File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\mod_wsgi\server\__init__.py", line 3613, in _cmd_setup_server generate_apache_config(options) File "E:\Documents\Work Stuff\Active Work Files\Code\venv\lib\site-packages\mod_wsgi\server\__init__.py", line 1086, in generate_apache_config if target.endswith('/') and path != '/': AttributeError: 'WindowsPath' object has … -
Django Rest Framework - Cannot POST because username already exists
I am working on a basic rest api with django rest framework. And my database is on MySQL. For one of the functions, when I try to POST, it gives me an error because there is a row with the same username already. I have set the model to have all three of its fields to be unique_together. Please help me understand where i am going wrong, heres snippets of what i have currently: models.py: class VolunteerHours(models.Model): username = models.OneToOneField(Volunteer, models.DO_NOTHING, db_column='Username', primary_key=True) date = models.DateField(db_column='Date') hours = models.IntegerField(db_column='Hours') class Meta: managed = False db_table = 'volunteer_hours' unique_together = (('username', 'date', 'hours'),) urls.py: urlpatterns = [ path('timesheet/', views.TimesheetAPIView.as_view()),] views.py: from . import models from . import serializers from rest_framework import generics from rest_framework import mixins class TimesheetAPIView(generics.GenericAPIView, mixins.CreateModelMixin): serializer_class = serializers.VolunteerTimesheetSerializer def post(self, request): return self.create(request) serializers.py: class VolunteerTimesheetSerializer(serializers.ModelSerializer): class Meta: model = models.VolunteerHours fields = '__all__' The error im getting is: "username": [ "volunteer hours with this username already exists." ] What I want to happen is i can add as many rows with the same username as long as the date and hours are unique. Which are what is submit in my POST requests, but it says username … -
Django - Pymongo list index out of range error
I want to print the _id part of the results by running a query on the mongo db, but I am getting the "list index out of range" error. view; def deleted(request): q1=('XX') q2=('XX') client = MongoClient("XX") database = client["XX"] collection = database["XX"] query = {} query["Marketplace"] = q1 query["$or"] = [ { "Tuyx": q2 } ] cursor = collection.find(query) print(cursor) sonuc= loads(dumps(cursor)) id=sonuc[0]["_id"] print(id) client.close() return render(request, 'deletedlisting.html', {'id':id} ) ti want to print _id value as string; -
Continue uploading the file after connecting to the Internet
If the internet file is disconnected while uploading, how can I continue to upload the file using Django when it is connected? if request.method == 'POST' and request.is_ajax(): if formset.is_valid(): obj = formset.save(commit=False) obj.experience_id = experience_id obj.save() return JsonResponse({'error': False, 'message': 'video is uploaded.'}) else: return JsonResponse({'error': True, 'errors': formset.errors}) -
How to capture webcam input from ReactJS, stream to Django backend and display it back on the React frontend?
I have built a virtual makeover app using python like this one: https://www.maybelline.com/virtual-try-on-makeup-tools. I want to connect this to my React frontend by capturing the webcam input, send it to the Django backend and return the video stream to the frontend so that the virtual makeover happens in real-time i.e. apply lipstick, foundation, etc. Any ideas are welcome, and please let me know if you need anymore details. Thanks in advance!!! -
How to implement a custom renderer in Django REST framework for PDF and Excel export?
I have implemented two custom renderers in django rest framework which export data in Excel or PDF format. The problem is that I'm unable to set the file names when the response is generated. I have the following renderers: # app/renderers.py import os import openpyxl import pdfkit import random from django.template.loader import render_to_string from rest_framework.renderers import BaseRenderer from rest_framework.response import Response # for newer python, do the configuration for pdfkit config = pdfkit.configuration(wkhtmltopdf=r'path_to_bin/wkhtmltopdf') class XLSXRenderer(BaseRenderer): # ... code truncated class PDFRenderer(BaseRenderer): media_type = 'application/pdf' format = 'pdf' charset = 'utf-8' def render(self, data, accepted_media_type=None, renderer_context=None): if hasattr(data, 'items'): for key, value in data.items(): if key == 'results': html_string = render_to_string('user_mbe/EmployeeList.html', {'header': ('first_name', 'last_name', 'id_number', 'phone_number', 'email', 'job_title'), 'data': [tuple(x.values()) for x in value]}) result = pdfkit.from_string(html_string, output_path=False, configuration=config) return result return None # app/views.py from rest_framework.generics import ListCreateAPIView from rest_framework.permissions import IsAuthenticated from rest_framework.renderers import JSONRenderer from .renderers import PDFRenderer, XLSXRenderer from .models import Employee from .serializers.employee import EmployeeSerializer class EmployeeAPIView(ListAPIView): serializer_class = EmployeeSerializer # Are these correct here? renderer_classes = [PDFRenderer, XLSXRenderer, JSONRenderer] def get_queryset(self): return Employee.objects.filter(created_by=self.request.user) def get(self, request, *args, **kwargs): ?? super().get_paginated_response(request, *args, **kwargs) ?? unable to set a file name here return response -
Multi-level access with ManyToMany relationships in Django
I have models, objects from which can be represented as a directed graph: from django.db import models from django.contrib.auth.models import User class Record(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=500) content = models.TextField() sequels = models.ManyToManyField('self', blank=True, symmetrical=False, through='Extend', related_name='extending') author = models.ForeignKey(User, on_delete=models.CASCADE) class Extend(models.Model): ancestor = models.ForeignKey(Record, on_delete=models.CASCADE, related_name='+') descendant = models.ForeignKey(Record, on_delete=models.CASCADE, related_name='+') class Meta: constraints = [ models.UniqueConstraint( name="%(app_label)s_%(class)s_unique_relationships", fields=["ancestor", "descendant"], ), models.CheckConstraint( name="%(app_label)s_%(class)s_prevent_self_extend", check=~models.Q(ancestor=models.F("descendant")), ), ] Anytime a new instance of Record is created and it has a relationship with another instance through the Extend model, I would love to calculate author.user.userprofile.income attribute in the User instance. The problem is I don't know how to calculate this attribute for all the ancestors of the newly created Record which follows some rule: if the newly created Record costs 50, the first-level ancestor gets 25 and 25 goes to other ancestors, constanly being divided by 2. I can write the formula for the first-level ancestor, but what for others? # In case of some purchase: class ExtendPurchase(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) items = models.ManyToManyField(Record) date = models.DateField(auto_now_add=True) cost = models.PositiveIntegerField() def calculate_income(self): for item in self.items.all(): item.author.userprofile.income += self.cost / len(self.items.all()) / 2 # first-level; if one would … -
Post request with an object via serializer many=False
I am trying to make a POST request with an object for example this is how I send my request : { "title": "Haloween", "body": " This is one of the greatest ones", "grade_level": { "id": 2, "country": "UG" }, "tags": [{"name": "Jamming"}] } So I wanted to post an object : "grade_level": { "id": 2, "country": "UG" } and below is my Serializer I use : class GradeClassSerializer(CountryFieldMixin, serializers.ModelSerializer): """GradeClass Serializer.""" class Meta: model = ClassGrade fields = ('id', 'grade', 'country', 'color_code', ) class PostSerializer(serializers.ModelSerializer): """Post Serializer""" owner = UserProfile(read_only=True) tags = TagSerializer(many=True) comments = CommentSerializer(many=True, read_only=True) slug = serializers.SlugField(read_only=True) grade_level = GradeClassSerializer(many=False) When I send the object grade_level , I cant seem to receive it it only receives the the id : def create(self, validated_data): """Create a blog post in a customized way.""" grade_level = validated_data.pop('grade_level', {}) status = validated_data.pop('status', '') post = Post.objects.create(**validated_data, owner=self.context['request'].user) if grade_level: grade = ClassGrade.objects.get(id=grade_level['id']) post.grade_level = grade post.save() return post When I make a request, this is what happens : KeyError: 'id' The object comes with only an country without an id. This is what grade_level = validated_data.pop('grade_level', {}) prints : OrderedDict([('country', 'UG')]) How can get the id from the object. NOTE: … -
Error during template rendering using extra_context django
Hello I'm using extra_context in views and in the HTML I'm passing it, but it seems that I am doing it wrong because I get this error: Error during template rendering Does anyone know why? views.py class InformacionTiendasAdd(CreateView): model=InformacionTiendas form_class=InformacionTiendasForm template_name='InformacionTiendas/informacion-tiendas-agregar.html' success_url=reverse_lazy('InformacionTiendas:list_tiendas') extra_context={'tiendas': InformacionTiendas.objects.all()} models.py class InformacionTiendas(models.Model): nombre=models.CharField(max_length=255) registro_desde=models.DateTimeField(default=datetime.now ) tax_id=models.IntegerField() def __str__(self): return f'{self.nombre} {self.registro_desde} {self.tax_id} informacion-agregar-tiendas.html <form class="needs-validation" novalidate> {% for tienda in tiendas %} <div class="row mb-3"> <div class="col-md-12"> <div> <label class="form-label" for="validationCustom01">Name</label> {{ tienda.nombre }} <div class="invalid-feedback"> Please provide the workshop name. </div> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="mb-3"> <label class="form-label" for="validationCustom06">Registration</label> {{ tienda.registro_desde }} Please provide workshop`s registration number. </div> </div> </div> <div class="col-md-6"> <div class="mb-3"> <label class="form-label" for="validationCustom07">TAX ID</label> {{ tienda.tax_id }} <div class="invalid-feedback"> Please provide workshop`s registration number. </div> </div> </div> </div> {% endfor %} </form> -
why the selected answers is not showing? django
I am trying to make a quiz app using Django and js with using &.ajax jquery function ,, everything runs ok except for selected answers I can see the result and questions everything, why is that happing I had created an input for the answers I can view them on the page. my problem is in the post this selected answer views.py @csrf_exempt def save_quiz_view(request, pk): if request.is_ajax(): questions = [] data = request.POST data_ = dict(data.lists()) # delet the csrf_token data_.pop('csrfmiddlewaretoken') for k in data_.keys(): print('key', k) question = Question.objects.get(text=k) questions.append(question) print(questions) user = request.user quiz = Quiz.objects.get(pk=pk) score = 0 # Get the ratio of user's answers multiplier = 100 / quiz.number_of_questions results = [] correct_answer = None for answer in questions: a_selected = request.POST.get(answer.text) print("selected:", a_selected) if a_selected != "": question_answers = Answer.objects.filter(question=answer) # loop through an answers of praticlar question for a in question_answers: if a_selected == a.text: # question is correct if a.correct: score += 1 correct_answer = a.text else: # both cases display the correct answer if a.correct: correct_answer = a.text results.append({ str(answer): { 'correct_answer': correct_answer, 'answered': a_selected } }) else: results.append({str(answer): 'not answered'}) score_ = score * multiplier Result.objects.create(quiz=quiz, user=user, score=score_) if score_ … -
Declarative mechanism for Django model rows
With some frequency, I end up with models who contents are approximately constant. For example, I might have a set of plans that users can sign up for, with various attributes -- ID, name, order in the list of plans, cost, whether the purchaser needs to be a student/FOSS project/etc.. I'm going to rarely add/remove/change rows, and when I do there's likely going to be code changes too (eg, to change landing pages), so I'd like the contents of the model (not just the schema) to be managed in the code rather than through the Django admin (and consequently use pull requests to manage them, make sure test deploys are in sync, etc.). I'd also like it to be in the database, though, so I can select them using any column of the model, filter for things like "show me any project owned by a paid account", etc.. What are good ways of handling this? I think my ideal would be something like "have a list of model instances in my code, and either Django's ORM magically pretends they're actually in the database, or makemigrations makes data migrations for me", but I don't think that exists? The two workable approaches … -
Printing kwargs.pop displays the right value, using it in a method takes None
I ant to pass a PK in kwargs to a form : views.py def create_mapping_form(request, pk): context = { 'form': MappingForm(pk=pk) } return render(request, 'flows/partials/mapping_form.html', context) In the form i retrieve the PK using : forms.py class MappingForm(forms.ModelForm): class Meta: model = MappingField fields = ( 'fl_col_number', 'fl_col_header', 'fl_cross_field_name', 'fl_cross_position', 'fl_replace_list' ) def __init__(self, *args, **kwargs): pk = kwargs.pop('pk', 'Rien') super(MappingForm, self).__init__(*args, **kwargs) #print(pk) self.helper = FormHelper(self) self.fields['fl_replace_list'].widget.attrs[ 'placeholder'] = "Liste de tuples eg. : [('reman','ES'), ('Gasoline','Diesel')] " headers = GetCsvHeadersAndSamples(pk)['headers'] [...] For populating some fields' CHOICES, I use a method that returns a dic (last line above) headers = GetCsvHeadersAndSamples(pk)['headers'] But something I can't explain sends 'Rien' to GetCsvHeadersAndSamples while when I print(pk) the right value is shown. (GetCsvHeadersAndSamples is not useful, I don't show it) Nota: I display the form in template using HTMX. The issue seems not coming from HTMX because when I hard-code the PK, everything is ok. For the time, I have found nothing else but stocking the PK value in a "temp" file but this slows my script. Thanks -
How to make a model's entries as a field.options list in other model's field?
I have two models - Account, like checking, wallet, credit, etc. and Transaction which includes each purchase and earning. Transaction has a foreign key to Account. In Transaction, I want users to select the Account of purchase. I considered the field.choices but the choices are permanent. I want users to select a choice of Account from Account models. How do I do that? -
bootstrap cdn not working in a django website
this is how it looks with online CDN.how I want it to look and when I give it the offline CDN path this is how it looks -
Avoid csrf token in django post method
I am making part of the web app where (unlogged users, all visitors) can fill the form and I have to save that data (name, phone number, question) in database.. I am making REST using Django, but for frontend I will use React or Django, and I am making POST method in Django framework that reads JSON data from POST https request, and then I save that data to database.. But I get error CSRF verification failed. Request aborted. because I don not use CSRF token, because it is not required for this (I do not have logged users). But I do not want to disable CSRF, because for admin page I would use this to authenticate users? So anyone knows how to avoid using CSRF token for this method? Thanks in advance.. def saveDataToDatabase(request): if request.method == 'POST': json_data = json.loads(request.body) try: data = json_data['data'] except KeyError: HttpResponseServerError("Malformed data!") This is the part of method.. -
'Stocks' object is not iterable - Django
I saw that there are other people who have my problem, but I still can't solve the problem ... thanks to anyone who will help me! models.py class Stocks(models.Model): image = models.ImageField() name = models.CharField(max_length=50) value = models.FloatField() desc = models.CharField(max_length=299) link = models.CharField(max_length=30) views.py def stocks_mt(request): return render(request, 'azmt.html', {'stock': Stocks},) home.html <div class="container"> <div class="row"> {% for Stocks in stock %} <div class="col-sm"> <br><div class="card" style="width: 18rem;"> <img src="{{stocks.image}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title text-center">{stocks.name}</h5> <!--<h5 class="card-text text-center">50.90€</h5>--> <p class="card-text ">{{stocks.desc}}</p> <h5 class="card-text text-center">{{stocks.value}}</h5> <a href="{{stocks.link}}" class="btn btn-primary">Buy</a> </div> </div> </div> {% endfor %} </div> I tried to capitalize the first letter but nothing has changed ... -
'GenericRelatedObjectManager' object has no attribute 'lang'
I am receiving the error 'GenericRelatedObjectManager' object has no attribute 'lang' when I making a post request. In this query and relationship I have two models Translation and Tags. class Translation(models.Model): """ Model that stores all translations """ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True, blank=True) object_id = models.CharField(max_length=50, null=True, blank=True) content_object = GenericForeignKey() lang = models.CharField(max_length=5) field = models.CharField(max_length=255, null=True) translation = models.TextField(blank=True, null=True) def __unicode__(self): return u'%s : %s : %s' % (self.content_object, self.lang, self.field) class Tags(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) DISEASE = 0 TYPE = [(DISEASE, 'disease')] type = models.PositiveSmallIntegerField(choices=TYPE) name = GenericRelation(Translation) description = GenericRelation(Translation) I am creating a serializer mixin to send the same data to different serializer (not only the Tag described below): SerializerTranslationField and TagSerialzer: class SerializerTranslationField(Field): def __init__(self, method_name=None, model_name=None, translation_field=None, **kwargs): self.method_name = method_name self.translation_field = translation_field self.model_name = model_name kwargs['source'] = '*' kwargs['read_only'] = True print("KWARGS ----->", kwargs) super().__init__(**kwargs) def to_representation(self, value): content_type = ContentType.objects.get_for_model(self.model_name) queryset = Translation.objects.filter(content_type=content_type, object_id=value, field=self.translation_field) result = TranslationSerializer(queryset, required=False, many=True).data final_result = {k: v for d in result for k, v in d.items()} print("FINAL RESULT --->", final_result) return final_result class TagsSerializer(NestedUpdateMixin,serializers.ModelSerializer): class Meta: model = Tags fields = ['id', 'type', 'name','description'] def __init__(self, *args, **kwargs): fields … -
How show image in django pdfkit pdf file?
I have a issue, I create detail view in html and after i convert it in pdf for all models object. i use pdfkit, however it doesnt shows object's image, then i run code with image it has some errors. def customer_render_pdf_view(request, pk): posts = get_object_or_404(Person, pk=pk) enrolment =get_object_or_404(Enrollment, pk=pk) template = get_template('test.html') html = template.render({'costumer': posts, 'enrolment':enrolment}) options = { 'page-size': 'Letter', 'encoding':' base64.b64encode("utf-8")', } pdf = pdfkit.from_string(html, False, options) response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="person.pdf"' return response my HTML code : <img src={{costumer.image.url}} height='200px'>