Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
manage.py invaild syntax error in kali server
I have a django project I want to publish it on an ubuntu server when I activate the virtual environment and make python manage.py runserver: File "manage.py",line 17 )from exc ^ SyntaxError:invalid syntax I'm getting the same error in every command about manage.py, not just the run server. I tried the makemigrations and migrate commands, it didn't work. I activated the virtual environment, it still didn't work I deleted django and reinstalled it still didn't work -
Handling form fields in django for logged in user
Im trying to handle the existing name of a Category, so that users wont be allowed to create 2 categories with the same name, but at the moment its taking all categories from the database, not only for the logged-in user. I dont know how and where to implement request.user. I`m building an inventory app where everyone creates their own categories and adds items. Thank you. This is my model: class Category(models.Model): user = models.ForeignKey(User, default=1, on_delete=models.CASCADE, related_name='category', null=True) name = models.CharField(max_length=100, null=False, blank=False) slug = models.SlugField(max_length=100) created_on = models.DateTimeField(auto_now_add=True) timestamp = models.DateTimeField(auto_now=True) class Meta: ordering = ['-timestamp'] verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('category_detail', kwargs={'slug': self.slug}) This is my form: class CategoryForm(forms.ModelForm): add_category = forms.BooleanField(widget=forms.HiddenInput, initial=True) class Meta: model = Category fields = ['name'] def clean_name(self): name = self.cleaned_data.get('name') if (name == ""): raise forms.ValidationError('This field cannot be left blank') for instance in Category.objects.all(): if instance.name == name: raise forms.ValidationError('There is a category with the name ' + name) return name This is my view: @login_required def index(request): categories = Category.objects.filter(user=request.user) items = Item.objects.all() add_item = ItemForm() add_category = CategoryForm() query = None if request.method == 'POST': if 'add_item' in request.POST: add_item … -
Django dj-rest-auth (django-allauth) redirection doesn't work, however, LOGIN_REDIRECT_URL is set
I'm using Django 4.1 (Djoser doesn't work with 4.x) and dj-rest-auth (if I'm not mistaken, registration is provided by django-allauth module). What am I trying to achieve is getting new user to a profile creation page ('/api/v1/new_hero/' endpoint), right after he signs up. Without any email verification, just right into it. But for now, with all theese settings, after registration, django keeps the user on the same ('auth/registration/') page with tokens demonstration and other stuff. By the way, situation keeps similar with loginning. How am I supposed to direct the user to a target page? settings.py: DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' REST_USE_JWT = True JWT_AUTH_COOKIE = 'jwt-auth' SITE_ID = 1 LOGIN_REDIRECT_URL = '/api/v1/new_hero/' ACCOUNT_SIGNUP_REDIRECT_URL = '/api/v1/new_hero/' ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = True ACCOUNT_EMAIL_VERIFICATION = 'none' items/urls.py urlpatterns = [ path('items/', ItemsListCreateView.as_view(), name='list_items'), path('items/<int:pk>/', ItemDetailView.as_view(), name='update_item'), path('heroes/', HeroListView.as_view(), name='list_heroes'), path('new_hero/', HeroCreateView.as_view(), name='create_hero'), path('heroes/<int:pk>/', HeroDetailView.as_view(), name='update_hero'), path('classes/', HeroClassListCreateView.as_view(), name='list_classes'), path('weapons/', WeaponClassListCreateView.as_view(), name='list_weapons'), # path('reg/', Registration.as_view(), name='custom_registration'), ] I tryied different django-allauth settings, checked correctness of INSTALLED_APPS, AUTHENTICATION_BACKENDS and other sections of settings.py, and it all end up here, with me writing a question. -
s3 bucket does not collect created pdfs in media folder django/aws
I just deployed my django application to a beanstalk server linked to an s3 bucket in the aws console. In my application pdfs from each post are created and forwarded to the media folder in the subfolder "postings". However, in the bucket no such folder is created and the pdfs also don't show up anywhere else. only the uploaded images of the post is there. How do I get the pdfs there? also, I get an ValueError now for the Image in the PDF (which is the uploaded image, and which was working just fine before adding the bucket). How do I get it to work again? I think both problems are due to some connection missing... This is my first project deploying to aws. Please help me out with a little explanation. Here is the code of the created upload and pdf: views.py def post_create(request): if request.method == 'POST': form = PostCreateForm(request.POST, request.FILES) if form.is_valid(): form.cleaned_data['num_post'] = Post.objects.count() + 1 Post.objects.create(**form.cleaned_data) else: form = PostCreateForm() return render(request, 'index.html', {'form': form}) def upload(request): if request.method == 'POST': image = request.FILES.get('image_upload') caption = request.POST['caption'] num_post = Post.objects.count() + 1 new_post = Post.objects.create(image=image, caption=caption, num_post=num_post) new_post.save() # create pdf buffer = io.BytesIO() … -
Problem with running maintenance mode in my Django and React apps that are stored on Azure Web App for Containers?
I have deployed Django and React application on Azure. I am using Web Application for Containers. One Web App is for Django and second one is for React (CORS headers are properly confiured, both apps are connected to each other). Docker images are stored on Azure Container Registry. I am looking for an option to switch both apps to Maintenance mode when doing some maitenance things or deploying. I was thinking abouting creating extra env variable called MAITENANCE_MODE in Application settings where I can switch manually from false to true and then it switches the mode on websites automatically. Another idea would be to create some webjobs but I am not familiar with these topics and I am asking for an advice on how to do it or at least where to look for such solution. -
place an order for a product in django
I have some products on my website And I want customer to place an order when clicking on a specific product ... and then the order form contains charfield or something from that product model to identify the order for which product is. How can I do this Thanks 😘☺️ I did the products model and I displayed them And I did the order model and I could get the data from user But I stil can't make a correct order -
Django modeltranslation and AutoSlugField
I'm struggling with combination of AutoSlugField (from django-extensions) and ModelTranslation. class Article(models.Model): title = models.CharField(max_length=255, default="") slug = AutoSlugField( populate_from=[ "title", ], overwrite=True, ) Make perfect sense without model translation. Unfortunately, if title and slug fields are translatable it does not work out of the box. The migration file created by ModelTranslation contains description for AutoSlugField: migrations.AlterField( model_name="article", name="slug_de", field=django_extensions.db.fields.AutoSlugField( blank=True, editable=False, null=True, populate_from=["title"] ), ), migrations.AlterField( model_name="article", name="slug_en", field=django_extensions.db.fields.AutoSlugField( blank=True, editable=False, null=True, populate_from=["title"] ), ), But slug_en should be based on title_en and slug_de should be based on title_de. Is it possible to enforce such behavior? -
login don't work in django user not login
login dont work i don't where the problem please help. https://youtu.be/tUqUdu0Sjyc ----- Dennis Ivy -- video learn in youtube views from django.contrib.auth import authenticate, login, logout def login(request): if request.method == 'post': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/') return render(request, 'login.html') html <form method="post"> {% csrf_token %} <input type="username" name="username"> <input type="password" name="password"> <input type="submit" name="submit"> </form> url path('login/', views.login, name="login") -
How to update ManyToManyField when source model is deleted?
Consider this model.py for a MariaDB-based setup: class User(models.Model): email = models.CharField(max_length=255) class Newsletter(models.Model): subscribers = models.ManyToManyField(User, blank=True) title = models.CharField(max_length=255) If I delete a User, I want the reference to it removed from any Newsletter's subscribers list. I do not want to delete the Newsletter itself at any point, even if the subscribers list is empty. Is this possible automatically with some Django feature like on_delete=REMOVE_FROM_LIST? -
if I pass hyderabad2 or hyderabad3 or Hyderabad in parameter then I want to get whole zeroth object in response. Could you please help me
data: string 0: object name: Hyderabad child: string 0: object name: hyderabad2 1: object name: hyderabad3 I am expecting whole object when name match found -
How do you implement csrf protection between Django and Php
If you wish to port backend endpoints from php to Django while the front end is still in php, how do you implement csrf protection in that case? There won’t be any way for each to have access in a secure manner to the same key correct? I also wish to run each eventually in their own kubernetes pod. -
How to let users download an excel file in a specific path in Django?
I am a beginner in Python Django. I am trying to let users download an excel file in a specific path in Django. My views.py is as follows. As you can see, I want to let user download OOOO.xlsx in the path /mysite/upload/. def download_file(request): # Define Django project base directory BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Define file name filename = 'OOOO.xlsx' # Define the full file path filepath = BASE_DIR + '/mysite/upload/' + filename # Open the file for reading content path = open(filepath, 'r') # Set the mime type mime_type, _ = mimetypes.guess_type(filepath) # Set the return value of the HttpResponse response = HttpResponse(path, content_type=mime_type) # Set the HTTP header for sending to browser response['Content-Disposition'] = "attachment; filename=%s" % filename # Return the response value return response My urls.py is as follows. urlpatterns = [ path('admin/', admin.site.urls), path('',views.index), path('download/', views.download_file), ] However, it keeps showing an error like this on my HTML page. <> Please help me to find the bug. -
Django Channles: Websocket connection failed
I am using Daphne + Gunicorn + Nginx for my django deployment. Following this tut., Everything worked fine on Localhost but once I publish to Ubuntu server, Connection to websocket failed. Question How can i log errors/warning/issues causing websocket connection failure. It will be easy to debug application or server. Package and versions: django==3.2.4, channels==3.0.5, channels-redis==3.4.1, daphne==3.0.2 -
I am trying to send data from my flutter application to my local api made with django
here you can see views.py, models.py and url.py and you can see here my flutter postdata function with static values when i call my function it's dont work and it's return status.code error 400 but when i try to post data using postmant it's work -
either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings
views.pyI want to test the function. An error occurs when starting the DEBUG mode. manage.py In manage.py ш didn't change anything -
How to display categories and subcategories that belong to their categories in django?
My scenario: I'm having three tables, Category, Subcategory, Products. While inserting new product, there are two select boxes 1st select is for Category (its working) 2nd is for Subcategory, which should be relevant to the 1st select. Needs to show subcategory table inside bets categories. (it doesn't work properly) Subcategory table has category id as a foreign key. I am a beginner, please somebody help. My models.py from django.db import models from django.urls import reverse class Category(models.Model): cat_name = models.CharField(max_length=25, verbose_name='Categ', db_index=True) cat_slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="SLUG") def __str__(self): return self.cat_name def get_absolute_url(self): return reverse('category', kwargs={'cat_slug': self.cat_slug}) class Meta: ordering = ['cat_name'] class SubCategory(models.Model): category = models.ForeignKey('Category', on_delete=models.SET_NULL, related_name='category', null=True, blank=True, db_index=True, verbose_name='Categ') scat_name = models.CharField(max_length=25, unique=True, db_index=True, verbose_name='Name') scat_slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="SLUG") def __str__(self): return self.scat_name def get_absolute_url(self): return reverse('subcategory', kwargs={'scat_slug': self.scat_slug}) class Meta: ordering = ['scat_name'] class Product(models.Model): price = models.IntegerField(default=0, verbose_name="Price") category = models.ForeignKey('Category', on_delete=models.SET_NULL, related_name='products', null=True, verbose_name="Categ") subcategory = models.ForeignKey('SubCategory', on_delete=models.SET_NULL, related_name='products', null=True, verbose_name="SubCateg") title = models.CharField(max_length=255, db_index=True, verbose_name="Title") slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") content = models.TextField(blank=True, verbose_name="Text") photo = models.ImageField(upload_to="images/%Y/%m/%d/", verbose_name="Photo") time_create = models.DateTimeField(auto_now_add=True, verbose_name="Created") time_update = models.DateTimeField(auto_now=True, verbose_name="Updated") is_published = models.BooleanField(default=True, verbose_name="Published") def __str__(self): return self.title def get_absolute_url(self): return reverse('product', … -
how to make fields required in django restframework
I build a blog API and the Post model is: the problem is when i want to create a post with no body content the error is class Post(models.Model): STATUS_CHOICES = [ ('P', _('Published')), ('D', _('Draft')), ('R', _('reject')) ] title = models.CharField(verbose_name=_("title"), max_length=255) slug = models.SlugField(null=True, unique=True, allow_unicode=True) lead = models.CharField(verbose_name=_( "lead"), max_length=1024, blank=True, null=True) body = models.TextField(verbose_name=_("context")) thumbnail = models.ImageField(verbose_name=_( "thumbnail"), upload_to='posts', blank=True, null=True) author = models.ForeignKey(UserAccount, verbose_name=_( "author"), on_delete=models.CASCADE) status = models.CharField( _("status"), max_length=1, choices=STATUS_CHOICES, default=STATUS_CHOICES[1][0]) publish_time = models.DateTimeField( verbose_name=_("published at"), default=timezone.now) created_at = models.DateTimeField( verbose_name=_("created at"), auto_now_add=True) updated_at = models.DateTimeField( verbose_name=_("updated at"), auto_now=True) category = models.ManyToManyField( Category, verbose_name=_("Categorys"), related_name='Categorys') like_count = models.IntegerField(verbose_name=_("like"), default=0) dislike_count = models.IntegerField(verbose_name=_("dislike"), default=0) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) class Meta: ordering = ['-publish_time'] def __str__(self): return self.title class PostListSerializer(ModelSerializer): dietale_url = HyperlinkedIdentityField( view_name='api:Post_detail' ) author = SerializerMethodField() class Meta: model = Post fields = [ 'title', 'author', 'lead', 'dietale_url', ] def get_author(self, obj): return obj.author.name the problem is when i want to create a post it return the erorr: { "title": [ "This field is required." ] } There are more fields required like author body and ... whay just the title is the required field what happens … -
Unrecoverable error: TypeError in celery on heroku
I deployed my django application to heroku and I need periodic tasks in it. versions: django-celery-beat==2.4.0, celery==5.2.7, redis==4.4.2, kombu==5.2.4 I tried different versions of celery, redis, kombu and nothing worked -
Using Django JWT authorization for FastAPI endpoint
I have a Django app where I use SIMPLE_JWT to authenticate users. I use Django to work with the admin panel, in addition, I use the Django rest framework to transfer data to the React frontend application. During authorization, the React application receives a JWT token, which is then passed along with any requests to Django rest framework endpoints. Now there is a need to create a new FastAPI endpoint. Is there any way to make FastAPI use the same JWT tokens that the Django application accepts (and creates) to check whether the user is authorized and has access rights to the FastAPI endpoint? How to do it most correctly? -
Docker enrtypiont not found on django app with alpine python
This is my Dockerfile: FROM python:alpine3.17 # Keeps Python from generating .pyc files in the container ENV PYTHONDONTWRITEBYTECODE=1 # Turns off buffering for easier container logging ENV PYTHONUNBUFFERED=1 WORKDIR /app # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev COPY Pipfile /app COPY Pipfile.lock /app RUN pip install pipenv RUN pipenv install --system COPY . /app USER root RUN chmod +x /app/entrypoint-prod.sh ENTRYPOINT ["/app/entrypoint-prod.sh"] When I run the image, this is the output: exec /app/entrypoint-prod.sh: no such file or directory This error occured only when I moved from FROM python:3.10 to FROM python:alpine3.17 I tried the following but didn't work also: USER root RUN chmod +x entrypoint-prod.sh ENTRYPOINT ["./entrypoint-prod.sh"] -
Django how to use a ModelChoiceField in a formset_factory
I am trying to use a modelchoicefield from the form in a formset_factory but i dont understand the error and don't know how to solve it. views.py def routecreate_view(request): orderformset = formset_factory(OrdersRouteForm, can_delete=False, extra=1) if request.method == 'POST': form = RouteForm(request.POST) formset = orderformset(request.POST) if form.is_valid() and formset.is_valid(): # process the data in form.cleaned_data as required messages.success(request, "You succesfully created an route.") return HttpResponseRedirect(reverse('planner.dashboard')) else: form = RouteForm() formset = orderformset() return render(request, 'planner/route.html', {'form': form, 'formset': formset}) forms.py class OrdersRouteForm(forms.ModelForm): route = ModelChoiceField( queryset=Order.objects.filter(status=1, delivery_until__gte=datetime.datetime.now(), deleted_at=None), label='Order') class Meta: model = Order fields = ("route",) def __init__(self, *args, **kwargs): super(OrdersRouteForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control m-2' self.fields['route'].label_from_instance = self.label_from_instance @staticmethod def label_from_instance(obj): return "pallets: %s, %s, %s, %s" % (obj.pallet_amount, obj.street, obj.city, obj.postal_code) template: {% extends 'base.html' %} {% block base %} <div class="container rounded bg-white mt-5 mb-5"> <div class="row"> <div class="col-md-5 border-right mx-auto"> planner//route <div class="p-3 py-5"> <form id="form-container" method="POST"> {% csrf_token %} {{ form }} {{ formset }} <button id="add-form" type="button">Add Another Bird</button> <button class="btn btn-danger profile-button mt-3" onclick="window.history.back()">Cancel </button> <button class="btn btn-primary float-end mt-3" type="submit">Order</button> </form> </div> </div> </div> </div> {% endblock %} error: Cannot assign "<Order: Order object (2)>": "Order.route" must … -
Djongo - how to add custom migration using raw mongodb command
I have a legacy mongodb database. And I create a django application witch uses it. Djongo is used as a database provider. I want to add a custom update in my migration file: db.collection1.updateMany({}, [{$set:{"field2": "$field1.id"}}]) I trid to add this command to migration file but it leads to an error: operations = [ migrations.RunSQL(""" update collection1 set field2 = "$field1._id" """), ] What is the correct way to add this command to migration? -
Safely store data from GET request - Django
Alright, Let's say we need to create a website with Django where people can book a lodge for the weekends. We add a search form on the homepage where people can fill in the check-in and check-out date to filter for all available lodges. We use a generic Listview to create an overview of all the lodges and we overwrite the queryset to grab the search parameters from the GET request to create a filtered view. views.py class ListingsView(ListView): """Return all listings""" model = Listing template_name = 'orders/listings.html' def get_queryset(self): """ Visitors can either visit the page with- or without a search query appended to the url. They can either use the form to perform a search or supply an url with the appropriate parameters. """ # Get the start and end dates from the url check_in = self.request.GET.get('check_in') check_out = self.request.GET.get('check_out') queryset = Calendar.objects.filter( date__gte=check_in, date__lt=check_out, is_available=True ) return queryset Now this code is simplified for readability, but what I would like to do, is store the check-in and check-out date people are searching for. Updated views.py class ListingsView(ListView): """Return all listings""" model = Listing template_name = 'orders/listings.html' def get_queryset(self): """ Visitors can either visit the page with- or … -
Prevent RawSQL injection in Django
In my Django application I am using RawSQL queries as an additional security layer, I want to parse every RawSQL query to prevent delete or update operation. example : There are some automated jobs scheduled from django admin panel which utilise the RawSQL queries while execution I need a method to add a validation layer over the rawsql execution so that I can prevent execution of any delete, update etc queries. -
request.user.is_authenticated does not work after changing urls
So my code looked like this at first: views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Information from django.db.models import Q from django.contrib import messages from django.contrib.auth import authenticate, login, logout from .forms import MyForm # rooms = [ # {'id': 1, 'name': 'Lets learn python!'}, # {'id': 2, 'name': 'Design with me'}, # {'id': 3, 'name': 'Frontend developers'}, # ] def home(request): q = request.GET.get('q') if request.GET.get('q') !=None else '' information_search = Information.objects.filter( Q(host__icontains=q) | Q(hostname__icontains=q) | Q(port__icontains=q) | Q(platform__icontains=q) | Q(username__icontains=q) | Q(password__icontains=q) | Q(groups__icontains=q) ) sort_info = [] informations = Information.objects.all() for i in informations: if i.groups not in sort_info: device_group = i.groups sort_info.append(device_group) information_count=information_search.count() context = {'informations':informations, 'information_search':information_search, 'information_count':information_count, 'sort_info':sort_info} return render(request, 'polls/home.html', context) def view_data(request, pk): information = Information.objects.get(id=pk) context = {'information':information} return render(request, 'polls/view_data.html', context) def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') try: user = User.objects.get(username=username) except: messages.error(request, 'User does not exist') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request, "Username or password does not exist") context = {} return render(request, 'polls/login_register.html', context) def logoutUser(request): logout(request) return redirect('home') def edit_data(request, pk): information = Information.objects.get(id=pk) form = …