Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why I get an "name 'os' is not defined" error (with import os done)
Good day! I write simplest code #!/usr/bin/python3 import os import os.path dirname = os.path.dirname(__file__) or '.' os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings") from django.template.loader import render_to_string rendered = render_to_string('Login.html', {'foo': 'bar'}) And got an error BASE_PATH = os.path.dirname(__file__) ^^ NameError: name 'os' is not defined. Did you forget to import 'os'? Clearly I don't forgot "import os". Any way to deal with this error? I try different code parts from any advice find on web, but no luck at all. -
Django Prefetch object with generic relation
As stated in the documentation: class Prefetch(lookup, queryset=None, to_attr=None) The Prefetch() object can be used to control the operation of prefetch_related(). The queryset argument supplies a base QuerySet for the given lookup For example, it can be used to specify the columns from the related object to SELECT, by using only(): Author.objects.prefetch_related(Prefetch("hometown", City.objects.only(["name"])) However, when prefetching the objects related through a generic relation, what model should be passed to the queryset param of Prefetch? I can't see any references to that on the docs nor SO. Something like: Prefetch("foo", GenericRelation.objects.only(["title"])) -
What's wrong with this Django view fucntion editpage func, EditForm class and editpage.html?
I am trying to just display page contents in console after the form is submitted. Also how to change editpage.html file's 'name' variable in such a way that instead of hardcoding 'ewew' variable name can be passed with name of each different pages.debug display on browser debug display on browserserver console view file of django: from django.shortcuts import render from . import util from django.http import HttpResponseRedirect from django.urls import reverse from django import forms from string import Template import markdown2 import re def writetofile(name,entryBody): file1 = open(f"encyclopedia/templates/wiki/{name}.html","w") file1.write('{% extends "encyclopedia/layout.html" %}\n') file1.write('{% block body %}\n') file1.write(entryBody) #editLink=f"<a href=\"{% url 'encyclopedia:editPage',{"name":{name}} %}\">Edit Page</a>" #editLink=f"<a href=\"{% url 'encyclopedia:editPage' name=name %}\">Edit Page</a>" #editLink=f"<a href=\"{% url 'encyclopedia:editPage' name='{name}' %}\">Edit Page</a>" #editLink="<a href=\"{% url 'encyclopedia:editPage' name='{}' %}\">Edit Page</a>".format(name) #editLink="<a href=\"{\% url 'encyclopedia:editPage',{'name': %s} \%}\">Edit Page</a>".format(name) #editLink = Template("<a href=\"{% url 'encyclopedia:editPage' , {name:'$name' }} %}\">Edit Page</a>") editLink = Template("<a href=\"{% url 'encyclopedia:editPage' name='$name' %}\">Edit Page</a>") editLink=editLink.substitute(name=name) print(editLink) file1.write(editLink) file1.write('\n{% endblock %}') file1.close() def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def newPageError(request): return render(request, "encyclopedia/newpageerror.html") #def content(request): def wiki(request,name): #name=request.GET.get('name') entryBody=util.get_entry(name) if entryBody: entryBody= markdown2.markdown(entryBody) writetofile(name,entryBody) #file1 = open(f"encyclopedia/templates/wiki/{name}.html","w") #file1.write('{% extends "encyclopedia/layout.html" %}\n') #file1.write('{% block body %}\n') #file1.write(entryBody) #file1.write('\n{% endblock %}') #file1.close() return … -
Trying to ban user as a super user (banned user can't create posts)
i give permission to my superuser to ban all the other types of users, this my views.py file: @login_required(login_url='login') def Home(request): posts = Post.objects.all() if request.method == "POST": #taking the id i passed in value attribute post_id = request.POST.get("post_id") user_id = request.POST.get("user_id") if post_id: post = Post.objects.filter(id=post_id).first() if post and (post.auther == request.user or request.user.has_perm('main.delete_post')): post.delete() elif user_id: user = User.objects.filter(id=user_id).first() if user and request.user.is_staff: try: group = Group.objects.get(name="default") group.user_set.remove(user) print("removed successfully") except: print("something went wrong") pass try: group = Group.objects.get(name="mode") group.user_set.remove(user) print("removed successfully") except: print("something went wrong") pass return render(request,"main/home.html", {"posts":posts}) my html file: {% if user.is_staff %} <form method="post"> {% csrf_token %} <button type="submit" class="btn btn-warning" value={{post.id}} name="user_id">Ban User</button> </form> {% endif %} i tried to print messages if the user is removed and it printing removed successfully, and then i logged as that banned user i can still create post,did i miss something in views.py? -
Get values from 2 database statements with radio buttons
I am trying to connect two database statements via two radio buttons. As soon as I change the radio button value, these have to be retrieved again directly via the database. I am currently trying to do this via HTML, JavaScript and Python. However, only one of the two statements is currently displayed. js: $("#id_base-0-show_null").change(function () { var show_null_value = document.querySelector('input[name=base-0-show_null]:checked').value; var checked_0 = document.getElementById('id_base-0-show_null_0').checked; var checked_1 = document.getElementById('id_base-0-show_null_1').checked; console.log(show_null_value, checked_0, checked_1); **currently doesn't do anything** }); exporter.py: def get_last_values_of_target(self, target_type, target_name): ... def get_zero_values_of_target(self, target_type, target_name): ... manual_input.py: def get_last_values_of_target(request): if is_ajax(request): target_type = int(request.POST['target_type']) target_name = request.POST['target_name'] exporter = Exporter() exporter.station = target_type values = exporter.get_last_values_of_target(target_type, target_name) **here is the current single exporter where i'm trying to add a second one (get_zero_values_of_target)** return HttpResponse(simplejson.dumps({'values': values}), 'application/javascript') else: return HttpResponseBadRequest("Not allowed") template: {% block content %} <form action="" method="post" id="manual_input_form" name="manual_input_form"> {% csrf_token %} <div class="timeDiffer"> {% for base_form in base_formset %} *** <div class="{% if base_form.non_field_errors %}error {% else %}showDiff{% endif %}"> <div>{{ base_form.show_differences.label_tag }}{{ base_form.show_differences }}</div> </div> {% if base_form.show_differences %} <div class="{% if base_form.non_field_errors %}error {% else %}showNull{% endif %}"> <div class="flex">{% trans base_form.show_null.label_tag %}{{ base_form.show_null }}</div> </div> {% endif %} {% endfor %} <input type='hidden' … -
python makemigration creating tables error
Traceback (most recent call last): File "C:\python\lib\threading.py", line 980, in _bootstrap_inner self.run() File "C:\python\lib\threading.py", line 917, in run self._target(*self._args, **self._kwargs) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\apps\registry.py", line 124, in populate app_config.ready() File "C:\Users\Asus\Documents\projects\valeohr\backend\app\apps.py", line 9, in ready from .jobs import updater File "C:\Users\Asus\Documents\projects\valeohr\backend\app\jobs\updater.py", line 3, in <module> from app.jobs.jobs import Syncing File "C:\Users\Asus\Documents\projects\valeohr\backend\app\jobs\jobs.py", line 8, in <module> class Syncing: File "C:\Users\Asus\Documents\projects\valeohr\backend\app\jobs\jobs.py", line 13, in Syncing db = DB.get_db('geco1') File "C:\Users\Asus\Documents\projects\valeohr\backend\app\models\base.py", line 14, in get_db dbo = cls.objects.filter(code=db).first() File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\models\query.py", line 1047, in first for obj in (self if self.ordered else self.order_by("pk"))[:1]: File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\models\query.py", line 394, in __iter__ self._fetch_all() File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\models\query.py", line 1867, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\models\query.py", line 87, in __iter__ results = compiler.execute_sql( File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1398, in execute_sql cursor.execute(sql, params) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\backends\utils.py", line 103, in execute return super().execute(sql, params) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers( File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\backends\utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\Asus\Documents\projects\valeohr\venv\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return … -
CSS on the site is not visible
I'm working on a project using Django. I imported HTML files and created a Base HTML. I placed CSS and images in a folder named 'static' and imported them, but the CSS is not appearing on the site, only the HTML. Would you like me to share the code? I try to change something on setting.py -
How can I troubleshoot an authentication issue?
When making a request to http://127.0.0.1:8000/auth/users/reset_password/. The endpoint works only if i include ""rest_framework_simplejwt.authentication.JWTAuthentication" at(DEFAULT_AUTHENTICATION_CLASSES) but not when using my Custom authentication "passportBackend.custom_auth.JWTOrOAuth2Authentication".I think the documentation of rest_framework_simplejwt it returns None when permission is not required. from rest_framework.authentication import BaseAuthentication from rest_framework_simplejwt.authentication import JWTAuthentication from oauth2_provider.contrib.rest_framework import OAuth2Authentication from rest_framework.exceptions import AuthenticationFailed class JWTOrOAuth2Authentication(BaseAuthentication): def authenticate(self, request): # Try authentication additional_info = request.META.get("HTTP_X_ADDITIONAL_INFO") # # DRF OAuth2 # print(additional_info) if additional_info == "OAuth2": oauth2_authentication = OAuth2Authentication() oauth2_user, oauth2_auth = oauth2_authentication.authenticate(request) if oauth2_user is not None: return oauth2_user, oauth2_auth # # Simple JWT # elif additional_info == "jwt": jwt_authentication = JWTAuthentication() jwt_user, jwt_token = jwt_authentication.authenticate(request) if jwt_user is not None: return jwt_user, jwt_token return None def authenticate_header(self, request): # Override this method if needed pass "DEFAULT_AUTHENTICATION_CLASSES": ( "passportBackend.custom_auth.JWTOrOAuth2Authentication", ), How can I troubleshoot an authentication issue with my custom JWTOrOAuth2Authentication class ? -
How to connect to the existing database through NGINX?
I have a project what I need to start with Docker. I've successfully created images and containers of Django, NGINX and postgreSQL, so the project starts correctly. I noticed that when I try to login to the admin panel, Django raises OperationalError at /admin/login/ connection to server at "database" (192.168.144.2), port 5432 failed: fe_sendauth: no password supplied. Everything worked fine without nginx, but now I cannot access to the database. As I understand the problem, I need to change nginx.config, but I tried almost everything and still cannot figure this out. Seems like postgreSQL doesn't see my user maybe. My code snippet below. uwsgi.ini [uwsgi] wsgi-file = config/wsgi.py strict = true socket = :8000 protocol = http master = true no-orphans = true die-on-term = true lazy-apps = true processes = 4 threads = 8 enable-threads = true max-requests = 500 reload-on-rss = 1024 worker-reload-mercy = 60 harakiri = 60 harakiri-verbose = true vacuum = true post-buffering = 1048576 buffer-size = 65535 nginx.conf worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; include /etc/nginx/uwsgi_params; server { listen 80; server_name localhost; location / { proxy_pass http://django:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header … -
Can't make Telegram WebApp Validation work using python
I am unable to validate data that Telegram sent to my WebApp.. import hashlib import hmac import json import typing from urllib.parse import unquote def parse_init_data(init_data: str) -> typing.Dict: return dict(param.split("=") for param in init_data.split("&")) def parse_user_data(user_data: str) -> dict: return json.loads(unquote(user_data)) def _extract_hash_value(init_data: str) -> str: return parse_init_data(init_data)["hash"] def generate_secret_key(telegram_bot_token: str, c_str: str = "WebAppData") -> str: c_str_enc = c_str.encode() token_enc = telegram_bot_token.encode() return hmac.new(token_enc, c_str_enc, digestmod=hashlib.sha256).hexdigest() def validate(init_data: str, secret_key: str) -> bool: hash_ = _extract_hash_value(init_data) unquote_init_data = unquote(init_data) sorted_init_data = sorted( [chunk.split("=") for chunk in unquote_init_data.split("&") if chunk[: len("hash=")] != "hash="], key=lambda x: x[0], ) sorted_init_data_str = "\n".join([f"{key}={val}" for key, val in sorted_init_data]) init_data_enc = sorted_init_data_str.encode() secret_key_enc = secret_key.encode() data_check = hmac.new(init_data_enc, secret_key_enc, digestmod=hashlib.sha256).hexdigest() return hmac.compare_digest(hash_, data_check) this code is from github. It is intended to validate data coming from Telegram to my WebApp.. I have passed all necessary things.. extracting user data from Telegram Sent data is working. But validating that data is from Telegram failing. This is initData I got query_id=AAHkHFkqAAAAAOQcWSqv8eyu&user=%7B%22id%22%3A710483172%2C%22first_name%22%3A%22Ro%27zmat%22%2C%22last_name%22%3A%22Otajonov%22%2C%22username%22%3A%22OtajonovR%22%2C%22language_code%22%3A%22en%22%2C%22is_premium%22%3Atrue%2C%22allows_write_to_pm%22%3Atrue%7D&auth_date=1713215281&hash=c7907965154661f6f322d02e4a97086568e033980818396b623649ba3a062685 and this code is my django view that trying to validate using above functions: from django.shortcuts import render from .webapp_auth import parse_init_data, parse_user_data, validate, generate_secret_key from django.contrib.auth import get_user_model User = get_user_model() def business_settings_view(request): … -
Most Efficient Way To Add Email Field of Auth User Model From A ManyToMany Field When Sending Email
In the code below I would like to add the email of the user's email field directly into the recipient's variable below in the notification function. How would one achieve this? class Pass(models.Model): guest_name = models.CharField(max_length=128,blank=False,verbose_name="Guest") date = models.DateField(blank=False,null=False,verbose_name='Date') area = models.CharField(max_length=128,blank=False,verbose_name='Area(s)') member_name = models.CharField(max_length=128,blank=False,verbose_name="Member") member_number = models.IntegerField(blank=False) phone = models.CharField(max_length=14,blank=False,null=False) email = models.EmailField(max_length=128,blank=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='pass_users', blank=True, null=True, ) managers = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='passes', blank=True, limit_choices_to = {'is_active': True}) def __str__(self): return '%s' % (self.guest_name) def get_absolute_url(self): return reverse('guestpass:pass_detail', kwargs={'pk':self.pk}) @receiver(post_save, sender=Pass) def notification(sender, instance, **kwargs): if kwargs['created']: subject = 'New Guest Pass' message = '%s guest pass has been created.' %(instance.guest_name) sender = 'noreply@email.com' recipients = [?] send_mail( subject, message, sender, recipients, fail_silently=False, ) -
Should model fields be tested in Django?
class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField(null=True, blank=True) date_of_death = models.DateField('Died', null=True, blank=True) MDN says: You don't need to explicitly test that first_name and last_name have been stored properly as CharField in the database because that is something defined by Django ... However you should check the text used for the labels (First name, Last name, Date of birth, Died), and the size of the field allocated for the text (100 chars), because these are part of your design and something that could be broken/changed in future. If I wanted to follow that advice, I would not write a test that tests that the field only accepts 100 characters, since that would mean testing Django's behavior. Instead, I would write a test that tests that max_length indeed equals 100. This test could look something like this: def test_max_length(self): self.assertEqual(models.Author._meta.get_field('first_name').max_length, 100) My feeling is that this test would basically be the same as testing that I wrote what I wrote. Of course, if a wrong max_length breaks some other piece of code, that should be tested, but it should be tested in that other piece of code. What are the best practices for testing Django model fields? … -
Django Python - What does _ do after a variable name
Sorry for my poor explanation but I'm reviewing my professor's code like this: user, _ = User.objects.get_or_create( name = serializer.data['name'], email = serializer.data['email'], password = make_password(serializer.data['password'])) when I remove the ", _" from that I can't access the objects (eg: name) of it. I was doing "user.name" but I cant without the ", _" can someone explain why that is. It's my first time here in in SO hehe I wanna access the name field through the user where I assigned the object I created -
Django HttpReponse: can't change file name (XMLHttpRequest)
I am trying to implement a file download feature via an XMLHttlpRequest. The response is formed as follows: response = HttpResponse(entries, content_type='application/text charset=utf-8') response['Content-Disposition'] = f'attachment; filename={self.title}.docx' So, the title should be something like 'Book.docx'. Instead, on every download I get a UUID-like title that is different, wrong, and has no extension, e.g. 'b691dac0-9498-414f-9c5b-a96223998b76'. Encoding the title with urlquote or .encode() doesn't help. -
Django - Need guidance on filtering data by keywords
In my web-app project, I have a page for advanced search. Initially, all the items from db should be displayed on front-end. From admin interface, for each item I have added keywords separated by comma. What I want to do is to filter the items on FE based on those keywords. Example: the wine has keywords like: red, dry . When I click on one of those options on front-end, the corresponding wines should be shown. I have created the template, added views and some javascript but now I'm stuck and I don't understand where the logic lacks. Here is the template piece: <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false"> Filter </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton" id="filterOptions"> <li><a class="dropdown-item" href="#" data-keyword="red">Red</a></li> <li><a class="dropdown-item" href="#" data-keyword="sparkling">Sparkling</a></li> <li><a class="dropdown-item" href="#" data-keyword="white">White</a></li> <li><a class="dropdown-item" href="#" data-keyword="sweet">Sweet</a></li> <li><a class="dropdown-item" href="#" data-keyword="dry">Dry</a></li> <li><a class="dropdown-item" href="#" data-keyword="citrus">Citrus</a></li> </ul> </div> <section class="products section-padding"> <div class="container"> <div class="row"> {% for wine in page_obj %} <div class="col-lg-4 col-12 mb-3"> <div class="product-thumb"> <a href="product-detail.html"> <img src="{{ MEDIA_URL }}{{ wine.image.url }}" class="img-fluid product-image" alt=""> </a> <div class="product-info d-flex"> <div> <h5 class="product-title mb-0"> <a href="product-detail.html" class="product-title-link">{{ wine.name }}</a> </h5> <p class="product-p">{{ wine.description }}</p> </div> </div> </div> </div> {% endfor %} … -
Django. 'GroupDetailView' object has no attribute 'object'
I try create AddMembersForm to Group in my app. 'GroupDetailView' object has no attribute 'object' class GroupDetailView(DetailView): model = Group context_object_name = 'group' template_name = 'rooms/group_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = AddGroupMemberForm(group_id=self.object.id) context['members'] = GroupMembers.objects.filter(group=self.object) #Download all members return context def post(self, request, *args, **kwargs): form = AddGroupMemberForm(request.POST, group_id=self.object.id) if form.is_valid(): new_member = form.save(commit=False) new_member.group = self.get_object() new_member.save() return redirect(self.get_object().get_absolute_url()) else: return self.render_to_response(self.get_context_data(form=form)) ----------------------------------------------------------------------------------- class Group(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='creator_group', on_delete=models.CASCADE) name = models.TextField(max_length=50) description = models.TextField(max_length=500) def __str__(self): return self.name def get_absolute_url(self): return reverse('group_detail', kwargs={'pk': self.pk}) class GroupMembers(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='membership') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='group_membership') role = models.TextField(max_length=30, default='Członek grupy') time_release = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.user.username} należy do {self.group.name}' I want to add users to my groups (the group founder will have this option). -
Issue with session authentication not being preserved across calls from React frontend to Django backend
I have the following code: LoginPage.js: import React from 'react'; import axios from 'axios'; import { useNavigate, Navigate } from 'react-router-dom'; import { Button, Grid, TextField } from '@mui/material' import DisplayAppBar from './DisplayAppBar'; export default function LoginPage() { const [username, setUsername] = React.useState(''); const [password, setPassword] = React.useState(''); const navigate = useNavigate(); const handleLogin = async (e) => { e.preventDefault(); try { axios.post('http://localhost:8000/login/', { username: username, password: password }).then((response) => { // navigate('/home'); // Navigate to home page axios.get("http://localhost:8000/check-login-status/") .then(response => { console.log(response.data); }) .catch(error => { console.log(error); // return <Navigate to="/" />; }) }).catch(error => { console.error(error); }); } catch (error) { console.error(error); } } return ( <div> <DisplayAppBar /> <Grid container direction="column" justifyContent="center" alignItems="center" spacing={2} > <Grid item> <TextField required label="Username" variant="outlined" id="usernameField" onChange={(e) => setUsername(e.target.value)}/> </Grid> <Grid item> <TextField required label="Password" variant="outlined" id="passwordField" onChange={(e) => setPassword(e.target.value)}/> </Grid> <Grid item> <Button variant="outlined" onClick={handleLogin}>Login</Button> </Grid> </Grid> </div> ) }; urls.py: from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from TeamData import views urlpatterns = [ path('club/', views.ClubListCreate.as_view()), path('club/<int:pk>/', views.ClubDetail.as_view()), path('swimmer/', views.SwimmerListCreate.as_view()), path('swimmer/<int:pk>/', views.SwimmerDetail.as_view()), path('user/', views.UserListCreate.as_view()), path('user/<int:pk>/', views.UserDetail.as_view()), path('login/', views.LoginView.as_view(), name='login'), path('logout/', views.LogoutView.as_view(), name='logout'), path('signup/', views.UserListCreate.as_view(), name='signup'), path('check-login-status/', views.CheckLoginStatus.as_view(), name='check-login-status'), ] urlpatterns = format_suffix_patterns(urlpatterns) views.py: from django.shortcuts import render from … -
What is the right way to run github actions for my django project on ec2?
I have a django project that's hosted on ec2. Everytime I want to update my application I have to push the code from vscode, pull it from my server, reload nginx, and restart uvicorn. I've been doing this every single time but I want to automate it with github actions. Am I supposed to have following commands in my yml fie or is there a better way to do this: cd myproject/myproject git pull origin main sudo systemctl reload nginx sudo systemctl restart uvicorn -
Efficient way to order Annotate field in DRF
I have three models in models.py, class AAA(models.Model): name = models.CharField(max_length=300, null=False, blank=False) class BBB(models.Model): aaa = models.ForeignKey(AAA, on_delete=models.CASCADE, null=False, blank=False) content = models.CharField(max_length=300, null=False, blank=False) class CCC(models.Model): aaa = models.ForeignKey(AAA, on_delete=models.CASCADE, null=False, blank=False) name = models.CharField(max_length=300, null=False, blank=False) and I want to order in views.py, class AAAListCreateView(generics.ListAPIView): class AAAPagination(CursorPagination): page_size = 2 queryset = ShortForm.objects.all().annotate( b_count=Count("bbb", distinct=True), c_count=Count("ccc", distinct=True), total=F('b_count')+('c_count') ) serializer_class = AAAListSerializer pagination_class = AAAPagination filter_backends = [DjangoFilterBackend, OrderingFilter] filterset_class = AAAListFilterSet ordering_fields = ['b_count', 'c_count', 'total'] ordering = 'b_count' The problems that I want to ask are... I want to descending all of my ordering_fields. Descending order without specifying -b_count or -c_count or -total. In views.py, I annotate all of my ordering_fields. But I think it is not efficient way because it fetches all sorting annotate fields. -
Django.core.exceptions.SuspiciousOperation when saving locally created csv file to s3 bucket
I need to create a csv report with django python and then save it to a FileField on a model. The filefield stores it to a secure amazon bucket. This is the logic I am using for the model: class MyModel(models.Model): created_on = models.DateTimeField(auto_now_add=True) the_file = models.FileField(blank=True,null=True,upload_to='some/dir/') def save(self, *args,**kwargs): super().save(*args,**kwargs) _access_key = settings.FINANCE_ACCESS _access_secret = settings.FINANCE_SECRET _access_bucket = settings.FINANCE_BUCKET s3 = boto3.client('s3', aws_access_key_id=_access_key, aws_secret_access_key=_access_secret) try: if self.the_file: _the_file_content = default_storage.open(self.the_file.name).read() s3.put_object(Body=_the_file_content,Bucket=_access_bucket,Key=self.the_file.name) except Exception as e: print(type(e),e) Using the admin site to upload a file, then everything works as expected. Things start to get tricky when I create the csv file and try to save the model programatically from the view. This is what I am doing: def create_and_save_the_file(): from tbkpayments.models import MyModel import os,csv,tempfile,sys _add_random_line = ['this','is','a','line'] csv_file_name='file.csv' csv_file_path = os.path.join(tempfile.gettempdir(), csv_file_name) csv_file = open(csv_file_path, 'w') csv_writer = csv.writer(csv_file) # add lines to the file csv_writer.writerow(_add_random_line) csv_writer.writerow(_add_random_line) csv_writer.writerow(_add_random_line) print(csv_file) print() csv_file.close() # We create the model to store the file _model=MyModel.objects.create() with open(csv_file_path, 'r') as f: data = f.read() _model.the_file.save(csv_file_path,data) f.close() //// And the exception that I am getting is: Traceback (most recent call last): File "<console>", line 1, in <module> File "<console>", line 20, in create_and_save_the_file File "/home/kenny/Projects/backend/virtenvs/venv/lib/python3.8/site-packages/django/db/models/fields/files.py", … -
im having trouble creating a dropdown navbar for my e-comm site using django
so my plan is to use a for loop to show all the possible categories instead of doing it manually used chatgpt but didnt help. nav_bar.html(manually): <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" id="navbarDropdown" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">Shop</a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="{% url 'category_summary' %}">All Categories</a></li> <li><hr class="dropdown-divider" href=""/></li> <li><a class="dropdown-item" href="{% url 'category' 'books' %}">Books</a></li> </ul> </li> this is trying to use a for loop: <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" id="navbarDropdown" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">Shop</a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="{% url 'category_summary' %}">All Categories</a></li> <li><hr class="dropdown-divider" href=""/></li> {% for category in categories %} <li><a class="dropdown-item" href="{% url 'category' category|slugify %}">{{ category }}</a></li> {% endfor %} </ul> </li> also created a view for the nav_bar.htlm page where i collect all the categories: def sent_data(request): categories = Category.objects.all() return render(request, 'nav_bar.html', {'categories': categories}) -
Containerize django rest framework server with django-auth-toolkit
I'm building an API for a condominium management app. Currently, I'm using Django OAuth Toolkit for user authentication. I've set up OAuth2 and the API server in the same place. My current workflow involves running the server and accessing /o/applications/ to register the app, then retrieving the client_id and client_secret and putting them into a .env file, and finally restarting the server. However, when I use Docker to containerize it, an issue arises because the container is already running and I can't access to edit the .env file anymore. I've been considering creating the app directly in the code and then storing the client_id and client_secret in Redis. If I separate OAuth2 and the API into two separate servers, my CustomUserModel would need to be in both servers. Do you have any suggestions for this scenario? -
How to filter foreign key for using ModelMultipleChoiceFilter in DRF?
I'm getting trouble with using ModelMultipleChoiceFilter in DRF. First, I have three models. # JUST STRUCTURE class A -> fields : [user:User] class B -> fields : [a:A(related_name="b"), c:C] class C -> fields : [name:string] And I want to filter with C's names (multiple choice) in class A. So... in views.py, class ShortFormListCreateView(generics.ListCreateAPIView): queryset = A.objects.all() filter_backends = [DjangoFilterBackend] filterset_class = AFilterSet and in filters.py, class AFilterSet(FilterSet): aa = filters.ModelMultipleChoiceFilter( field_name='b__c__name', to_field_name='name', lookup_expr='in', queryset=C.objects.all(), method='filter_cc', widget=CSVWidget, ) class Meta: model = ShortForm fields = ['aa'] def filter_cc(self, queryset, name, value): c_ids = [v.id for v in value] if value: queryset = queryset.filter(b__c__in=c_ids).distinct() return queryset It worked but I think it is not efficient way. Is there any solutions? -
How can I use nextjs with the Django
I started coding by using the python, When I surfed on internet, I get to know about Django. I used it very well and was easier to edit as this was generating pages dynamically. Now, I am Exploring about the nodejs and nextjs framework. I think it is good combination of both Django and Nextjs so that I can get speed as well as security. I want to know how can I integrate nextjs into Django. -
Router in router
I'm doing a project using Cookiecutter Django. I have urls and api_router.py in config. I want to add another url in 'api/' but I can't do that. I want to see the url in 'api/' like: { "users": "http://localhost:8000/api/users/" } I tried use registry but doesn't work. I have api_router.py: router = DefaultRouter() if settings.DEBUG else SimpleRouter() router.register("users", UserViewSet) router.registry.extend(product_router.registry) print(router.registry) app_name = "api" urlpatterns = router.urls and products/urls.py: router = SimpleRouter() router.register('products', ProductViewSet) urlpatterns = [ path('', include(router.urls)) ] and then, in the main urls: # API URLS urlpatterns += [ # API base url path("api/", include("config.api_router")), # DRF auth token path("auth-token/", obtain_auth_token), path("api/schema/", SpectacularAPIView.as_view(), name="api-schema"), path( "api/docs/", SpectacularSwaggerView.as_view(url_name="api-schema"), name="api-docs", ), ] So, I want to have different endpoints in localhost:8000/api/.