Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get user object based on username and not the (id, pk) in Django
I am having struggles viewing other profiles with the users username in the URL, I am able to see there pages with the users ID, but not with there usernames, this is the url now http://127.0.0.1:8000/user/30/, but I want to have this http://127.0.0.1:8000/user/reedlyons/. I know I could do it with the get_object_or_404, but I was wondering if there is another way around that. Here is my views.py def profile_view(request, *args, **kwargs): context = {} user_id = kwargs.get("user_id") try: profile = Profile.objects.get(user=user_id) except: return HttpResponse("Something went wrong.") if profile: context['id'] = profile.id context['user'] = profile.user context['email'] = profile.email context['profile_picture'] = profile.profile_picture.url return render(request, "main/profile_visit.html", context) urls.py urlpatterns = [ path("user/<user_id>/", views.profile_view, name = "get_profile"), ... -
Mathjax with Vue.js
I am rather stumped as to how I can render Tex equations in my html. I have a vue project with django in the backend as the CMS. I am using Ckeditor as a rich text field which uploads the equation within markdown from an api. In my vue page I can render all the text with no issues using v-html but my mathematical equations are rendering like this: \(x = {-b \pm \sqrt{b^2-4ac} \over 2a}\) I have tried many ways to no avail and I can currently get a test equation to render by adding this to index.html <script> MathJax = { tex: {inlineMath: [['$', '$'], ['\\(', '\\)']]} }; </script> <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js">. </script> and this to my vue page: <span class='math-tex'>( \(\frac{2}{7},\frac{2}{18}\) )</span> However I cant seem to get it to work with inline math and text. Here is my vue div: <template v-if="$store.state.user.isAuthenticated"> <template v-if="activeLesson"> <span v-html="activeLesson.long_description"></span> </template> </template> Whats strange as well is when I add the test equation <span class='math-tex'>( \(\frac{2}{7},\frac{2}{18}\) )</span> in the template v-f section it doesnt render? What am i doing wrong? Please halp. -
how to round a MoneyField in Django
Use django-money to reprent a product rate. The Model is defined as follows. class ItemPrice(models.Model): """ Item price """ rate = MoneyField(_('Unit rate'), max_digits=10, decimal_places=2, default_currency='USD') If I want to have the rounded rate in template, such as USD200 but not USD200.23, how to write the code? -
How to import swagger/?format=openapi to postman from django-rest-swagger without error of format not recognized?
Our project use django-rest-swagger to manage API, and we would like to export all api and import Postman, I can get JSON by below url localhost:5000/swagger/?format=openapi, but when I import the file, postman says Error while importing: format not recognized, How to import swagger/?format=openapi to postman from django-rest-swagger without error of format not recognized? Is there anyone who knows some easy way to solve it? Thanks so much for any advice. { swagger: "2.0", info: { title: "TestProjectAPI", description: "", version: "" }, host: "localhost:5000", schemes: [ "http" ], paths: { /api-token/: { post: { operationId: "api-token_post", responses: { 201: { description: "" } }, parameters: [ { name: "data", in: "body", schema: { type: "object", properties: { pic_id: { description: "", type: "string" }, phonenumber: { description: "", type: "string" }, checkcode: { description: "", type: "string" }, user_phone: { description: "", type: "string" }, phone_code: { description: "", type: "string" }, username: { description: "", type: "string" }, password: { description: "", type: "string" } } } } ], description: "User Login", summary: "User Login", consumes: [ "application/json" ], tags: [ "api-token" ] } }, /porject_management/: { get: { operationId: "porject_management_list", responses: { 200: { description: "" } … -
Using metamask to authenticate a SSO flow
Is it possible to do something like a social signup/login using crypto wallets like Metamask? Analogous to signup/login with Google/Facebook/Apple... Does the concept even make sense? I'm thinking that the user could prove he owns the wallet, but there is no profile data like email/name/avatar so basically every usual datapoint of signup must be provided manually anyway, so what would be the point in some sense. If it is possible, are there any libraries that support this in Django/Python? -
How to pass multiple arguments from one template to another template?
I'm creating a to do list, and on the detail page I have a list of tasks. And when I click on the delete button on the side of the task, it will bring me to a delete confirmation page. Question I've been stuck for a long while trying to figure a way to pass in 2 different pks(dailies.pk & task.pk) from the detail page to the delete confirmation page, so that I can click the delete button to delete task(associated with task.pk) or click "back" to return to the previous page(with dailies.pk as a reference). Currently i'm only able to pass in one argument dailies_detail.html: <h3> <p> {{dailies.date}} Dailies pk({{dailies.pk}}) <a href="{% url 'task-create' dailies.pk %}">Add task</a> </p> {% for todo in dailies.dailytask_set.all %} <br> {{todo.task}} {{todo.pk}} <a href="{% url 'task-delete' todo.pk %}"> Delete</a> {% endfor %} </h3> I tried to do {% url 'task-delete' todo.pk dailies.pk %}, that didn't work URLS: urlpatterns = [ path('', DailiesListView.as_view(), name='home'), path('dailies/<int:pk>/', DailiesDetailView.as_view(), name='todo-detail'), path('dailies/<int:pk>/task-create/', TaskCreate.as_view(), name='task-create'), path('dailies/<int:pk>/task-delete/', TaskDelete.as_view(), name='task-delete'), # I kind of wanted to do something like 'dailies/<int:dailies_pk>/task-delete/<task_pk>/' ] I know that I need to do something with the URL in order to take in both arguments, not quite sure … -
Django no static files after deploying to AWS Elasticbeanstalk?
I have successfully deployed django application to single instance elasticbeanstalk. But the issue is that, css and js are not loading up. As by default Elastic Beanstalk uses Nginx, i think i am missing something. Note: I have used certbot for ssl and ngnix configs are updated by certbot. My django settings: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ BASE_DIR / 'project/static' // All static files at this directory only ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'project/static/files') In the above, I have a directory inside project called static. And all my static files are presented over there only. And my elastic beanstalk config: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: config.wsgi:application aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: config.settings aws:elasticbeanstalk:environment:proxy:staticfiles: /static: static container_commands: 01_collectstatic: command: "source $PYTHONPATH/activate && python manage.py collectstatic --noinput" Note: I have moved my django settings to separate folder named config. And by adding this aws:elasticbeanstalk:environment:proxy:staticfiles elastic beanstalk added a new section named Static files and it also has /static and static Am not sure where am doing wrong. As i have already mentioned aws:elasticbeanstalk:environment:proxy:staticfiles am not sure if i need to add alias to ngnix config for static files. Please advice. -
The problem with django in the server must be closed and opened every time
I am facing a problem with django. The server must be closed every time something changes, even if it is in the link, for example, localhost:8888/admin and I run the server and visit the site, the control panel appears, but when I change the link in the urls file. py to localhost:8888/any, the browser says that the link does not exist and shows me the option localhost:8888/admin, note that the problem appeared recently and appeared only when using template html and linking it to the project -
Image URL not getting redirect to port 8000 of Django while working with React
I am working on a project where backend is Django Rest Framework and frontend is React. I have a Product Screen where I have Product details listed down. In Product Screen I first fetch product object from Redux store and then use that product to render details and also image of the product from the URL. Fetching product object from Redux store: const productDetails = useSelector((state) => state.productDetails); const { error, loading, product } = productDetails; Image Tag: <Image src={product.image} alt={product.name} fluid /> I have setup a setupProxy.js file where I set the target port 8000. SetupProxy.js const { createProxyMiddleware } = require("http-proxy-middleware"); module.exports = function (app) { app.use( "/api", createProxyMiddleware({ target: "http://127.0.0.1:8000", changeOrigin: true, }) ); }; But when I have image uploaded from Django Admin Panel the image url in Product Screen turns out to be: http://localhost:3000/images/sample.jpg instead of: http://localhost:8000/images/sample.jpg How can I fix this issue? -
Error: 'django.db.utils.IntegrityError: NOT NULL constraint failed: base_user.is_superuser'
Hi, I'm creating a registration form in django and this error occured. Tried many things and just came for help Here's my code RegistrationForm class RegistrationForm(UserCreationForm): full_name = forms.CharField(max_length=255, widget=forms.TextInput(attrs={'class': 'inpt', 'placeholder': 'Insira o seu nome completo'})) email = forms.EmailField(max_length=255, help_text="Required email", widget=forms.EmailInput(attrs={'class': 'inpt', 'placeholder': 'Insira o seu email'})) password1 = forms.CharField(max_length=255, widget=forms.PasswordInput(attrs={'class': 'inpt', 'placeholder': 'Insira a sua password'})) password2 = forms.CharField(max_length=255, widget=forms.PasswordInput(attrs={'class': 'inpt', 'placeholder': 'Confirme a sua password'})) class Meta: model = User fields = ('full_name', 'email', 'password1', 'password2') UserManager class UserManager(BaseUserManager): def create_user(self, email, full_name, password=None, is_staff=False, is_admin=False, is_superuser=False): if not email: raise ValueError('User must have an email address') if not password: raise ValueError('Users must have a password') user_obj = self.model( email = self.normalize_email(email) ) user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.full_name = full_name user_obj.save(using=self.db) return user_obj def create_superuser(self, email, full_name, password=None): user = self.create_user( email, password=password, full_name=full_name, is_staff=True, is_admin=True, is_superuser=True ) return user My register view ... context = {} if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password1') user = authenticate(email=email, password=raw_password) login(request, user) return redirect('home') else: context['registration_form'] = form else: form = RegistrationForm() context['registration_form'] = form ... By far thank you for your attention! I think the … -
How to fetche the near point (X,Y) object stored in db by filter
I want to fetch the near data. for example in this case id x y 1 243.242 5124.3242 2 143.242 4724.3242 3 240.242 374.3242 4 243.242 1424.3242 I want to get the point near 240,240 in this case 3 is most close to the point. I can do this after fetch the item row by row. However it takes so much time. I want to do this like filter or Q for django model. How can I do this? -
Django PostgreSQL Heroku works correctly on localhost, works on Heroku until database used
There are many similar questions on here, but the solutions have not helped and I cannot find this exact case listed. My project is made with Django and PostgreSQL and deployed on Heroku. When using localhost, everything works well. Deploying to Heroku works and everything works until I make a POST request. The error I get is Server Error (500). I turned on debug in production and got these messages: "connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections?" Why would everything work fine on localhost and deploy fine but not work when I begin to use the database? -
Show multi-selected itens when load a edit view
I'm doing a edit form for some data. I'm having problem to pass information to . As you can see in my view, I pass the data to form using "initial" dictionary. VIEWS.PY @login_required def project_detail(request, project_id): if request.method == 'POST': project = get_object_or_404(Project, pk=project_id) form = ProjectDetailForm(project_id, request.POST, instance = project) if form.is_valid(): instance = form.save(commit=False) instance.client = Project.objects.get(pk=project_id).client form.save() messages.success(request,'Projeto modificado') return redirect('projects') else: messages.error(request,'Ocorreu um erro!') else: project = get_object_or_404(Project, pk=project_id) form = ProjectDetailForm(project_id, initial={'modal':project.modal, 'culture':project.culture, 'owner':project.owner, 'value':project.value, 'final_date':project.final_date, 'text':project.text, 'status':project.status, 'farm':project.farm.values()}) return render(request,'project_detail.html',{'form':form}) But doing this, the data is not displaied in . Thinking here, ManyToManyField saves data in lists. I tried iterate this field but still not working and I guess thats not the best way to do this. MODELS.PY class Project(models.Model): modal_types = [('CUSTEIO AGRÍCOLA','Custeio Agrícola'),('CUSTEIO PECUÁRIO','Custeio Pecuário'),('INVESTIMENTO AGRÍCOLA','Investimento Agrícola'),('INVESTIMENTO PECUÁRIO','Investimento Pecuário'),('FGPP','FGPP')] status_opts = [('Análise','Análise'),('Desenvolvimento','Desenvolvimento'),('Processamento','Processamento'),('Liberação','Liberação'),('Finalizado','Finalizado'),('Cancelado','Cancelado'),('Suspenso','Suspenso')] farm = models.ManyToManyField(Farm, related_name='farm_name',verbose_name='Propriedade beneficiada') client = models.ForeignKey(Clients, on_delete=models.CASCADE, related_name='project_client',default=None,null=True, verbose_name='Cliente') owner = models.ForeignKey(Owner, on_delete=models.CASCADE, related_name='project_bidder',default=None,null=True, verbose_name='Proponente') warranty = models.ManyToManyField(Farm, related_name='project_warranty',default=None, verbose_name='Propriedade de garantia') modal = models.CharField(max_length=100,default=None,choices=modal_types, null=True, verbose_name='Tipo') culture = models.CharField(max_length=50,null=True, verbose_name='Cultura') status = models.CharField(max_length=50,null=True, verbose_name='Status', choices=status_opts) created_date = models.DateField(null=True, verbose_name='Data de criação') value = models.FloatField(max_length=10,null=True, verbose_name='Valor financiado') final_date = models.DateField(default=None,null=True, verbose_name='Fim do contrato') text = models.TextField(default=None,null=True, verbose_name='Observações') … -
How to filter WHERE , OR on django with serializer,model and view?
I'm making a request via GET with the following query: site.org/mymodel?ordering=-created&state=awaiting_review and I have updated to send with multiple states: site.org/mymodel?ordering=-created&state=awaiting_review,phone_screened,interview_scheduled,interview_completed,offer_made,hired,rejected But I have not found a doc in django that specifies how to treat it. So I'm not sure what to do right now. Maybe there is a vanilla option of how to do it. The following codes are a mock of the current ones. What kind of function of part of django/python should I use to receive a filtered query with multiple values ? the current one complains throwing this as response too. { "state": [ "Select a valid choice. awaiting_review,reviewed,phone_screened,interview_scheduled,interview_completed,offer_made,hired,rejected is not one of the available choices." ] } Should I change the URL too ? Model.py: ` class MyModel(): STATE_OPTIONS = ( ("awaiting_review", "awaiting_review"), ("reviewed", "reviewed"), ("phone_screened", "phone_screened"), ("interview_scheduled", "interview_scheduled"), ("interview_completed", "interview_completed"), ("offer_made", "offer_made"), ("hired", "hired"), ("rejected", "rejected"), ) state = models.CharField( max_length=19, choices=STATE_OPTIONS, default="awaiting_review", null=False ) Serializer.py: class ASerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ( state ) ` view.py: ` class MyModelView(generics.ListAPIView, ProtectedResourceView): serializer_class = ASerializer filter_fields = ("state") ordering_fields = ("state") def get_queryset(self): return MyModel.objects.filter(user=self.request.user).filter( something_thats_not_state = self.request.query_params.get("something_thats_not_state") ) ` -
Django - Query by foreign key in views
I am trying to make a button on the post that when a user cliks on it, is requesting to be added to the post as an attendance and then, the author of the post has to approve that request. Models.py class Attending(models.Model): is_approved = models.BooleanField(default=False) attending = models.ManyToManyField(User, related_name='user_event_attending') class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) attending = models.ForeignKey(Attending, on_delete=models.CASCADE, verbose_name='atending', null=True) My problem here is that every time I writte a query for the button is giving me erros and I couldn`t figure it out how to get the reverse of the foreign key. This is my code on my views.py def request_event(request, pk): previous = request.META.get('HTTP_REFERER') try: query = Attending.objects.get(pk=pk) request_attending = query.post_set.add(request.user) messages.success(request, f'Request sent!') return redirect(previous) except query.DoesNotExist: return redirect('/') Thank you very much for your help in advance! -
symbol not found in flat namespace '_png_do_expand_palette_rgb8_neon' Mac M1 Pycharm error
I am trying to use face_recognition for python in my django project but it does not seem to work as it is giving error when i write import face-recognition I am using it in pycharm, M1 macbook air, django rest framework. Following is the versions Python 3.8 face_recognition 1.3.0 dlib 19.23.0 here is error: ImportError: dlopen(/venv/lib/python3.8/site-packages/_dlib_pybind11.cpython-38-darwin.so, 0x0002): symbol not found in flat namespace '_png_do_expand_palette_rgb8_neon' If anyone can help me solve this error or know any work around to get it working ? -
How to make domain extension in Django
I am making a website, and i want to add an extension for it, like users.example.com. I have searched a lot and came up with nothing. Would I have to create a whole new website, or is there something else that I could do? -
Error sending mail in shell but not in codebase - Django
I have this code in my codebase, I am using Sendgrid: from django.core.mail import send_mail try: mail_sent = send_mail( 'Header', 'Body', 'sender@email.com', ['reciever@email.com'], fail_silently=False) except SMTPException: raise SMTPException() except Exception as e: print('Error sending mail: {0}'.format(e)) And the mail_sent object is ALWAYS 1, which means that the email was sent. Even if I inject an error by changing the sender address. BUT in shell if I run the same send_mail the error is thrown, a 403 forbidden. I have no idea why this is happening but it is messing with my testing. Any thoughts? I am using Docker and have placed my API KEY in the docker-compose file. It seems tha the shell is functioning but the app isn't. -
Trouble with Django ASGI (DAPHNE) Deployment on HEROKU
i've been trying to deploy for the last couple days and I just can't seem to get it working: on heroku , it says application deployed but then when i go into the logs I see errors. I try opening up the app (for example, admin page) and I get application error. I've tried calling the get_asgi_application prior to importing anything else, that didn't work. Here are the errors i recieve: ERROR File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/registry.py", line 136, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Process exited with status 1 State changed from starting to crashed at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=myappname.herokuapp.com request_id=18f76666-adff-40f8-83ae-55df56d78208 fwd="24.150.189.187" dyno= connect= service= status=503 bytes= protocol=https my asgi file: import os from django.core.asgi import get_asgi_application import django #from channels.auth import AuthMiddlewareStack #from channels.security.websocket import AllowedHostsOriginValidator from channels.routing import ProtocolTypeRouter, URLRouter #from .settings import ALLOWED_HOSTS from myappnameapp.routing import * os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myappname.settings') django.setup() #from django.urls import path django_asgi_app = get_asgi_application() from myappname.auth_middleware import TokenAuthMiddleware application = ProtocolTypeRouter({ # (http->django views is added by default) "http": django_asgi_app, 'websocket': TokenAuthMiddleware( URLRouter( websocket_urlpatterns ) ), }) my procfile: release: python manage.py migrate web: daphne myappname.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker channel_layer -v2 SETTINGS … -
relation " " does not exist in Django
I have a doubt what does it mean: relation "clientes" does not exist LINE 1: select nombre from Clientes where joindate between "2022-02-... It seems strange to me; or that this error appears since my model is called Customers; I just did the migrations on heroku, but I get this error In my views I have this: def list_clientes(request): if request.method == 'POST': fromdate=request.POST.get('fromdate') todate = request.POST.get('todate') searchresult=Clientes.objects.raw('select nombre from Clientes where joindate between "'+fromdate+'" and "'+todate+'"') return render(request,'Clientes/clientes-list.html',{'clientes':searchresult}) else: displaydata = Clientes.objects.all() return render(request, 'Clientes/clientes-list.html', {'clientes': displaydata}) models.py class Clientes(models.Model): tipo = models.CharField(max_length=200) nombre = models.CharField(max_length=200) fecha_registro = models.DateTimeField(default=datetime.now) def __str__(self): return f'{self.nombre}' settings.py DATABASES = { 'default': { 'ENGINE':'django.db.backends.postgresql_psycopg2', 'NAME':'sistemacarros_db', 'USER':'postgres', 'PASSWORD':'1234', 'HOST':'localhost', 'PORT':'5432', 'OPTIONS':{ 'init_command':"SET sql_mode='STRICT_TRANS_TABLES'", } } } -
How do I filter a Django Model by month or year from a JSON dict?
I am trying to parse through a JSON database and filter by month or by year using Django and this is driving me up a wall since this should be simple. An example of the dict key value pair in the JSON object is formatted as so: "release_date": "2022-12-25T07:00:00", From my views.py file, I set up this function to filter the model: @api_view(['GET']) def yearList(request,pk): queryset = Character.objects.filter(release_date__year=pk) serializer = CharacterSerializer(queryset, many=True) return Response(serializer.data) And in my urls.py, I have this urlpattern (ignoring every other pattern) urlpatterns = [ path('year/<str:pk>', views.CharacterList.as_view(), name="Character by year" ) ] I followed this link to get the idea to append "__year" to the release_date attribute when filtering the queryset. But it's not filtering the database, I'm still seeing all objects. Where am I going wrong? I can't look to filter by months if I can't even get the years filtered, so I'm focusing on the year first. Thank you in advance. -
Extracting data from Django Queryset and inserting into a Python list
I am trying to get one column of data from a Django model into a python list for further processing the in Django view. I have successfully created a simple Django model and populated the data. The fields are: "id", "x_coord", "y_coord". I have run a few commands to extract data from the model. I want to get the values from the "x_coord" field into a Python list so I can then apply the statistics.mean method to all the values. I have had some success in extracting data, see below the Django commands I have issued in the shell, but I can't get the data into a Python list. Any assistance will be appreciated. set environment (in mysite directory) python manage.py shell from polls.models import CC_pts_to_avg temp_list = CC_pts_to_avg.objects.values_list('x_coord',flat=True) >>> temp_list <QuerySet [Decimal('0.60'), Decimal('0.60'), Decimal('0.45'), Decimal('0.60'), Decimal('0.90'), Decimal('0.60'), Decimal('0.60'), Decimal('0.50'), Decimal('0.60'), Decimal('0.60'), Decimal('0.60'), Decimal('0.65'), Decimal('0.60'), Decimal('0.60'), Decimal('0.60'), Decimal('0.60'), Decimal('0.60'), Decimal('0.60'), Decimal('0.50'), Decimal('0.75'), '...(remaining elements truncated)...']> >>> >>> temp_list[0] Decimal('0.60') >>> temp_list[2] Decimal('0.45') >>> type(temp_list[0]) <class 'decimal.Decimal'> >>> type(temp_list) <class 'django.db.models.query.QuerySet'> >>> -
problem with a field that expected a number but got another thing
im using django 4.0.2 and making a cart but when i make the check out, i get this error any suggestion to make it work? i appreciate your help i have in checkout.py this code class Checkout(LoginRequiredMixin, View): def post (self, request): addres = request.POST.get('addres') comment = request.POST.get('comment') cart = request.session.get('cart') user= request.session.get('user') product = Product.get_product_by_id(cart) print(addres, comment, User, cart, product ) for product in product: print(cart.get(str(product.id))) order = Order(user_id=user, product=product, price=product.price, addres=addres, comment=comment, quantity=cart.get(str(product.id))) order.save() request.session['cart'] = {} return redirect ('cart:cart_detail') #i have a cart.py code to that have some values, but i can't see where is the problem i'm following some tutorials to do this code. my cart.py from django.conf import settings from product.models import Product class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product): if str(product.id) not in self.cart.keys(): self.cart[product.id]={ "product_id": product.id, "title":product.title, 'quantity': 1, 'id': int(product.id), "image":product.image.url, "thumbnail":product.thumbnail.url, "price": str(product.price) } else: for key, value in self.cart.items(): if key== str(product.id): value["quantity"] = value["quantity"]+ 1 break self.save() def save(self): self.session["cart"] = self.cart self.session.modified = True def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def decrement(self, product): … -
How to access Django models outside of Django?
I am trying to access my Django models from a script that will be run outside of any Django views. It will be a standalone script and not related to any Django views etc, however, I would like to be able to use the Django ORM to update fields in the database. My standalone script is in the data directory: I have tried endless suggestions from SO, such as the code below, but I keep hitting a similar issue - "ModuleNotFoundError: No module named 'nft.settings'" import django import sys import os sys.path.append('/Users/chris/Documents/Python/Django/nft/') # This path being the directory at the top of my screenshot os.environ.setdefault("DJANGO_SETTINGS_MODULE", "nft.settings") django.setup() from nft_app.models import Object Any help would be greatly appreciated -
Django - Too many similar queries
I'm creating a music rating app and I'm making a serializer for albums which has many relations and one aggregation method serializer which I think is causing all the trouble. The method gets average and count of reviews for every album. That's how album serializer looks. "id": 2, "title": "OK Computer", "slug": "ok-computer", "created_at": "2022-02-22T21:51:52.528148Z", "artist": { "id": 13, "name": "Radiohead", "slug": "radiohead", "image": "http://127.0.0.1:8000/media/artist/images/radiohead.jpg", "background_image": "http://127.0.0.1:8000/media/artist/bg_images/radiohead.jpg", "created_at": "2022-02-22T00:00:00Z" }, "art_cover": "http://127.0.0.1:8000/media/album/art_covers/ok-computer_cd5Vv6U.jpg", "genres": [ "Alternative Rock", "Art Rock" ], "reviews": { "overall_score": null, "number_of_ratings": 0 }, "release_date": "1997-05-28", "release_type": "LP", "tracks": [ { "position": 1, "title": "Airbag", "duration": "00:04:47" }, { "position": 2, "title": "Paranoid Android", "duration": "00:06:27" } ], "links": [ { "service_name": "spotify", "url": "https://open.spotify.com/album/6dVIqQ8qmQ5GBnJ9shOYGE?si=L_VNH3HeSMmGBqfiqKiGWA" } ], "aoty": null Here is a queryset in album Viewset class AlbumViewSet(ModelViewSet): queryset = Album.objects.prefetch_related("tracks").prefetch_related("album_genres").prefetch_related( "album_links").prefetch_related("reviews").select_related("aoty").select_related("artist_id").all() Here is a method serializer that I use to get the average and count of reviews of certain album def get_avg_and_count_of_reviews(self, album: Album): reviews = Review.objects.only("rating").filter(album_id=album.id).aggregate( overall_score=Avg(F("rating"), output_field=IntegerField()), number_of_ratings=Count(F("rating"), output_field=IntegerField())) return reviews reviews = serializers.SerializerMethodField( method_name="get_avg_and_count_of_reviews")