Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Relation does not exist "userAuthentication_user" when migrate Django
I am trying to install my Django project on an Ubuntu 20.04 instance on AWS. I have done the necessary configurations. But when I go to perform the migrations, I get this error. The userAuthentication_user are internal tables that are managed for authentication in Django. -
How to make an intuitive form field for a M2M relationship with many options in Django?
Apologies if the title is poorly worded, I couldn't figure out a succinct way to describe this issue. I've been working with a client who uses the Django form library to allow users to create/edit model instances. I've recently added a many to many relationship between model A and model B, and I want there to be an input on the model A form that allows users to connect instances of model B to it. The SelectMultiple widget used by Django by default is unintuitive, and the alternative CheckboxSelectMultiple widget seems like it wouldn't be great once there are 100s of options (which is a likely scenario). What complicates this further is that there's also a M2M relationship between model C and D, connected by a through table that determines a D instance's order on a C instance, and neither of those widgets work well with through tables. My initial thought was to use CheckboxSelectMultiple and just order the already selected options at the top, wrapping the widget in a scroll overflow container. I unfortunately don't know how to order options in that way though, since the accepted queryset parameter is inherently unordered. For the case with the through table, … -
Django formset missing id for manually rendered template
I am using django formset to submit a dynamically generated form (based on a file uploaded by the user). The template renders this form manually (I prefer this because it's easier for me to work on style+HTML together in template). On submitting the form, I get an error that id is a required field. My form looks like this after rendering: <form method="post" id="add3"> {{ formset.management_form }} {% csrf_token %} <table id="forms"> <tbody> {% for lst in result %} <input type="hidden" name="form-{{ forloop.counter0 }}-id" value="{{ forloop.counter }}" id="id_form-{{ forloop.counter0 }}-id"> <tr> <td> <input type="hidden" name="form-{{ forloop.counter0 }}-expense" id="id_form-{{ forloop.counter0 }}-expense" value="{{lst.0}}"/> </td> <td> <input type="hidden" name="form-{{ forloop.counter0 }}-amount" id="id_form-{{ forloop.counter0 }}-amount" value="{{lst.1}}"/> </td> {% endfor %} </tbody> </table> </form> This is a short version. I have 6 fields in each row. I am able to get all 6 fields but it complains about the id. I have added the hidden id input type in each row but that doesn't work. How can I fix this? -
How to fix Modulenotfounderror when using external files with os.environ.setdefault in Django
I put my module in a folder and tried to use it in conjunction with Django. my_module folder is not django app this is my project example structure: mysite |-- my_module | |-- __init__.py | |-- mymodule1.py | |-- mymodule2.py | |-- mymodule3.py |-- mysite | |-- settings.py | |-- base.py | |-- dev.py | |-- production.py | |--wsgi.py |-- myapp |-- manage.py in my_module/mymodule1.py import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") django.setup() if if __name__ == '__main__': # my code... When I run this python file in Pycharm, it runs without any problem. but, when I run this terminal command, it occurs error which "ModuleNotFoundError: No module named 'mysite'" How can I fix this problem? and What is the diffrence between runining at Pycharm and terminal command? -
django 4.1 polls tutorial, all done Admin working fine but index not found
ok polls tutorial is done and can enter questions, vote, etc. but from the admin pages View site aka localhost:8000 gives... Page not found (404) Request Method: GET Request URL: http://localhost:8000/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: dose/ admin/ The empty path didn’t match any of these. Now I have polls/views.py... from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.utils import timezone from django.views import generic from .models import Choice, Question class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """ Return the last five published questions (not including those set to be published in the future). """ return Question.objects.filter( pub_date__lte=timezone.now() ).order_by('-pub_date')[:5] and mysite/urls.py set to ... from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] and polls/urls.py set to... from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] The only hint I can find is that all the imports show error highlights in VSCode with the Error "reportMissingModuleSources" But python and django run perfectly well everywhere but index.html -
Converting object to an encodable object failed due to 404
Receiving 404 error while writing the data in json format. var response = await http.post(Uri.parse(url + "/api/register"), body: jsonEncode({ "username": _username.text, "first_name": _fname.text, "last_name": _lname.text, "password": _password.text, "email": _email.text, "usertype": _userDropdown.toString(), "gender": _genderDropdown.toString(),`enter code here` "bloodgroup": _bloodDropdown.toString(), "phone_no": _contact.toString() }), headers: {"Content-Type": "application/json"}); print("Status Code : " + response.statusCode.toString()); -
Django insert from data from another table using sql
I'm not so familiar in sql that execute in django. My database is PostgreSQL, now I want to insert selected data from One table to another in same database base on created date. But I got this error:IndexError: string index out of range Please help me to save my time. Thank you Here's my code: def insert(): now = datetime.today() - timedelta(days=1) now = str(now) created = datetime.strptime(date_now[:-7],'%Y-%m-%d %H:%M:%S') created= created.strftime('%Y-%m-%d') with connections['database_2'].cursor() as cursor: cursor.execute('''INSERT INTO Item .......some sql condition here..... AND date_created::date = %s ''', (''.join(created))) row = cursor.fetchone() return row The problem is here AND date_created::date = %s ''', (''.join(created))), I don't know the right way to call variable inside a sql. If I change like this AND date_created::date = %s ''', (created)throw another error TypeError: argument 1 must be a string or unicode object: got tuple instead. The date_created format from the table where I get the data is 2022-08-15 00:00:00.000 +0700. -
Django. Add foreign key to another model in view
Suppose, i have two models: Model Basket Model Apple One basket can have many apples in it, so there is one-to-many relationship between Basket and Apple. For example, here is my models: class Basket(models.Model): backet_name = models.CharField(max_length=150) owner = author = models.ForeignKey(get_user_model(), on_delete = models.CASCADE) class Apples(models.Model): apple_sort = models.CharField(max_length=150) apple_size = models.CharField(max_length=150) basket = models.ForeignKey(Basket, on_delete=models.CASCADE, related_name="apple_in_basket") I want to create a page to add basket and then to add apples to it at the same page, so i created a following forms, using formsets: class NewBasketForm(ModelForm): class Meta: model = Basket exclude = ['owner'] class AddAppleToBasket(ModelForm): class Meta: model = Apple exclude = ['basket'] AppleFormSet = modelformset_factory(Apple, form=AddAppleToBasket, extra=1, max_num=10) I want my apples to automaticly set foreign key to basket that i just created. So i created a view to insert Basket and Apple objects to the database: class BascketAddView(View): form_class_for_basket = NewBasketForm form_class_for_apples = AppleFormSet template_name = 'buskets/add.html' def get(self, request, *args, **kwargs): basket_form = self.form_class_for_apples() apples_form = self.form_class_for_answers() return render(request, self.template_name, {'basket_form': basket_form, 'apples_form': apples_form}) def post(self, request, *args, **kwargs): basket_form = self.form_class_for_basket(request.POST) apple_form = self.form_class_for_apples(request.POST) if basket_form.is_valid() and apple_form.is_valid(): print("form is valid!!!") new_basket = basket_form.save(commit=False) new_basket.owner = request.user new_basket.save() instances = apple_form.save(commit=False) for instance … -
NoReverseMatch error when trying to use Google OAuth 2.0
I am stuck on [Step 2: Redirect to Google's OAuth 2.0 server][1] of Google's Using OAuth 2.0 for Web Server Applications Guide. I have registered my application, got my client id and secret, and have the same authorized Redirect URIs in Google Developer Console than in my app. I am getting this error when I try to redirect the user to the google consent form. NoReverseMatch at /login/ Reverse for '?response_type=code&client_id=&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2F&scope=profile+openid+email&state=NZkfzNYMEqWIY1YG07eFxE6VL2YSip&access_type=offline&prompt=consent&include_granted_scopes=true' this is the function that is giving the error on the return: import google_auth_oauthlib.flow from django.shortcuts import redirect def authorize(): """ Set authorization parameters and redirect to Google's OAuth 2.0 server to prompt user for consent """ flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( client_config=client_secret.json, scopes=['profile', 'openid', 'email'] ) # Indicate where the API server will redirect the user after the user completes # the authorization flow. The redirect URI matches one of the authorized # redirect URIs for the OAuth 2.0 client in the API Console. flow.redirect_uri = 'http://localhost:8000/' authorization_url, state = flow.authorization_url( access_type='offline', prompt='consent', include_granted_scopes='true') return redirect(authorization_url) -
Why don't aggregations work correctly in Django migrations?
When I import the real model and run the query on it, I get the right answer. When I use the fake "historical" model from apps.get_model(), I get the wrong answer. Migration from django.db import migrations from django.db.models import Count from advisors.models import PlanShareRequest print(PlanShareRequest.objects.values("advisor_id", "plan_id").annotate(cnt=Count('id')).filter(cnt__gt=1)) def forward(apps, schema_editor): PlanShareRequest = apps.get_model("advisors", "plansharerequest") print(PlanShareRequest.objects.values("advisor_id", "plan_id").annotate(cnt=Count('id')).filter(cnt__gt=1)) class Migration(migrations.Migration): dependencies = [ ('plans', '0037_autoshare'), ("advisors", "0046_drop_advisor_logout"), ] operations = [ migrations.RunPython(forward, migrations.RunPython.noop), ] Output odigity@mypc:~/src/proj$ ./manage.sh migrate advisors 0047 <QuerySet [{'advisor_id': UUID('46bb6c3c-dfb6-40b2-9fd3-4cb5c413bf8a'), 'plan_id': UUID('9c789523-3319-4b2c-8192-27b43b2d5991'), 'cnt': 2}]> Operations to perform: Target specific migration: 0047_plansharerequest_unique, from advisors Running migrations: Applying advisors.0047_plansharerequest_unique...<QuerySet []> OK -
How can I get the average score calculation to be less than 0.01 seconds?
I created a function to average the comments in TVAndMovie. However, when I created 100000 comments, it took an average of 4 seconds to get the average of the scores! I have been trying to find a way to get the average of the scores. How can I reduce the time to less than 0.01 seconds? class TVAndMovie(models.Model): tmdb_id = models.IntegerField( verbose_name="", blank=False, null=False, ) judge_tv_or_movie = models.CharField( blank=False, null=False, default="movie", max_length=20 ) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)], ) def get_comments(self) -> object: return Comment.objects.filter( tv_or_movie_id=self.id ) def average_stars(self) -> float: comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = round( sum([comment.stars for comment in comments]) / n_comments, 3 ) else: self.stars = 0 self.save() return self.stars class Comment(models.Model): comment = models.TextField(max_length=1000) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)], ) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) tv_or_movie = models.ForeignKey(TVAndMovie, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: unique_together = ("user", "tv_or_movie") indexes = [models.Index(fields=["user", "tv_or_movie"])] -
How expensive is raise in Python?
During development using drf, an efficient method for error handling was needed. I found two methods, one using ErrorResponse created by inheriting Response, and one using APIException provided by drf. The first method is done through return, and the second method uses the raise command. I wonder which one is more efficient and why! I apologize in advance for the question may be too vague. -
Results are not being shown on my terminal
After writingenter image description here this code in my views.py, in order to be certain the code was working perfectly I added a print() into the if statement, but it doesn't seem to show the desired result This is the views.py 1: https://i.stack.imgur.com/aANSO.jpg Then the html is this enter image description here -
How can I fetch data from another model to create object in CreateAPIView in DRF
I have two models and their corresponding serializers: Review model: class Review(models.Model): store = models.ForeignKey(Store, to_field='id', null=True, on_delete=models.SET_NULL) customer = models.ForeignKey(CustomerProfile, to_field='id', null=True, on_delete=models.SET_NULL) product = models.ForeignKey(Product, on_delete=models.CASCADE) feedback_image = models.ImageField(upload_to='images', blank=True) comment = models.TextField(blank=True) store_rating = models.PositiveIntegerField(default=0) product_rating = models.PositiveIntegerField(default=0) Review serializer class ReviewSerializer(serializers.ModelSerializer): feedback_image = serializers.ImageField(required=False) class Meta: model = Review fields = '__all__' Order model: class Order(models.Model): store = models.ForeignKey(Store, to_field='id', null=True, on_delete=models.SET_NULL) customer = models.ForeignKey(CustomerProfile, to_field='id', null=True, on_delete=models.SET_NULL) order_ref = models.CharField(max_length=20, unique=True, null=True) ... Order serializer class OrderSerializer(serializers.ModelSerializer): customer = serializers.ReadOnlyField(source='customer.email') class Meta: model = Order fields = ['order_ref', 'store', 'customer',...] I want to create a review instance but only have the following fields in the client payload: { "order_ref": "10001111401218982", "comment": "black black", "store_rating": 5, "product_rating": 4, "product": 1 } As you can see above, the payload is missing store and customer fields. These fields are in the Order model and can be gotten with the order_ref. I am trying to override the generics.CreateAPIView for the Review model so I can use the order_ref to first get the missing fields, and then create the Review object. Review view: class ReviewCreate(generics.CreateAPIView): permission_classes = [AllowAny] queryset = Review.objects.all() serializer_class = ReviewSerializer def create(self, request, *args, **kwargs): data … -
Django: view_name() missing 3 required positional arguments: 'email', 'amount', and 'product'
I am writing a simple logic for payment of product, i am passing in the some parameters in the function like name, 'amount', 'email' etc, but i started getting this error that says missing 3 required positional arguments: 'email', 'amount', and 'product' i cannot really tell where the problem is coming from? Views.py @login_required def productCheckout(request, pk): ... if request.method == "POST": order_item = OrderItem.objects.create(user=user, product=product) order_item_id = order_item.id product = Product.objects.get(id=pk) name = request.POST.get("name") email = request.POST.get("email") amount = request.POST.get("amount") return redirect(str(process_payment_product(name,email,amount, product, order_item_id))) context = {"product":product,} return render(request, "marketplace/product-checkout.html", context) def process_payment_product(name, email, amount, product, order_item_id): auth_token= settings.FLUTTER_SECRET_KEY hed = {'Authorization': 'Bearer ' + auth_token} ... ... -
Websocket notifications in django
I am implementing web socket notifications into my Django project and am having trouble with passing the user the the amount of unread notifications that they currently have. My solution to this problem was to simply send all objects in the notification model class to the user once they connected to the web socket as messages in the web socket itself, which initially worked, but breaks if there are more then one tab open as each new tab connects to the web socket again which in turn will send the web socket messages again to any other open tab logged in to that user. ending up with duplicates of the same notification. What i need is a way display all notifications on each page when it is loaded. Preferably without sending it through the context of a view My consumers.py @database_sync_to_async def create_notification(notification): """ function to create a notification. :param notification: notification in json format to create notification object """ user = User.objects.get(username=notification["target"]) NotificationsModel.objects.create( target=user, sender=notification["sender"], alertType=notification["alertType"], title=notification["title"], message=notification["message"], ) class NotificationConsumer(AsyncWebsocketConsumer): async def websocket_connect(self, event: dict) -> None: if self.scope["user"].is_anonymous: await self.close() else: self.group_code = self.scope["url_route"]["kwargs"]["group_code"] await self.channel_layer.group_add(self.group_code, self.channel_name) await self.accept() # Since removed the send notifications from here … -
How to rename the ManytoMany Model in Django Admin
I have two models: class ModelA(models.Model): id = models.AutoField() name = models.ManyToManyField(ModelB) class ModelB(models.Model): id = models.AutoField() In the Django Admin page, I noticed that I now see a table called "modelA-modelB relationships". Is this the expected outcome? If so, how can I rename this to be something more user-friendly? I've tried several parameters verbose_name, related_name, and db_table for the ManytoManyField and none seem to overwrite the default name. -
python django - exclude class from makemigrations
Let`s say I have a class: class A(models.Model, GrandparentClassSharedByAllClasses): value = models.CharField(max_length=2000, blank=False, null=False) def __str__(self): return self.value class Meta: verbose_name = _('test') verbose_name_plural = _('tests') can I somehow exclude it from makemigration/migrations? Why would I want that? -> Class A is one of manny classes of which all others save the objects in the db. Class A should bring the same functionality like the other classes, so it can be used in the same pipeline, but not be stored in the db. -
how to sum(details_item_quantity) as an admin action in django
Hi! I need to know the quantity of sales made in a range of time and the subtotal per Item as an admin action in django admin. for example: between 6:30 and 7:00 pm of jan.01, 2022. customer-1: bought "1" item(666000354) for $1000 and "1" item(666000251) for $35 customer-2: bought "1" item(666000251) for $35 Show somethin like this: Total: $1070 Item(666000354) - qtty:1 - total_item: $ 1.000 Item(666000251) - qtty:2 - total_item: $ 70 The view of "TICKETS" in the django admin already show Tickets and Details_Ticket in a single view, so I want to make something similar, I know how to filter the new consulted-ticket and all that, but not how to correctly add every quantity and price per item because the details to SUM, are in another table. And another thing,how to search a date?, bc the list_filter in admin.py search for a string... models.py: class Ticket(models.Model): ticket_id =models.AutoField(primary_key=True) customer_id=models.ForeignKey(Customers, models.DO_NOTHING, blank=true, null=true) date= models.DateTimeField(blank=True, null=True) total= models.IntegerField(blank=True, null=True) class Meta: db_table='tickets' class Details_ticket(models.Model): detailsticket_id = models.AutoField(primary_key=True) ticket_id = models.ForeignKey(Ticket, models.DO_NOTHING, blank=true, null=true) item_id = models.ForeignKey(CartItems, models.DO_NOTHING, blank=true, null=true) qtty = models.IntegerField(blank=True, null=True) total_item= models.IntegerField(blank=True, null=True) -
Django link to JavaScript works from desktop platfroms but not mobile platforms
I recently finished upgrading a Django 1.9.6 project to 4.0.5. Everything is finally working well with one minor glitch. I have a function (JavaScript) that is called from within a form. The code uses an tag. I've used both href= and onclick=. Everything works when called from a desktop platform; Windows, Mack, or Linux. With a mobile platform like iOS or Android the link doesn't respond at all. Other controls on the page work fine. I compared the page with the original code and both versions are identical. I am not the original author of the code. I have to assume that this did work at one point as the owner has pointed it out to me. I've never run across something like this before and I'm at a bit of a loss as to where to look. Any suggestions would be greatly appreciated. Thanks in advance! -
Get the max value in Django queryset for a foreign key
Hell all, I have two models as following class Publisher(models.Model): location = models.CharField() some_other_field = models.CharField() class Author(models.Model): publisher = models.ForeignKey(Publisher, related_name='authors', on_delete=models.CASCADE) name = models.CharField() lastname = models.CharField() location = models.CharField() class Books(models.Model): author = models.ForeignKey(Author, related_name='books', on_delete=models.CASCADE) date_published = models.DateField() I want get the Max number of books for a given group of actors that belong to a certain set of publishers. Something along these lines: publisher_ids = [1, 2, 3] max_books = Author.objects.filter(publisher_in__in=publisher_ids).aggregate(max_value=Max('books')) Any help is really appreciated!!! -
Changing posts and information on form/page and getting an users information without directing to another page
I am creating a Django based website and it includes users information page. At the left side (can be seen in picture) I printed the usernames dynamically. I want to refresh the information of user when I clicked to a username without changing page or something. (It only shows the information of logged in user now.) Only want to change information written on the form. -
Set default media files in Docker using Django
I am deploying my Django web application using Docker and Docker Compose, Nginx and Postgresql. I have already done the deployment and it works well. But I have a problem with the default media files. When I was deploying in local and in my server, I add those default media files manually to the media folder, but now with Docker I can't do that. One of my models would be that one, which has a default image "dictionary/default.png" and obviously when I run my docker image doesn't load because it doesn't exist anywhere. class Dictionary(models.Model): dictionary_name = models.CharField(max_length=200) dictionary_picture = models.ImageField(upload_to='dictionary', default='dictionary/default.png') I was thinking to have these default media files locally and copy them to the Docker media folder in the Dockerfile, but I do not know if this is possible. -
How to keep a user logged in (even when phone turns off ) on a React Native app with Django backend?
I am beginning to code with react native and I am trying my first app. I am in the process of making the login/signup of the app. I managed to log the user in but I cannot seem to figure out how to keep the user logged in when I close the app. How can I keep a user logged in to the app even when the app is closed? This is what I have- login.js import { StatusBar } from 'expo-status-bar' import { StyleSheet, Text, View, FlatList, Image, Button, Pressable, ScrollView } from 'react-native'; import React, {useState, useEffect} from 'react' import { TextInput } from 'react-native-gesture-handler'; export default function Login(props) { const message = props.navigation.getParam('message', null) const [ username, setUsername ] = useState("") const [ password, setPassword ] = useState("") const log = () => { fetch(`http://192.168.5.223:8000/home/login/`, { method: 'POST', headers: { "Content-Type": 'application/json' }, body: JSON.stringify({ username: username, password: password}), }) .then( res => res.json()) .then( res => { console.log(res) if (res.valid === true){ if (res.set === true){ props.navigation.navigate("Home", {"user": username}) } else { props.navigation.navigate("Profile", {"user": username}) } } else { props.navigation.navigate("Login", {'message': "username/password are incorrect"}) } }) .catch( error => console.log(error)) } const sign = () => … -
K8's pod status: OutOfmemory
I have a Django application deployed on an Azure Kubernetes Service (AKS). It's using Redis as a server and Celery instances for the workers. I'm running into a new issue where one of the pods has a status of OutOfmemory and soon as it's redeployed. For example, I'll run kubectl delete -f deployment/dendro-pod-prod-2.yaml to remove the pod and kubectl apply -f deloyment/dendro-pod-prod2.yaml to redeploy it. When I run kubectl get pods immediately after, I see a status: NAME READY STATUS RESTARTS AGE dendro-backend 1/1 Running 1 84d dendro-celery 1/1 Running 0 23h dendro-celery-3 0/1 OutOfmemory 0 4s I would think that redeploying should reset the memory. I've tried increasing the memory for the requests and limits in the YAML file. I'm new to kubernetes, and the only related solutions I'm finding online have to do with the OOMKilled status.