Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Conflict on Python Django API Deployment
Please, i'm very new to Python and Django, a friend (non developer) reached out to me on deploying django on digitalocean. I've tried troubleshooting some of my issues but dont understand how to solve the latest one: The conflict is caused by: The user requested Django==2.2.16 django-cors-headers 3.2.1 depends on Django>=1.11 django-filter 2.0.0 depends on Django>=1.11 django-phonenumber-field 4.0.0 depends on Django>=1.11.3 django-rest-knox 3.0.3 depends on django django-rq 2.3.2 depends on django>=2.0 djangorestframework 3.11.1 depends on django>=1.11 drf-yasg 1.20.0 depends on Django>=2.2.16 django-rest-logger 1.0.4 depends on Django<=2.2 and >=1.11 To fix this you could try to: 1. loosen the range of package versions you've specified 2. remove package versions to allow pip attempt to solve the dependency conflict ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/user_guide/#fixing-conflicting-dependencies ERROR: failed to build: exit status 1 I've tried visiting the address but dont know what to do with the information given. Please, help me out -
Create Dockerfile , docker-compose.yml , and nginx-setup.conf file for a Django and Next.js project
I want to create a Dockerfile , docker-compose.yml and a nginx-setup.conf file for my Django GraphQL and Next.js project in order to make it run on localhost on my machine then to make it ready to deploy it on DigitalOcean. I'd also like to add PostgreSQL too. How can I do all of that ? Here is what I've tried by now : Dockerfile for Django : FROM python:3.9-alpine ENV PYTHONUNBUFFERED=1 WORKDIR /backend COPY requirements.txt requirements.txt RUN pip install -r requirements.txt COPY . . Dockerfile for Next.js : FROM node:16.14-alpine WORKDIR /frontend COPY . . RUN npm install CMD [ "npm", "run", "dev" ] Nginx setup file : server { listen 8080; location / { root /var/www/frontend } } docker-compose.yml file : version: "3.9" services: backend: build: context: ./backend command: gunicorn app.wsgi --bind 0.0.0.0:8000 ports: - "8000:8000" depends_on: - frontend frontend: build: context: ./frontend dockerfile: Dockerfile volumes: - .:/frontend - /frontend/node_modules ports: - "3000:3000" nginx: image: nginx:latest ports: - 80:8080 volumes: - ./nginx/nginx-setup.conf:/etc/nginx/conf.d/default.conf:ro - nextjs_build:/var/www/frontend depends_on: - backend - frontend Now I know that something is off or missing , but I don't really know what is it , plus I haven't added yet the image for postgresql. -
Is there any alternative to force_bytes by django.utils.encoding?
I've been using force_bytes in one of my projects, and it is causing errors since I am using Django 3+. Question: Is there any alternative to it? What Force Bytes Does? Gives bytestring version of string with lazy instances resolved to strings -
Questions about inclusion_tag
I was follow to a old courses Udemy and I try create a project had 2 app( group & posts) and just found out that you can use: from django import template register = template.Library() To allow link models app to another app. In the old courses it just add in models.py and create tag in post_list.html to show what group you join and all group but don't create templatetags folder and how it work. Even when I check the sample it don't had any thing. So I was search gg try build it by myself, but it doesn't show anything Can you check it. Thank App groups models.py class Group(models.Model): name = models.CharField(max_length=235, unique=True) slug = models.SlugField(allow_unicode=True,unique=True) descripsion = models.TextField(blank=True,default='') descripsion_html = models.TextField(editable=False,default='',blank=True) member = models.ManyToManyField(User,through='GroupMember') def __str__(self): return self.name def save(self,*args, **kwargs): self.slug =slugify(self.name) self.descripsion_html = misaka.html(self.descripsion) super().save(*args, **kwargs) def get_absolute_url(self): return reverse("groups:single", kwargs={"slug": self.slug}) class GroupMember(models.Model): group = models.ForeignKey(Group,related_name='memberships',on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='user_groups',on_delete=models.CASCADE) def __str__(self): return self.user.username In templatetags group_tags.py from django import template from ..models import Group,GroupMember register = template.Library() @register.inclusion_tag('clonemedia/posts/templates/posts/post_list.html') def get_other_group(): group_members = GroupMember.objects.all() other_groups = Group.objects.all() return {'other_group':other_groups, 'group_member':group_members } In template post_list.html {% load group_tags %} <h5 class='title'> Your Groups</h5> <ul class='list-unstyled'> … -
Django KeyError and MultiValueDictKeyError when trying to POST
I am trying to do a POST request to Django through Vue JS, this POST request is a review to a city, When I try to POST through Vue JS I get no response so I tried using the Django API directly and each time I get the same error MultiValueDictKeyError The way I'm trying to POST this request is that each Review is connected to a specific City so I have to attach the city ID to it so I can pass to that City through the API. This is my views.py file: from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from .models import City, Review from .serializers import CitySerializer, ReviewSerializer from rest_framework.parsers import FormParser, MultiPartParser, JSONParser from django.http import HttpResponse class LatestCityList(APIView): parser_classes = (FormParser, MultiPartParser) def get(self, request, format=None): cities = City.objects.all() serializer = CitySerializer(cities, many=True) return Response(serializer.data) def post(self, request, format=None): Name = request.data['Name'] Picture = request.data['Picture'] Description = request.data['Description'] slug = Name.lower().replace(' ', '_') City.objects.create(Name=Name, Picture=Picture, Description=Description, slug=slug) return HttpResponse({'message': 'City created successfully'}, status=201) class CityDetail(APIView): parser_classes = (FormParser, MultiPartParser) def get(self, request, slug, format=None): city = City.objects.get(slug=slug) serializer = CitySerializer(city) return Response(serializer.data) class CityReviewList(APIView): parser_classes = (FormParser, MultiPartParser) def get(self, … -
Django Change boolean field with click
I am working on a To-do app. The individual to-dos reference a to-do list via a foreign key and the to-do lists reference a project via a foreign key. I want the to-do's status to be set to true when clicked. I have seen some tutorials where this is done but I haven't been able to get this to work yet. Here are the models: class Project(models.Model): title = models.CharField(max_length= 200) description = tinymce_models.HTMLField() status = models.CharField(max_length=20, choices=PROJECT_CHOICES, default="active") date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse ('project_detail', args=[str(self.id)]) class ProjectTodoGroup(models.Model): title = models.CharField(max_length=250) description = tinymce_models.HTMLField() project = models.ForeignKey(Project, blank=True, on_delete=models.CASCADE, related_name='todo_group') date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.title class ProjectTodo(models.Model): title = models.CharField(max_length= 250) notes = tinymce_models.HTMLField() status = models.BooleanField(default=False) projectgroup = models.ForeignKey(ProjectTodoGroup, blank=True, null=True, on_delete=models.CASCADE, related_name='todo_set') date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.title The view: model = ProjectTodo fields = ['status'] def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context['project'] = get_object_or_404(Project, id=self.kwargs.get('pk')) return context def get_success_url(self): return reverse('company_project:todo_group_detail', args=[self.kwargs.get('pk'), (self.object.id)]) Everything I have tried to far with the view hasn't worked. The template: {% extends 'base.html' %} {% load crispy_forms_tags %} {% … -
How to deal with unsaved nested models in serializer?
My input is a JSON object that represents a video channel. It has some simple fields and fields that contain an array e.g. tags. What I want to accomplish is parse the JSON, turn it into a Channel model object that a tags property with a list of Tag model objects. I set it up as a many to many relationship. Tag has only 1 field: title, but the JSON input is an anonymous array like "tags": ["tag1", "tag2",...]. On channelSerializer.is_valid(), it fails. Hacking around, I converted the input from "tags": ["tag1"] to "tags": ["title": "tag"] which worked but I don't like hacky solutions. I'm at a point of making a service, pull out tags, create a channel objects, convert tags independently and add it to channel...but I feel I'm missing a better, standard method. What is the recommended approach for this situation in Django? Code that definitely has some issues: class Tag(models.Model): title = models.CharField(unique=True, null=True, blank=True, max_length=255) class Meta: db_table = "tag" class Channel(models.Model): tags = models.ManyToManyField(Tag) class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ['title'] def create(self, validated_data): return Tag.objects.create(title=validated_data) class ChannelSerializer(serializers.ModelSerializer): tags = TagSerializer(many=True, read_only=False, required=False) class Meta: model = Channel fields = '__all__' -
Wrong name format. Got uploads\385757.jpg ; should be <app>.<model>/<content_field>/<mimetype_field>/<filename_field>/<filename>
I have a problem with my django project I have a form where I need load the next fields: Driver Carnet Number Driver Name Driver photo But when i load the image I have the problem, and watched the django documentation and I couldn't solve it. My model class is the next class Conductor(models.Model): ci = models.CharField(max_length=30, null=False) nombre_apellido = models.CharField(max_length=50,null=False) #para la imagen imagen = models.ImageField(upload_to='uploads') My form class class CrearConductorForm(forms.ModelForm): def __init__(self, *args, **kwargs): #user = kwargs.pop('alloweduser', None) super(CrearConductorForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs['autocomplete'] = 'off' self.helper = FormHelper() self.helper.form_tag = False self.helper.form_class = 'form-horizontal' self.helper.label_class = 'm-1 col-md-3 create-label' self.helper.field_class = 'm-1 col-md-6' class Meta: model = Conductor fields = ['ci', 'nombre_apellido', 'imagen'] labels = { 'ci': ('Cédula de Identidad '), 'nombre_apellido': ('Nombre y Apellido '), 'imagen' : ('Foto del conductor'), } My view function def crear_conductor(request): if request.method == 'POST': form = CrearConductorForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(reverse_lazy('mantenimiento:ListaConductores')) else: form = CrearConductorForm() return render(request, 'mantenimiento/CrearConductor.html', {'form' : form}) My HTML in the form tag <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <table> {{ form.as_table }} </table> <div class="row"> <div class="col-sm-6"> <button type="submit" class="btn btn-sm btn-success">Guardar</button> </div> <div class="col-sm-2 offset-sm-4"> <a class="btn btn-sm btn-danger" … -
is there a way for me to connect my html form to my Modelform
so I have a pre-built HTML form and I will like to connect the HTML form to my Model form in such a way that I will have my normal styling and don't have to render the Django form on the frontend this is the model.py class Property(models.Model): home_types = ( ('BG', 'Bungalow'), ('DP','Duplex'), ('AP','Apartment'), ('MN','Mansion'), ('VA','Villa'), ('CO','Condo'), ) list_types = ( ('FS', 'For Sale'), ('FR','For Rent'), ) property_name = models.CharField(max_length=250, default='e.g 19 Queens Ave, Encino') property_location = models.CharField(max_length=250, default='e.g 19 Queens Ave, Encino') list_type = models.CharField(max_length=2, choices=list_types, default= 'For Sale') price= models.DecimalField(max_digits=13, decimal_places=2) home_type = models.CharField(max_length=2, choices=home_types, default= 'Bungalow') property_id = models.UUIDField(primary_key=True, default=uuid.uuid4) bedrooms = models.IntegerField(default=0) bathrooms = models.IntegerField(default=0) garage = models.IntegerField(default=0) lot_size = models.IntegerField(default=0) images = models.ImageField(upload_to='property_images') description = models.TextField(max_length=600) built_on = models.DateTimeField(null=True) listed_on =models.DateTimeField(auto_now_add=True, auto_now=False, null=True) property_link = models.URLField(max_length=150, null=TRUE) def __str__(self): return self.property_location I need to find a way to submit data to the model database without changing the frontend design here is the add listing frontend link http://realtinic.com/add-listing -
Group results of queryset
I have a function that returns projectName, QuestionnaireTitle, and finalScore The function loops through every project and every questionnaire. I’m trying to format the data so that I end up with a list or a dict that contains the projectName and the scores for each questionnaire so that i can pass this into a JSChart. The format of the chart is: name: 'Project Name', data: [5,8,4,7,2,5,5,7] My current queryset is returning: {'q_rounded': 100, 'title': 'Product Evaluation', 'final_score': 5.0, 'project': <Project: C>} {'q_rounded': 100, 'title': 'Community', 'final_score': 5.0, 'project': <Project: C>} {'q_rounded': 100, 'title': 'Marketing', 'final_score': 5.0, 'project': <Project: C>} {'q_rounded': 0, 'title': 'Product Evaluation', 'project': <Project: D>} {'q_rounded': 0, 'title': 'Community', 'project': <Project: D>} {'q_rounded': 0, 'title': 'Marketing', 'project': <Project: D>} {'q_rounded': 0, 'title': 'Product Evaluation', 'project': <Project: E>} {'q_rounded': 0, 'title': 'Community', 'project': <Project: E>} {'q_rounded': 0, 'title': 'Marketing', 'project': <Project: E>} Is there a way to group the results so that I have: ProjectC,5,5,5 ProjectD ... ProjectE ... for project in all_projects: for q in questionnaires: print("getting ", q.title, "responses for", project.name, project.id) if ProjectQuestionnaireResponse.objects.filter(project_name_id=project.id, questionnaire_id = q.id).exists(): q_response = ProjectQuestionnaireResponse.objects.get(project_name_id=project.id, questionnaire_id = q.id) q_answered = ProjectQuestionnaireAnswer.objects.filter(response = q_response, answer__isnull=False).count() if q_answered > 1: q_count = (100 / … -
What is the better way to do a join query with related in Django
I have these three tables, Food, Template and CustomUser: class Food(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, default=1, on_delete=models.CASCADE, related_name="%(class)s_food", ) The template model class Template(models.Model): template_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) The user model class CustomUser(AbstractUser): first_name = models.CharField(max_length=191, null=False, unique=True) To get user's templates, I do this: self.request.user.templates.all() What I want to do is get the templates alongside the Food instances using a given template. I don't mind restructuring the models for a better way to achieve this. -
Created Field(DateTimeField) auto_now_add=True is not working in Abstract Class in Django
class TimeStampMixin(models.Model): id = models.CharField(max_length=60,editable=False,primary_key=True,default=generate_unique_id) created = models.DateTimeField(editable=False) modified = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): if not self.id: print("SAVING WHILE CREATE") self.created = timezone.now() print("MODIFY WHILE UPDATE") self.modified = timezone.now() return super().save(*args, **kwargs) class Meta: abstract = True class Sport(TimeStampMixin): name = models.CharField(max_length=100, unique=True) image = models.ImageField(upload_to=path_and_rename,null=True,blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.name = self.name.upper() return super(Sport, self).save(*args, **kwargs) Explaination I have created an abstract model TimeStampMixin with custom save method. Then i have inherited from TimeStampMixin model to Sport Model. Now whenever i'm creating Sport object it raising django.db.utils.IntegrityError: null value in column "created" of relation "events_sport" violates not-null constraint DETAIL: Failing row contains (id, Test, image,2022-04-10 13:30:00+00, 2022-04-10 14:30:00+00, 2022-04-10 12:00:00+00). Also Custom save method from timestampmixin not called. (Not print Anything). Solution I need: While updating an object created field is also get updated. auto_now_add=True in datetimeField attribute is not working!!. How to prevent this? -
How to center form fields with bootstrap and django
<form class="text-center mt-5" action="{% url 'add' %}" method="post"> {% csrf_token %} {% for field in form %} <div class="row col-md-3 mx-auto mb-3"> {{field}} {% if not field.field.required %}<span class="text-light w-25">(optional)</span> {% endif %} </div> {% endfor %} <button type="submit" class="btn btn-primary">Add</button></form> So what happens is that the button is centered but the fields are a little to the left. how do I make it so that the fields are centered and the (optional) span goes next to the ones that it has to go next to. -
Multiple update using RAW SQL in Django
I have a situation in Django where I need to update multiple rows in a database using RAW SQL, because it is a table created on another system and not managed by the ORM. Since there are multiple rows to be updated, is it possible to run a single command that updates all things at once without having to include a cursor.execute(SQL,params) inside a for loop? At the moment, I was only able to get this update to work correctly by including each update line inside a for loop, but I don't think it's a good practice. It's working something like this: person_list=[[john,33,50],[mary,20,41],[peter,12,93]] with connection.cursor() as cursor: for item in person_list: SQL="UPDATE PERSON SET NAME = %s, AGE = %s WHERE PERSON_ID = %s" params.extend([item[0], item[1], item[2]]) cursor.execute(SQL,params) I would like Django to run a single SQL command like this: SQL+=""" update person name='john', age='33' where person_id=50; update person name='mary', age='20' where person_id=41; update person name='John', age='12' where person_id=93; """ cursor.execute(SQL) I tried to do as follows, but without success, with error message "ORA-00933:SQL command not properly ended": for item in person_list: SQL+="UPDATE PERSON SET NAME = %s, AGE = %s WHERE PERSON_ID = %s; " params.extend([item[0], item[1], item[2]]) with … -
Why I can't save values in database? Django
I want to save my form in database, but save() doesn't work. When I do this, error wasn't showing. At the start, I think problem was in database, but it isn't views.py def comments(request): comments = Comment.objects.all() form = CommentForm() context = {"comments": comments, "form": form} if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.avtor = request.user comment.save() return HttpResponseRedirect(reverse('comment')) else: context["form"] = form return render(request, "home/comments.html", context) else: return render(request, "home/comments.html", context) And models. So, I think problem yet in views.py. I bad know how function save() is working. models.py class Comment(models.Model): Text = models.TextField(verbose_name='Text') date = models.DateTimeField(default=timezone.now, verbose_name='date') avtor = models.ForeignKey(User, verbose_name='avtor', on_delete=models.CASCADE) def __str__(self): return 'Comment {} at {}'.format(self.avtor, self.date) class Meta: ordering = ["-id"] forms.py class CommentForm(ModelForm): class Meta: model = Comment fields = ("Text",) At the last, I want to save avtor, text and Date. Help me please. -
How to display plotly graph on form submit in django
I have a form in django template as follows <div class="container"> <div class="bar_graph_container"> <form id="bar_graph_form" method="post" action="display_bar_graph"> {% csrf_token %} <select class="form-select bar_dropdown" aria-label="Default select example" name="bar_graph_dropdown"> <option selected>Select data to visualise</option> <option value="1">By category</option> <option value="2">By language</option> </select> </form> <div class="bar_graph_container"> </div> </div> </div> When the dropdown value changes, I want the form to submit and display the graph in the bar_graph_container div. To achieve this I tried the following js file $(document).ready(function () { $('.bar_dropdown').change(function (event) { event.preventDefault(); var data = new FormData($('#bar_graph_form').get(0)); $.ajax({ url: $(this).attr('action'), type: $(this).attr('method'), data: data, cache: false, processData: false, contentType: false, success: function (data) { console.log('form submitted successfully') console.log(data) } }) }) }) views.py def display_bar_graph(request): if request.method == 'POST': user_select = request.POST['bar_graph_dropdown'] if int(user_select) == 1: graph = plotly_helper.make_bar_graph('category', 'count', 'category', 'count', None) if int(user_select) == 2: graph = plotly_helper.make_bar_graph('language', 'count', 'language', 'count', None) # context = {'graph': graph} print('the form was submitted using ajax') return JsonResponse(graph, safe=False) While something is happening, this is just returning the entire HTML content for the page in the data variable. The print in the views.py is not printing which makes me think the view is not even running. I am not sure what I am … -
How to revert a deleted (but applied) migration in Django (MariaDB)?
The Problem (Short Description) I have a migration file deleted, but it was previously applied in the database. I want to revert the changes it has made. The Problem (Long Description) I had forked a python package and had made some changes on one of their models. I used the fork instead of the official package in my project and had my new migration applied in my database. A couple of days ago, I replaced the fork with the official version of the package and did what I wanted to do in another way without changing the model anymore. This means, that for the same app, now one migration is missing (the migration that I created). However, the changes that this migration made on the database are still present and the migration name is still listed on the django_migrations table. This has occurred weird problems, since the code and the database are not synchronized. What I have tried I tried running python manage.py migrate <appname> <previous_migration> where the appname is the app I have problem with migrations and the previous_migration is the last migration the app had before I added mine. I tried modifying the database directly by manually reverting … -
Is it possible to replace a string in a model instance field based on field original value
I need to replace a field value based on current value such that: Current:Replacement S:D D:S s:d d:s I can do it using multiple queries: myModel.objects.filter(child = ID).update(rel = Replace('rel', Value('S'), Value('D'))) myModel.objects.filter(child = ID).update(rel = Replace('rel', Value('D'), Value('S'))) myModel.objects.filter(child = ID).update(rel = Replace('rel', Value('s'), Value('d'))) myModel.objects.filter(child = ID).update(rel = Replace('rel', Value('d'), Value('s'))) However, that would require multiple database hits and only one query will match. I tried to use a hash table in the update query but I got error: nr = {'S':'D', 's':'d', 'D':'S', 'd':'s'} myModel.objects.filter(child = ID).update(rel = Replace('rel', F('rel'), nr[F('rel')])) KeyError: F(rel) I recoded my answer to solve the double replacement issue but still the database gets hit four times: myModel.objects.filter(child = ID, rel = 'D').update(rel = Value('S')) myModel.objects.filter(child = ID, rel = 'd').update(rel = Value('s')) myModel.objects.filter(child = ID, rel = 'S').update(rel = Value('D')) myModel.objects.filter(child = ID, rel = 's').update(rel = Value('d')) -
Module 'sklearn' not found when running program in VSCode
I installed sklearn using pip install sklearn. When I run scripts in Jupyter Notebook then everything works fine. I write Django app and I try to run same scripts in VSCode but Module 'sklearn' not found comes up. I guess I need to somehow install sklearn but don't know how and where. I selected Python Interpreter in VS. I also tried to install through pip3 install sklearn (my version - Python 3.10.1). I also installed this library through VS terminal (in virtual environment). Still get the same error. I also tried to install updated version pip install -U scikit-learn but in no vain. However, when I run some other Django apps (no sklearn) then it goes smoothly, I run them in my virtual environment and it works fine. -
How to make ModelSerializer field optional in Django rest framework
I have this model Reaction with code and comment fields. I have both of them null=True, blank=True in my models.py file. I want one of them to filled and other to be empty, for this I created clean method in models and validate method in serializers. But when I try to create a reaction without code/comment it says code/comment is required. models.py class Reaction(models.Model): code = models.ForeignKey(Code, null=True, blank=True, related_name="code_reactions", on_delete=models.CASCADE) comment = models.ForeignKey(Comment, null=True, blank=True, related_name="comment_reactions", on_delete=models.CASCADE) user = models.ForeignKey(User, related_name="reations", on_delete=models.CASCADE) REACTION_CHOICES = [ ("like", "Like"), ("dislike", "Dislike"), ("wow", "Wow"), ("love", "Love"), ("sad", "Sad"), ("haha", "Haha"), ("rocket", "Rocket"), ("angry", "Angry"), ] name = models.CharField(choices=REACTION_CHOICES, max_length=10) class Meta: unique_together = [["code", "user"], ["comment", "user"]] def clean(self): if self.code and self.comment: raise ValidationError(_('One reaction cannot be assigned to a code and a comment')) if not self.code and not self.comment: raise ValidationError(_("Please enter a code or a comment")) serializers.py class ReactionCreateSerializer(serializers.ModelSerializer): code = serializers.IntegerField(required=False) comment = serializers.IntegerField(required=False) class Meta: model = Reaction fields = ["id", "user", "code", "comment", "name"] def validate(self, data): if data["code"] and data["comment"]: raise serializers.ValidationError(_('One reaction cannot be assigned to a code and a comment')) if not data["code"] and not data["comment"]: raise serializers.ValidationError(_("Please enter a code or a … -
Django View that shows related views.py
i wanna get single product in my product list it shows error error line is 20 in views.py if i['_id'] == pk i cant solve this here are my views.py and errorenter image description here [enter image description here][2] -
Is there any methods to create charts based on exported excel files data using Django?
I am using the xlwt library to export Django data to Excel and ran into such a problem that this library does not support charting. What solutions can there be in such a situation? What other libraries would be suitable? Here is example of my simple Excel file export function using xlwt in Django views.py: def export_excel_av_items(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="available-items.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Available Items') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Name', 'Qty'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows = Stock.objects.all().values_list( 'name', 'quantity') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, str(row[col_num]), font_style) wb.save(response) return response I will be grateful for good advice! -
Error showing json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I am new to python and try to make recommendation engine when I click on recommendation button it throws error showing json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0). I have paste my code below: def recommend(request): user_id = request.user.id url = "http://127.0.0.1:5000/recommend/" payload = {'user_id':user_id} headers = { 'content-type': "multipart/form-data", 'cache-control': "no-cache", } responses = requests.request("POST",url,data=payload) response = json.loads(responses.text) responses_tuple = make_tuple(response) context = list() for user_id in responses_tuple: try: recommended = Product.objects.get(id=user_id) context.append(recommended) except: pass return render(request,"recommend/recommend.html",{'context': context}) -
DRF : Question about filtering with manytomany
I have two models with a many to many relationship. I have 3 tags model to categorize all the info objects. class Tag(models.Model): name= models.CharField(unique=True, max_length=100) class Info(models.Model): title = models.CharField(max_length=120) tag = models.ManyToManyField(Tag, blank = True) I want to have a list where it list all relevant Info objects base on Tag, requested by the user. I would like to know if what I'm doing is the right approach since its my 1st time building API and I havent build any frontend using backend API before so unsure if my understanding/approach is right. Question Do I : Make a Tag.objects.all() list API endpoint to expose all tags and let the frontend sort the list requested by the user with something like --> requested_relevant_tags.info_set.all() . Reverse lookup. in the frontend. In this case all I do for the backenbd API is just Tag.objects.all(). Make 3 list endpoint Info.objects.filter(tag = whatever_number1,2,3) to list info based on the tags. And when the client request, say Info.objects.filter(tag =1) then I just get grab that endpoint? I'm having a hard time imagining the actual application of this with the frontend. Do the user get to "click" the tag -> frontend do the thing with … -
Creating object on different model with logic to another model
Say I have 2 models, One is Order and the other is Item. STATUS_CHOICES = ( ('Un Finished', 'Un Finished'), ('In Progress', 'In Progress'), ('Assigned', 'Assigned For PickUp'), ('Picked Up', 'Picked Up'), ('Completed', 'Completed'), ) class Order(models.Model): product = models.CharField(max_length=100) # ... status = models.CharField( max_length=150, choices=STATUS_CHOICES, default='Un Finished') #item class Item(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Meta: ordering = ["updated"] If any of the object status in the Order model changes to Completed I want to automatically create the object in the Item models. Let's say Model Order contains and object: {id: 12 , product : "Product Name", status : "Completed"} Then here I want to update the Item with an object containing that information. How I can do this in a simpler way? I found some articles that suggest using Django signals but I'm new to Django and need little help to reproduce the solution.