Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to get results when searching in django using postgresql
I am unable to retrieve any search results when searching for items. I am using Postgresql and Django. Below is my code. I have the search bar in "inventory_management.html". I am trying to get it to where the user searches for an item, and then a list of the displayed items are shown. Any help would be greatly appreciated! models.py class Inventory(models.Model): product = models.CharField(max_length=50) description = models.CharField(max_length=250) paid = models.DecimalField(null=True, max_digits=5, decimal_places=2) bin = models.CharField(max_length=4) listdate = models.DateField(null=True, blank=True) listprice = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True) solddate = models.DateField(null=True, blank=True) soldprice = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True) shipdate = models.DateField(null=True, blank=True) shipcost = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateField(auto_now=True) def __str__(self): return self.product + "\n" + self.description + "\n" + self.paid + self.bin + "\n" + self.listdate + "\n" + self.listprice + "\n" + self.solddate + "\n" + self.soldprice + "\n" + self.shipdate + "\n" + self.shipcost views.py @login_required(login_url="/login") def search(request): q = request.GET.get('q') if q: vector = SearchVector('product', 'description') query = SearchQuery(q) searchinv = Inventory.objects.annotate(search=vector).filter(search=query) else: searchinv = None return render(request, 'portal/search.html', {"searchinv": searchinv}) inventory_management.html (where the search bar is located) {% extends 'portal/base.html' %} {% block title %}{% endblock %} {% block content %} <br> … -
Django: nested forloop not rendering
I have a "Homeworks" model, and I have a "Grades" model, and I'm trying to add a grade and show it in each homework. Everything is working great but apparently I cant save or even make the grades_form show inside a loop in a loop. Models.py class Hw_upload(models.Model): title = models.CharField(blank=True, max_length=255, null=True) description = models.TextField(blank=True, max_length=255, null=True) document = models.FileField(blank=True, upload_to='documents/', null=True) creation_date = models.DateTimeField(default=timezone.now) hw_author = models.ForeignKey(User, on_delete=models.PROTECT, related_name="hw_author") activity = models.ForeignKey(Activity, on_delete=models.CASCADE, related_name="hw_uploads", null=True) class Grades(models.Model): grade = models.PositiveIntegerField(validators=[MaxValueValidator(100)], blank=True, null=True) hw_upload = models.ForeignKey(Hw_upload, on_delete=models.CASCADE, related_name="hw_grades", null=True) Forms.py class Hw_gradeForm(ModelForm): class Meta: model = Grades fields = ['grade'] widgets = { 'grade': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': '0-100'}) } Views.py def activity(request, id): if not request.user.is_authenticated: return render(request, "auctions/login.html") activity = Activity.objects.get(id=id) try: hw_upload = Hw_upload.objects.get(id=id) except Hw_upload.DoesNotExist: hw_upload = None try: grades = Grades.objects.get(id=id) except Grades.DoesNotExist: grades = None if request.method == 'POST': form = Hw_uploadForm(request.POST, request.FILES or None) if form.is_valid(): upload_hw = form.save(commit=False) upload_hw.hw_author = request.user upload_hw.activity = Activity.objects.get(id=id) upload_hw.save() if request.method == 'POST': grade_form = Hw_gradeForm(request.POST, request.FILES or None) if grade_form.is_valid(): grade_hw = grade_form.save(commit=False) grade_hw.hw_upload = Hw_upload.objects.get(id=id) grade_hw.save() url = reverse('activity', kwargs={'id': id}) return HttpResponseRedirect(url) return render(request, "auctions/activity.html", { "activity": activity, 'hw_upload': hw_upload, 'grades': grades, 'grade_form': … -
Django Form is not submitting, even though it seems to be working
My form is still not submitting. I am stressed out now, I am rebuilding my app from the ground up because a form wasn't working (in total I have three, the other two did work), and it still isn't working. I did use the same model, so maybe it has something to do with it. That or it has something to do with two fields, the ones that are foreign keys of the other two forms. Anyway here is my code if you could check it out: #models.py class Contratos(models.Model): name=models.CharField(max_length=30) contractor=models.ForeignKey(Vendors, on_delete=models.CASCADE) contractee=models.CharField(max_length=30) start=models.DateField() end=models.DateField() cost=models.DecimalField(max_digits=9, decimal_places=2) blank='' Pesos= 'PE' Dolares='DL' CURR_CHOICES= [ (blank, '----'), (Pesos, 'MXN'), (Dolares, 'DLLS'), ] currency=models.CharField( max_length=2, choices=CURR_CHOICES, default=None, ) def is_upperclass(self): return self.currency in {self.Pesos, self.Dolares} Producto12='PR' Servicio= 'SE' Poliza='PO' Lic='LC' Otro='OT' TIPO_CHOICES= [ (blank, '----'), (Producto12, 'Product'), (Servicio, 'Service'), (Poliza, 'Policy'), (Lic, 'Licensing'), (Otro, 'Other'), ] type=models.CharField( max_length=2, choices=TIPO_CHOICES, default=None, ) def is_upperclass(self): return self.type in {self.Servicio, self.Otro} IT='IT' Fin='FN' Rec='RH' Man='MT' Cua='CR' depc_CHOICES= [ (IT, 'IT'), (blank, '----'), (Fin, 'Finance'), (Rec, 'Human Resources'), (Man, 'Maintenance'), (Cua, 'Rooms'), ] department=models.CharField( max_length=2, choices=depc_CHOICES, default=NONE, ) def is_upperclass1(self): return self.department in {self.IT, self.Cua} description =models.TextField() product=models.ForeignKey(assets, on_delete=models.CASCADE) attached_file=models.FileField(blank=True) notification=models.BooleanField(default=False) #forms.py class ContractsForm(forms.ModelForm): class Meta: … -
How to return a value from another model. Django Rest Framework
When I query all the comments of the post, I want to return the user's username. My two Models: class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey( Post, on_delete=models.CASCADE, null=False, blank=False) title = models.TextField() date = models.DateField(auto_now=True) class User(AbstractUser): objects = UserManager() username = models.CharField(max_length=60, unique=True) avi_pic = models.ImageField( _('avi_pic'), upload_to=aviFile, null=True, blank=True) My Comments Serializer: class CommentSerializer(serializers.ModelSerializer): username = serializers.SerializerMethodField('get_username_from_user') avi_pic = serializers.SerializerMethodField('get_avi_pic') class Meta: model = Comment fields = '__all__' def get_username_from_user(self, comment): username = comment.user.username return username def get_avi_pic(self, comment): request = self.context['request'] avi_pic = comment.user.avi_pic.url return request.build_absolute_uri(avi_pic) My Comments View: class CommentView(APIView): authentication_class = [authentication.TokenAuthentication] permission_class = [permissions.IsAuthenticated] serializer_class = CommentSerializer # Get all comments from current post def get(self, request): post_id = request.data.get('id') post = Post.objects.get(id=post_id) comment = Comment.objects.filter(post=post).values() serializer = CommentSerializer(comment) return Response(serializer.data, status=status.HTTP_200_OK) In my console I get: 'QuerySet' object has no attribute 'user' Appreciate any help!! -
PayPal API Cross Site Request Cookie Issue (Django, JavaScript Issue)
I'm creating a site for my senior project and have run into some trouble creating a payment portal for my site. The site was working correctly the other night, and without making any changes, the buttons now fail to render and I am being spammed with errors regarding indicating a cookie in a cross site address. Attached is the checkout.html file which the PayPal js is included within, along with the error codes I am receiving from the console. Any help would be much appreciated! {% extends 'main.html' %} {% load static %} <!DOCTYPE html> <head> <link rel="stylesheet" type="text/css" href="{% static 'css/checkout.css' %}"> </head> <body> {% block content %} <div class="row"> <div class="col-sm-6 mt-4 mb-4"> <div class="box-element" id="form-wrapper"> <h2>Recipient Information</h2> <form id="form"> <div id="recipient-info"> <div class="form-field"> <input required class="form-control" type="text" name="recipient_first_name" placeholder="Recipient First Name.."> </div> <div class="form-field"> <input required class="form-control" type="text" name="recipient_last_name" placeholder="Recipient Last Name.."> </div> <br> <div class="form-field"> <input required class="form-control" type="email" name="recipient_email" placeholder="Recipient Email.."> </div> <div class="row ml-auto"> <label class = "mt-1" for="pickup_location">Select a pickup location: </label> <select class="mt-2 ml-2" name="pickup_location" size="4" multiple> <option value="nabatieh">Nabatieh</option> <option value="tyre">Tyre</option> <option value="saida">Saida</option> <option value="beirut">Beirut</option> </select><br><br> </div> </div> <hr> <input id="form-button" class="btn btn-success btn-block" type="submit" value="Continue"> </form> </div> <br> <div class="box-element hidden" … -
leaflet does not display the map in my django application
I am developing an application with django. In a page of this application I want to display a map with leaflet. I try to display a basic map according to the information I could have on the leaflet site but nothing is displayed. There is not even an error message in the console. templatefile.html: {% extends 'elec_meter/base.html' %} {% load static %} {% block title %}Geolocalisation des compteurs - Interactiv {% endblock %} {% block titre %} Carte {% endblock %} {% block css %} <link rel="stylesheet" href="https://unpkg.com/leaflet@1.8.0/dist/leaflet.css" integrity="sha512-hoalWLoI8r4UszCkZ5kL8vayOGVae1oxXe/2A4AO6J9+580uKHDO3JdHb7NzwwzK5xr/Fs0W40kiNHxM9vyTtQ==" crossorigin=""/> <script src="https://unpkg.com/leaflet@1.8.0/dist/leaflet.js" integrity="sha512-BB3hKbKWOc9Ez/TAwyWxNXeoV9c1v6FIeYiBieIWkpLjauysF18NzgR1MBNBXf8/KABdlkX68nAhlwcDFLGPCQ==" crossorigin=""> </script> <script src="{% static 'assets/js/main.js' %}"></script> <style> <link href="{% static 'assets/css/style.css' %}" rel="stylesheet" /> </style> {% endblock %} {% block add %}{% endblock %} {% block content %} <div class="row" onload="init"> <div id="mapid" style="height:450;"> </div> </div> {% endblock %} Here is the content of my js file which initializes the map: main.js function init(){ const coordGabon = { lat: -0.803689, lng: 11.609444 } const zoomLevel = 13; const mymap = L.map('mapid').setView([coordGabon.lat, coordGabon.lng],zoomLevel); const mainLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {maxZoom: 19,attribution: '© OpenStreetMap'}).addTo(mymap); } -
how to write DRF serializers for the desired output?
need to get the following output using the below given model structure { "User": [ { "id": 1, "name": "XYZ", "Task": [ { "id": "1", "task_name": "task 1" }, { "id": "2", "task_name": "task 2" } ] }, { "id": 2, "name": "ABC", "Task": [ { "id": "1", "task_name": "task 1" } ] } ] } This is how the model is designed and I want the above output without dealing with extra database query for each record (n+1). Can this be achieved using select_related or prefetch related or something else? class User(models.Model): name = models.Charfield() class Task(models.Model) task_name = models.Charfield() class UserTask(models.Model): user = models.Foreignkey(User, related_name = 'user') task = models.Foreignkey(Task, related_name = 'tasks') -
How to get dynamically created glb from django backend to display in three.js
I have an application that takes user input and creates a 3D model from that input in a python script. I now want to visualize this 3D object using three.js. My problem is that I cannot seem to get the data from the backend to the three.js GLTFLoader in the correct format. The glb data is generated with trimesh. I am certain the 3D model is created correctly because I can output it to a file and open it in Blender. The loading of static resources in the glb format through three.js also works. But since the content is dynamically created, I do not want to save it on the server-side unless the user decides to keep it. My current approach is to try and include the 3D model in the content of a template view. The three.js documentation says, glb data can be parsed from a js BufferArray. But it seems the data gets read as a binary string in js: "b'......'" The views.py: class PreviewView(TemplateView): template_name = 'editor/preview.html' context_object_name = 'preview_generated' def get_preview(self, request): from editor.tools.gltf import GLTFConverter raw_lines = json.loads(request.POST.get('vertex_sets')) if type(raw_lines[0]) is list: lines = [np.pad(np.array(line).reshape((-1,2)),[(0,0),(0,1)], mode='constant') for line in raw_lines] else: lines = [np.pad(np.array(raw_lines).reshape((-1,2)),[(0,0),(0,1)], mode='constant')] … -
Django super user keeps getting deleted when I create a new user either from admin or register page
As mentioned above, every time I create a super user using python manage.py createsuperuser, everything works fine and I am able to log in and view the admin page as usual. However, the moment I register another user, the superuser gets deleted and can longer 1.view the login page 2. view the admin page. If I use the shell and query my users, I only have the user that was registered. Somehow the superuser gets deleted? models.py from django.db import models from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractUser, PermissionsMixin, BaseUserManager, AbstractBaseUser from .utils import generate_patient_id_for_user import uuid from rest_framework import serializers class PatientData(models.Model): id = models.AutoField(primary_key=True) heart_rate = models.IntegerField(default=0) sp02 = models.IntegerField(default=0) temp = models.DecimalField(decimal_places=2,max_digits=4, default=0) recorded_time = models.DateTimeField(auto_now=False) patient_rec = models.ForeignKey(to='CustomUser',on_delete= models.SET_NULL,null=True,blank=True) class CustomUserManager(BaseUserManager): def create_user(self, email, username, first_name, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) elif not username: raise ValueError(_('You must provide a user name')) elif not first_name: raise ValueError(_('You must provide a first name')) elif not other_fields.get('dob'): raise ValueError(_('You must provide a date of birth')) email = self.normalize_email(email) user = self.model(email=email, username=username, first_name=first_name, **other_fields) other_fields.setdefault('is_active', True) other_fields.setdefault('patient_id', generate_patient_id_for_user()) user.set_password(password) user.save() return user def create_superuser(self, email, username, first_name, password, **other_fields): … -
Django view to combine parent and child table data
I've two Django models with a foreign key relationship: class Parent(models.Model): id = models.IntegerField() parent_name = models.CharField() class Child(models.Model) id = models.IntegerField() child_name = models.CharField() parent = models.ForeignKey(Parent, related_name='parent', on_delete=models.CASCADE) Both tables are high volume so looking for something very efficient. What's the best way to write an efficient django view to return json as: Expected JSON: [ { "id": 1, "parent_name": "Elon", "childs": [ { "id": 101, "child_name": "Elon son" }, { "id": 101, "child_name": "Elon daughter" } ] }, { "id": 2, "parent_name": "Jeff", "childs": [ { "id": 101, "child_name": "Jeff son" }, { "id": 101, "child_name": "Jeff daughter" } ] } ] -
send checkout details of the orders each to anyone press checkout button to clients whatsapp api using django
enter image description hereenter image description here how to implement a function like this to send checkout details of the orders each to anyone press checkout button to clients Whatsapp api using django def products(request): products_value = Product.objects.all() return render (request, 'accounts/products.html', {'products_key': products_value}) def customer(request, pk_test): customer_value = Customer.objects.get(id=pk_test) orders_value = customer_value.order_set.all() orders_value_count = orders_value.count() context = {'customer_key':customer_value, 'orders_key': orders_value, 'orders_key_count': orders_value_count} return render (request, 'accounts/customer.html', context) def createOrder(request): form_value = OrderForm() if request.method == 'POST': form_value = OrderForm(request.POST) if form_value.is_valid: form_value.save() return redirect('/') context = {'form_key':form_value} return render(request, 'accounts/order_form.html', context) def deleteOrder(request, pk): order = Order.objects.get(id=pk) if request.method == 'POST':***emphasized text*** order.delete() return redirect('/') context={'item':order} return render (request, 'accounts/delete.html', context) def SendOrder(request ,order, sent_to_admin, plain_text, email) : if (email.id == 'customer_completed_order' or email.id == 'new_order') : link = str(str('https://wa.me/' + str(order.get_billing_phone('edit'))) + '/?text=') + urlencode('your text messages') print(str(str(str(str(str('<div style="margin-bottom: 40px;"> <h2>' + str(__('Customer WhatsApp link', 'text-domain'))) + '</h2> <p><a href="') + str(link)) + '" target="_blank">') + str(__('Contact', 'text-domain'))) + '</a></p> </div>',end=""); -
TLS with MQTT ASGI?
I want to use the MQTT ASGI Protocol Server for Django (https://pypi.org/project/mqttasgi/) but need a TLS connection for my MQTT client (I use HiveMQ as a broker). When I use port 8883 to start the server, it 'reconnects' inifinitely. Is there some way to configure TLS? Thanks in advance -
Django if check always goes into else
I'm trying to use if inside the for loop in Django, but it keeps getting into the else part. What causes this problem? yazilar.html {% for yazi in yazilar %} {{ yazi.tur }} # output : 2 {% if yazi.tur == 1 %} standart format {% elif yazi.tur == 2 %} quote format {% elif yazi.tur == 3 %} link format {% else %} nothing {% endif %} {% endfor %} -
Ajax and Django Like button
I made a like button with Ajax and it works, but only when I click on the 1st post, the like_count counter updates the instant value. The like_count value does not change after clicking the button for the 2nd and subsequent posts. ** When I click on the like button of the second and subsequent posts, I see a change in the like_count value of the first post. When I refresh the page, I see that the value of the 2nd and subsequent posts has changed.** My problem is that I want the like count value to change instantly for the 2nd and subsequent posts. could this be the problem (id="like_count") myviews.py @login_required(login_url="login") def like(request): if request.POST.get('action') == 'post': result = '' id = request.POST.get('postid') post = get_object_or_404(Post, id=id) if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) post.like_count -= 1 result = post.like_count post.save() else: post.likes.add(request.user) post.like_count += 1 result = post.like_count post.save() return JsonResponse({'result': result, }) mybutton.html {% if request.user.is_authenticated %} {% if post.like_count >= 2 %} <button style="margin-top: 10px;" class="btn btn-light like_button_true like-button" value="{{ post_item.id }}"> <img style="width: 32px; height:32px;" src="{% static 'img/likeTrue.png' %}" /> <br> <span id="like_count">{{post_item.like_count}}</span> </button> {% else %} <button style="margin-top: 10px;" class="btn btn-light like_button_detail like-button" value="{{ post_item.id }}"> <img … -
Prefetch with few filters
There is a table Order, which is connected to table Signal through FK. I loop through the records from table Signal and access the child elements from table Order. As a result, I get N+1 query. Tried to do prefetch_related, Prefetch, but nothing helps. for signal in profile.signals.prefetch_related('orders').all(): filter1 = signal.orders.filter(position_direction=OrderDirectionChoice.ENTER).order_by("exchanged_at") filter2 = signal.orders.filter(position_direction=OrderDirectionChoice.ENTER) filter3 = signal.orders.filter(position_direction=OrderDirectionChoice.EXIT) filter4 = signal.orders.filter(exchanged_at__isnull=False).first() print(filter1, filter2, filter3, filter4) -
django - saving list of base64 images
i have a django and django restframework project with postgres as database. so i send a payload from frontend to this django project and this payload is json and have one field named images. images is contain list of base64 images. so i want to save them in database and i use code below for this field: images = ArrayField(base_field=models.ImageField(upload_to='hotel_images/')) but when i want to save images i get this error: images: ["The submitted data was not a file. Check the encoding type on the form."] i understand that i have to decode base64 so that i can save them in imageField but how should i do that? how can i decode base64 this images in list one by one? or do you know a better way for this? this are some of my codes: serializer.py class HotelsSerializer(serializers.ModelSerializer): class Meta: fields = ("id", "name", "stars", "address", "description", "number_of_floors", "number_of_rooms", "room_delivery_time", "room_empty_time", "images", "features") model = Hotel models.py class Hotel(models.Model): """ model for create a hotel """ name = models.CharField(max_length=60, unique=True) stars = models.IntegerField() address = models.CharField(max_length=150) description = models.TextField(default="nitro hotel") number_of_floors = models.IntegerField() number_of_rooms = models.IntegerField() room_delivery_time = models.TimeField() room_empty_time = models.TimeField() images = ArrayField(base_field=models.ImageField(upload_to='hotel_images/')) features = models.JSONField() def __str__(self) … -
send json from template to django view and then redirect to that view
I have a template cat1.html with a listing of products . When a customer selects an item, it builds an object with properties of the selected product. If the customer clicks 'add to cart' button, axios sends a request + params stringified product object to /cart ulElement.addEventListener('click', function(event) { let targetClasses = Array.from(event.target.classList); if(targetClasses.includes('dropdown-item')) { /* code to build the item */ } if(targetClasses.includes('btn-cart')) { axios.get('/cart', { params: { item: JSON.stringify(item) } } ); } }); so far this is working fine, I can print the object/json from the server so I know it makes it through. def cart(request): item_dict = json.loads(request.GET.get('item')) user_cart.append(item_dict) print(user_cart); # this seems to work fine /* return redirect('cart') this results in error TypeError(f'the JSON object must be str, bytes or bytearray, ' */ The problem happens when I try to add a redirect to the /cart view. I get the error the JSON object must be str, bytes or bytearray, not NoneType I've tried to get around this using window.location.href and also wrapping the button in an but I get the same error, so I get the sense I'm using the wrong approach. -
How to find the no of people following a hashtag - Django
I have used Django-Taggit in the posts to add tagging in my project. My post model schema is like this : class Feed(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,related_name='feedposts') publish =models.DateTimeField(default = timezone.now) created = models.DateTimeField(auto_now_add=True) *** tags = TaggableManager() In order to make user follow the hashtags. I have added this field in the User Model Schema which looks like this. class Profile(models.Model): **** following_tags = TaggableManager() Then if the user follows the particular tag, I add that particular tag in the listed field. Now we can get the feed according to the hashtags user is following. But now I want to find out the total number of people following a particular hashtag and this is something I am not able to do. Also, Please tell me if there is any other implementation from which I can achieve this feature using django-taggit since it is easy without using it by just making a simple table of FollowedHashtags like below class FollowedHashtags(models.Model): name = models.CharField(unique = True) user = models.ManyTOManyField(User) We can get the no of people following the Hashtags: hashtag = FollowedHashtags.objects.get(id=1) nooffollowers = hashtag.user.count() I have tried some filtering queries but no success yet. So if know any other implementation … -
How to make a button show the appropriate message in Django?
I am trying to create asocial media type site that allows users to follow other users through a Django model. For some reason, the Follow Button says "Unfollow" when a user is not following the user and says "Follow" when the user is following the other user. Do you know how to display the appropriate message? (I have tried switching the True and False values but that just makes the button say "Follow" permanently.) views.py follow_or_unfollow = '' try: following = get_object_or_404(Follower, Q( user=user) & Q(followers=request.user)) print(following) except: following = False if following: follow_or_unfollow = True else: follow_or_unfollow = False if request.method == "POST": if request.POST.get('follow'): follower = Follower.objects.create(user=user) follower.followers.add(request.user) #Follower.objects.create(user=user, followers.set()=request.user) follow_or_unfollow = False elif request.POST.get('unfollow'): follower = Follower.objects.get(followers=request.user) follow_or_unfollow = True follower.remove() code in html template <form action = "{% url 'username' user %}" method = "POST"> {% csrf_token %} {% if follow_or_unfollow == True %} <input type="submit" value = "Follow" name = "follow"> {% else %} <input type="submit" value = "Unfollow" name = "unfollow"> {% endif %} </form> -
Django: Broken migration => remove old migration files
I was trying to remove on my dev machine old migration files with manage.py myapp zero But it failed at some point and I messed up. I have a project with ~1000 migration files. Unfortunately I have no backups for my dev sql database. (I have to build everything from scretch) But on my prodiction system I have also this ~1000 migration files and was wondering if it is possible to delete all migration files and just use the last state. So that each migrations folder has only one migration file left. Is this possible? This would save my life ... -
Django Foreign Key or ManyToMany is throwing an error
I am trying to connect two tables without success in Django. I have 2 models in my code: class IngredientFoodPortion(models.Model): food_code = models.ForeignKey(Ingredient, on_delete=DO_NOTHING, related_name="ingredients2") modifier = models.CharField(max_length=200, blank=True, null=True) gram_weight = models.DecimalField(decimal_places=6, max_digits=10, default=0) class MealIngredients(models.Model): meal = models.ForeignKey(Meal, on_delete=DO_NOTHING, related_name="details" , verbose_name='Meal Name', default='defaultMeal') ingredient = models.ForeignKey(Ingredient, on_delete=DO_NOTHING, related_name="ingredients" , verbose_name='Ingredients', default='defaultIngredient') serving = models.ManyToManyField(IngredientFoodPortion) amount = models.DecimalField(decimal_places=3, max_digits=10, default=0) the tables look like this: The issue is in this link: serving = models.ManyToManyField(IngredientFoodPortion) The way it should work is that if we choose the ingredient code (first column in screenshot), we should be getting back the 2nd & 3rd columns, which are usually multiple row. i tried both ForeignKey which failed because the FK is not unique, and ManyTOManyField as you can see. Any help would be appreciated. Thanks in advance, -
Update is_online field to true when user logs in
Building logic that, when a user logs in would change a boolean field in my Profile model to true and then turn that to false when the user logs out. The problem is I have an api_end point where I can see a list of all users and information related to said users. If I login as two different users (using different browsers), When I console log their information both users are shown as online: email: "user@gmail.com" ... is_online: true ... However, when I check the api_end point showing me the list of all users, only 1 user appears to be online (the last user I logged in as). This is the view related to api_end point to view all users: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all().order_by('-date_joined') serializer_class = RegisterSerializer @action(detail=True, methods=['POST']) def set_password(self, request, pk=None): user = self.get_object() serializer = PasswordSerializer(data=request.data) if serializer.is_valid(): user.set_password(serializer.validated_data['new_password']) user.save() return Response({'status': 'password set'}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is my RegisterSerializer: class RegisterSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ['username', 'email', 'password', 'first_name', 'last_name', 'profile'] extra_kwargs = { 'password': {'write_only': True}, } def validate_password(self, value): validate_password(value) return value def create(self,validated_data): profile_data = validated_data.pop('profile') user = User.objects.create(**validated_data) Profile.objects.create(**profile_data, user=user) return user … -
Get particular attribute value from django queryset (password authentication)
I am trying to implement a login system into my web page and i want to check if the password entered inside the form is equal to the users password inside the database. I can get the password from the database inside a dictionary which is inside a queryset. How can i just get the value from this dictionary? I want password_from_DB to equal to "password1234" views.py def login(request): if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): email = form.cleaned_data.get("email") password_entered = form.cleaned_data.get("password") find_person_by_email = Person.objects.filter(email=email) password_from_DB = find_person_by_email.values("password") print(password_from_DB) if password_from_DB != password_entered : print("INCORRECT") else: print("CORRECT") context = {"title": "Login"} return render(request, "myApp/login.html", context) The output from print(password_from_DB): <QuerySet [{'password': 'password1234'}]> -
Why I cannot save my template's content in my postgres database?
I have a model to rate a rented car in my Django project. However, when I submit the template's content, it seems that they are saved in the database but when I check in my data base, the table is empty. I've check all my code, I cannot find the error. Please, here are my model, views, the urls and my template respectively. Model: class tb_CARS_COMMENTS(models.Model): SCORE_CHOICES = zip(range(6), range(6) ) nom_client = models.CharField(max_length=250) vehicule = models.ForeignKey(tb_CARS, on_delete=models.CASCADE, null=True) qualite = models.PositiveSmallIntegerField(choices=SCORE_CHOICES, blank=False) prix = models.PositiveSmallIntegerField(choices=SCORE_CHOICES, blank=False) confort = models.PositiveSmallIntegerField(choices=SCORE_CHOICES, blank=False) conduite = models.PositiveSmallIntegerField(choices=SCORE_CHOICES, blank=False) email = models.EmailField(max_length=254) site_web = models.CharField(max_length=250, null=True, blank=True) Commentaires = models.TextField() def __str__(self): return 'Évaluation(Véhicule ='+ str(self.vehicule)+', Qualité ='+ str(self.qualite)\ +', Prix ='+ str(self.prix)+', Confort ='+ str(self.confort)+', Conduite ='+ str(self.conduite)+')' class Meta: verbose_name='COMMENTAIRE' verbose_name_plural='COMMENTAIRES' The views: def AddComment(request): detail=get_object_or_404(tb_CARS_CONDITIONS,id=id) form=CARS_COMMENTForm(request.POST or None) if request.method == 'POST': if form.is_valid(): print('Hello chef') obj, created = tb_CARS_COMMENTS.objects.update_or_create( vehicule=detail.vehicule_id, nom_client=request.GET.get('nom_client'), qualite=request.GET.get('qualite'), prix=request.GET.get('prix'), confort=request.GET.get('confort'), conduite=request.GET.get('conduite'), email=request.GET.get('email'), site_web=request.GET.get('site_web'), Commentaires=request.GET.get('Commentaires') ) else: print('We are not reaching here') context={ } return render(request,'Cars/comments.html', context ) The urls: app_name = 'website' urlpatterns = [ path('', views.HompePage, name='home_page'), path('about_page/', views.AboutPage, name='about_page'), path('contact_page/', views.ContactPage, name='contact_page'), path('service_page/', views.ServicePage, name='service_page'), path('liste_voiture/', views.ListeVoiture, name='liste_voirute'), path('vehicule/<int:id>/detail/', views.DetailsVoiture, name='vehicule_detail'), path('addComments/', views.AddComment, name='add_comments'), … -
Value Error in Django admin/spirits_trackers/entry
I am a noob at Django and coding in general. I am building a web app using Django to track libations and rate them as an addition to my GitHub portfolio and I am stuck. I am running into a Value Error exception when trying to add an entry or access entries to a spirit via the admin site. I've been racking my brains trying to understand why but I have no clue. I am hoping that the smarter folks on here can point me in the right direction. I am using a VENV in case that helps. Below is my models.py, views.py, spirit.html, and traceback error message. models.py from django.db import models # Create your models here. # A spirit the user is enjoying or has enjoyed. class Spirit(models.Model): text = models.CharField(max_length=50) date_added = models.DateField(auto_now_add=True) # Returns a string representation of the model. def __str__(self): return self.text # Information specific to a spirit. class Entry(models.Model): spirit = models.ForeignKey(Spirit, on_delete=models.CASCADE) type = models.CharField(max_length = 20) bottle_label = models.CharField(max_length = 150) distillery = models.CharField(max_length = 150) location = models.CharField(max_length = 50) cask_strength = models.BooleanField() proof = models.IntegerField() #abv = proof / 2 age = models.CharField(max_length = 20) barrel_select = models.BooleanField() price …