Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I fix errors in django data base?
when I went to the 2nd part of the django tutorial, I saw a bug in the shell. when I reach the end of the first part of the shell and write Question.objects.all (), and then the shell responds to all commands <QuerySet [<Question: Question object (1)>]> because of this my site does not work -
ProgrammingError at / relation "home_sitesetting" does not exist LINE 1: ...ation", "home_sitesetting"."news_pagination" FROM "home_site
my project currectly run on local host But when I try to run it on the server, I get an error. On the server command line, I also get this error when executing the Migrate command: django.db.utils.ProgrammingError: relation "home_sitesetting" does not exist LINE 1: ...ation", "home_sitesetting"."news_pagination" FROM "home_site... my model: from distutils.command.upload import upload from tabnanny import verbose from django.db import models from django.core.validators import MaxValueValidator from ckeditor_uploader.fields import RichTextUploadingField # Create your models here. class SingletonBaseModel(models.Model): class Meta: abstract = True def save(self, *args, **kwargs): self.pk = 1 super().save(*args, **kwargs) def delete(self, *args, **kwargs): pass @classmethod def load(cls): obj, created = cls.objects.get_or_create(pk=1) return obj class SiteSetting(SingletonBaseModel): site_title = models.CharField(max_length=250, verbose_name="عنوان سایت") about_us = RichTextUploadingField(verbose_name="متن درباره ما", blank =True, null= True) about_us_img = models.ImageField(upload_to='site/setting', verbose_name='تصویر صفحه درباره ما') contact_us = RichTextUploadingField(verbose_name="متن صفحه ارتباط با ما", blank =True, null= True) contact_us_img = models.ImageField(upload_to='site/setting',null= True, verbose_name='تصویر صفحه ارتباط با ما') phone = models.CharField(null=True, blank=False, max_length=12) address = models.TextField(verbose_name="آدرس", null=True) email = models.EmailField(verbose_name='ایمیل', max_length=100) instagram = models.URLField(max_length=200, verbose_name='آدرس اینستاگرام', null=True) telegram = models.URLField(max_length=200, verbose_name='آدرس کانال تلگرام', null=True) fb = models.URLField(max_length=200, verbose_name='آدرس فیس بوک', null=True) twitter = models.URLField(max_length=200, verbose_name='آدرس توییتر', null=True) youtube = models.URLField(max_length=200, verbose_name='آدرس یوتیوب', null=True) linkedin = models.URLField(max_length=200, verbose_name='آدرس لینکدین', null=True) whtasapp … -
django blog like button not showing up
am making a django blog and writen some like code but cant seem to get it to work. Any ideas how to get my like button to work? Any help would be appreciated! First error code i get is: newsapp folder views.py from django.shortcuts import render, get_object_or_404, redirect from django.views import generic from .models import Post, Like from .forms import CommentForm class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' paginate_by = 6 def post_view(request): qs = Post.objects.all() user = request.user context = { 'qs': qs, 'user': user, } return render(request, 'newsapp/main.html', context) def like_post(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() return redirect('posts:post-list') def post_detail(request, slug): template_name = 'post_detail.html' post = get_object_or_404(Post, slug=slug) comments = post.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = CommentForm() … -
Django orm is creating a copy of instance instead of accessing it
I have I think kind of a tricky question in Django and it's orm. This does not work : cartitemproduct_in_cart_session.get().quantity+=1 cartitemproduct_in_cart_session.get().save() If I check just after that the value of cartitemproduct_in_cart_session.get().quantity, it wasn't updated This works : cartitem_session=cartitemproduct_in_cart_session.get() cartitem_session.quantity+=1 cartitem_session.save() The value was updated But why ? (cartitemproduct_in_cart_session is a queryset, result of a filter, but I think it doesn't matter : cartitemproduct_in_cart_session=cart_session.cartitem_set.filter(product__slug=cartitem.product.slug) ) I am guessing that somehow, when I do cartitemproduct_in_cart_session.get().quantity, the field quantity becomes a new attributes of cartitemproduct_in_cart_session.get() and isn't linked anymore to the field in the database, but I don't understand why ... Why do you need to first assign an instance of a model to a name, in order to update the fields of that instance ? -
How to make the test take an existing coin_id?
My code It is necessary that the test itself could substitute the existing coin_id, so that in the future the test does not fall, for example, due to the removal of a coin under id=2 class ModelTransactionTest(TestCase): @freeze_time(timezone.now()) def test_auto_setting_date_if_field_empty(self): field = Transaction.objects.create(rubles_cost=1, purchase_price=1, amount=1, dollars_cost=1, coin_id=2) self.assertEqual(timezone.now(), field.date) -
Omit __str__ of model in TabularInLine
I am using a TabularInLine to display a list of models, however each entry also displays the __str__ method of this model, and I was wondering how I can remove this. According to this answer I need to change the CSS file used in the admin interface, but this answer is over 10 years old so I'm not sure if that is still the best way of doing this. -
Django form - use different pre defined date ranges for different choices
I have a Django form where the user can select a variable in a choice field, start date and end date in a select date widget. For different variables, the possible start and end dates varies. The form works, but only with one pre-defined date range for all variables. How can I change the possible start and end dates according to the variable? from django import forms from datetime import datetime Parameter_CHOICES = [ ('', 'Wähle ein Umweltvariable'), ('niederschlag', 'Niederschlag [L/m²]'), ('bodentemperatur_5cm', 'Bodentemperatur in 5cm Tiefe [°C]') ] class DataForm(forms.Form): parameter = forms.ChoiceField( widget=forms.Select, choices=Parameter_CHOICES) start_date = forms.DateField(label='Beginn:', widget=forms.SelectDateWidget(years=list(range(2007,2023)))) end_date = forms.DateField(label='Ende:', initial=datetime.now, widget=forms.SelectDateWidget(years=list(range(2007,2023)))) Is it possible to do this in the forms.py or do I have to make this in javascript/html? -
store an object in django
i use react to get all the data of a table and that data is stored into a single variable called res. i want to store that data into another table and in a single row of django. const [data,setData]=useState(""); const put=async()=>{ const res=await Axios.get("http://127.0.0.1:8000/api/getdata"); console.log(res.data); setData(res.data); } function set(){ console.log(data); const a={ abc:data } Axios.post("http://127.0.0.1:8000/api/test",a).then((res)=>alert(res.data)); } -
how to apply a custom function to a specific field in a number of queries in Django
I have a simple model class Person(models.Model): name = models.CharField(max_length=20,default="") when I do Person.objects.all() I get Queryset with 20 results I want to apply a custom function def foo(name): return "Hello" + str(name) I don't want to use any loops is there any better method so that when I query I directly get these values -
How do I fix the warning "Cookie 'cookie_name' will be rejected soon ..." that I get after deleting the cookie?
Firefox throws the following warning after deleting a valid cookie: Cookie “cookie_name” will be soon rejected because it has the “SameSite” attribute set to “None” or an invalid value, without the “secure” attribute. To know more about the “SameSite“ attribute, read https://developer.mozilla.org/docs/Web/HTTP/Headers/Set-Cookie/SameSite Scenario After a valid login I send a cookie to the frontend. This cookie can be used during my session without any problems or warning. The development console also shows me the expected values: SameSite: "Strict" and Secure: true. During the logout process the set cookie is removed by setting max-age=0 or expire=<date_in_past>. The browser deletes the cookie immediately as expected but I also get the warning mentioned above. It doesn't matter if I remove the cookie in the backend or frontend - the message will always be shown. Code Set Cookie - Backend (django): class Login(): def post(self, request): ... response = Response(status=status.HTTP_200_OK, ...) response.set_cookie("cookie_name", value, max_age=60*60*5, secure=True, httponly=False, samesite='strict') return response Remove Cookie - Frontend: (preferred way for this cookie in my scenario so far) function removeItem(key, path, domain) { ... document.cookie = encodeURIComponent(key) + // "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + "=; max-age=0" + (domain ? "; domain=" + domain : "") + … -
ModuleNotFoundError: No module named 'tastypie'
I am new to Django and coding in general. When I try to use the django-tastypie (0.14.4) in my virtual env using pipenv, I get the following error when I try to launch the server ModuleNotFoundError: No module named 'tastypie'. I tried the solutions in here and in here Here is my models.py of my api app: from tastypie.resources import ModelResource from movies.models import Movie class MovieResource(ModelResource): class Meta: queryset = Movie.objects.all() resource_name= "movies" excludes = ["date_created"] and my urls.py: from django.contrib import admin from django.urls import path, include from api.models import MovieResource movie_resource = MovieResource() urlpatterns = [ path('admin/', admin.site.urls), path("movies/",include("movies.urls")), path("api/",include(movie_resource.urls)) and the full error: Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x10e6d9090> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import … -
django hidden page available only after loging in
I have made a simple login form in django. after a typing a correct details it redict to other page (result.html) but you can also get to the page after typing page address in browser. I don't know how to make available only after loging in. home.html {% extends "index.html" %} {% block content %} <div class="card border-secondary"> <div class="card-body"> <h4 class="card-title">Login form</h4> <form method="post"> {% csrf_token %} <label>Login</label> <input class="m-3" type="text" name="txtLogin" placeholder="login (admin)"> <br> <label>Password</label> <input class="m-3" type="text" name="txtPassword" placeholder="Password (admin)"> <hr> <button name="btnSend" type="submit" class="btn btn-secondary">Log in</button> </form> </div> </div> views.py def home(request): if request.method == 'POST' and 'btnSend' in request.POST : login = request.POST.get('txtLogin') password = request.POST.get("txtPassword") if login=="admin" and password=="admin": return HttpResponseRedirect('/main/result') else: return HttpResponseRedirect('/main/home') template = loader.get_template('home.html') context={} return HttpResponse(template.render(context,request)) def result(request): template = loader.get_template('result.html') context={ } return HttpResponse(template.render(context,request)) -
URLValidator throw the error when correct URL
I have URLValidator When I try to validate this url from django.core.validators import URLValidator from django.core.exceptions import ValidationError url = 'https://webapl-test.exxample.co.jp/company/senpai/index? type=data&code=0001&utm_source=line&utm_medium=topics&utm_campaign=20220720' URLValidator(schemes=['https','http']) url_val(path) Some how it returns exception... How can I fix it or can I customize the URLValidator for this kind of case?? -
Django rest spectacular - Customizing get_queryset()
I am trying to customize the redoc documents using DRF-Spectacular. For some reason, the extend_schema class is not updating the description, summary or tags on the document. How can I customize this? @extend_schema( summary="Get All Classes", description='This endpoint will return all the classes created by your account.', tags=["Class"] ) def get_queryset(self): return super().get_queryset().filter(taxonomy__is_public=True) | super().get_queryset().filter(taxonomy__client=Client.objects.get(user=self.request.user)) -
Django Models disappear from app deployed in Heroku
I am building a personal portfolio website with Django which I'm hoping to host on Heroku. I am aware of the platform's ephemeral storage problem so all of the images are served from an s3 bucket. After deploying the app though and running the python manage.py migrate from the dyno and check the postgresql database on the dashboard I can see rows and columns created but they're not populated. Therefore, there are no models stored in this database. I'm not .gitignore-ing the db.sqlite3. I'm also using a virtual environment. Ih short here's the output of the tree command from the root folder: ├── Procfile ├── db.sqlite3 ├── manage.py ├── media │ └── images │ ├── angular.png │ ├── bash.png │ ├── c.png │ ├── calibration.png │ ├── commerce_img.png │ ├── css3.png │ ├── django.png │ ├── git.png │ ├── html.png │ ├── image-processing-api.png │ ├── js-logo.png │ ├── mail.png │ ├── my_store.png │ ├── network.png │ ├── nodejs.png │ ├── programmer.svg │ ├── python.png │ ├── rest_with_node.png │ ├── sql.png │ ├── typescript.png │ └── wiki_image.png ├── portfolio │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-39.pyc │ │ ├── settings.cpython-39.pyc │ │ ├── urls.cpython-39.pyc │ │ └── wsgi.cpython-39.pyc … -
How to cancel an add django
I have a model and there are relevance values. how can I make it so that while one object (101) is false so that it cannot be added, and when the value is true, you can IN ADMIN PANEL class Rooms(models.Model): objects = None room_num = models.IntegerField(verbose_name='Комната') room_bool = models.BooleanField(default=True,verbose_name='Релевантность') category = models.CharField(max_length=150,verbose_name='Категория') price = models.CharField(max_length=105,verbose_name='Цена (сум)') def __str__(self): return f'{self.room_num}' class Meta: verbose_name = 'Комнату' verbose_name_plural = 'Комнаты' class Registration(models.Model): objects = None rooms = models.ForeignKey(Rooms, on_delete=models.CASCADE,verbose_name='Номер',help_text='Номер в который хотите заселить гостя!') first_name = models.CharField(max_length=150,verbose_name='Имя') last_name = models.CharField(max_length=150,verbose_name='Фамилия') admin = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name='Администратор') pasport_serial_num = models.CharField(max_length=100,verbose_name='Серия паспорта',help_text='*AB-0123456') birth_date = models.DateField(verbose_name='Дата рождения') img = models.FileField(verbose_name='Фото документа',help_text='Загружайте файл в формате .pdf') visit_date = models.DateTimeField( default=datetime.datetime(year=year, month=month, day=day, hour=datetime.datetime.now().hour, minute=datetime.datetime.now().minute, second=00,),verbose_name='Дата прибытия') leave_date = models.DateTimeField( default=datetime.datetime(year=year, month=month, day=day + 1, hour=12, minute=00, second=00),verbose_name='Дата отбытия') guest_count = models.IntegerField(default=1,verbose_name='Кол-во людей') room_bool = models.BooleanField(default=False,verbose_name='Релевантность',help_text='При бронирование отключите галочку') price = models.CharField(max_length=105,default='Появится после сохранения!',verbose_name='Цена (сум)') def __str__(self): return f'{self.rooms},{self.last_name},{self.first_name},{self.room_bool}' class Meta: verbose_name = 'Номер' verbose_name_plural = 'Регистрация' -
django orm .values() is not working in for loop
menu_group = MenuGroup.objects.filter(is_deleted=False,store_id=store_id,version=version).values('id','name','color') menu_group_serializer = MenuGroupMixSerializer(menu_group, many=True) for menu_group_data in menu_group_serializer.data: menu_item_group = MenuItemGroup.objects.filter(menu_group_id=menu_group_id, is_deleted=False).values('id','name','starting_price','menu_group') .values() in second for loop is not working the menu_group is foreign key -
Django filter in prefetch_related object
I have a class where I am using prefetch_related. I'd like to apply a filter so it only shows categories that contain products and if product status is equal to 1. Below is the code that I am using but it shows me the whole area multiple times and it renders all items from Needs model. Moreover, I am getting errors when clicking on the product link. It gives the following error: Cannot resolve keyword 'product' into the field. Choices are: category_area, category_area_id, category_need, category_need_id, id, products, slug, title Do you know why am I getting this error? models.py class Area(models.Model): title = models.CharField(max_length=75, blank=False) body = models.CharField(max_length=150, default='-', blank=False) publish = models.DateTimeField('publish', default=timezone.now) class Need(models.Model): title = models.CharField(max_length=75, blank=False, null=False, help_text='max 75 characters') body = models.CharField(max_length=150, default='-', blank=False) publish = models.DateTimeField(default=timezone.now) need_area = models.ForeignKey(Area, on_delete=models.CASCADE, related_name='need_area') class ProductCategory(models.Model): title = models.CharField(max_length=400, blank=False, null=False, help_text='max 400 characters') body = models.TextField(default='-') publish = models.DateTimeField('publish', default=timezone.now) category_area = models.ForeignKey(Area, on_delete=models.CASCADE, related_name='category_area', null=True) category_need = models.ForeignKey(Need, on_delete=models.CASCADE, related_name='category_need', null=True) class Product(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=400, blank=False) category = models.ForeignKey(ProductCategory, on_delete = models.CASCADE, blank=True, related_name='products') def get_absolute_url(self): return reverse("product", kwargs={'slug': self.slug}) views.py class Search(LoginRequiredMixin, ListView): template_name = 'search/product_search.html' model = Product queryset … -
Adding functionality to a signup buttom on Django
I am using the following html example taken from https://www.w3schools.com/howto/howto_css_signup_form.asp <!-- Button to open the modal --> <button onclick="document.getElementById('id01').style.display='block'">Sign Up</button> <!-- The Modal (contains the Sign Up form) --> <div id="id01" class="modal"> <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">times;</span> <form class="modal-content" action="/action_page.php"> <div class="container"> <h1>Sign Up</h1> <p>Please fill in this form to create an account.</p> <hr> <label for="email"><b>Email</b></label> <input type="text" placeholder="Enter Email" name="email" required> <label for="psw"><b>Password</b></label> <input type="password" placeholder="Enter Password" name="psw" required> <label for="psw-repeat"><b>Repeat Password</b></label> <input type="password" placeholder="Repeat Password" name="psw-repeat" required> <label> <input type="checkbox" checked="checked" name="remember" style="margin-bottom:15px"> Remember me </label> <p>By creating an account you agree to our <a href="#" style="color:dodgerblue">Terms & Privacy</a>.</p> <div class="clearfix"> <button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button> <button type="submit" class="signup">Sign Up</button> </div> </div> </form> </div> What it does is add a 'signup' button.. When input is eventually filled it sends back an error How do we add functionality to it using python? -
How to get the name of ContentType foreign key in database
I have field like this below from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType class MessageLog(BaseModel): receiver_type = m.ForeignKey( ContentType, related_name="receiver_%(class)s_set", on_delete=m.CASCADE,null=True) receiver_id = m.PositiveBigIntegerField(null=True) receiver = GenericForeignKey('receiver_type', 'receiver_id') I can access member like this, and both returns the number. m = MessageLog.objects.get(id=1) print(m.receiver_id) // 2 print(m.receiver_type) // 12 However print(m.receiver) object has no attribute 'receivor' I want to get the name of receiver_type name. How can I do this? -
ReactJS & Django Cross-domain
I am trying to connect a ReactJS app (running on localhost:1234) to a Django API HTTPS site. Although I am successfully requesting CSRF with axios (withCredentials: true), still the token is not set. Here is the response: enter image description here This is my Django settings: CORS_ALLOWED_ORIGINS = [ 'http://localhost:1234' ] CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SECURE = True CSRF_TRUSTED_ORIGINS =[ 'http://localhost:1234' ] Any suggestions what I might be missing? Could it be something wrong with the browser (I am testing on Chrome)? -
Embedding documents from static folder in Django
I am not expert in Django, but I am doing a web site where I would like to embed a ppt, which is saved into the static folder. The code of the html is: {% extends 'base.html' %} {% load static %} {% block content %} <iframe src="{% static 'ppt/pptexample.pptx' %}" style="width:800px; height:600px;" frameborder="0"/> {% endblock %} When I load the site, the ppt is perfectly downloaded, but I would like to visualise it online. Then, I have tried to add embedded=true, that is to say {% static 'ppt/pptexample.pptx' %}&embedded=true, which did not work. Could you recommend me or letting me know how to embed such a PowerPoint document in the Web? Many thanks in advance -
Mayan edms with s3 amazaon
Can any one guide with s3 integration of mayan edms? https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html -
How to Customize Django Permission Model and Still Have Admin Panel Support
I want to add several fields to the original Django Permission model and add custom permision checking logics. The catch is that I'd like to have Django admin support as well. What's the best way to do it? P.S.: I don't care about the relationship between the Permission class and ContentType and I don't need it. P.S. 2: I'm using django to create a Centralized Authentication and Authorization Service. What I've tried: I added a Custom user model that inherits from AbstractBaseUser. I also Added PermissionModel and PermisionMixin (with all the methods defined by original Django) Except that I removed the ForeignKey to ContentType which I presume is the main reason that I don't see Groups and Permissions in the Admin panel. So, back to original question? What's the best way to add custom fields to Django Permission model and still have the Admin Panel Support for CRUD on Users, Groups, and Permissions? -
How to set permissions for CRUD operations in ModelViewSet Django
I have a viewset for model News. I want to do next permissions: All people can see news. Only authorized users and admin can create news. Only owner and admin can update news. Only admin can delete news. How can I set different permissions for each operation? For create I want to use: IsAuthenticated and IsAdminUser. For update I want to use IsAdminUser and I create my own permission for owner. For delete I want to use also IsAdminUser. view: class NewsViewSet(viewsets.ModelViewSet): queryset = News.objects.all() serializer_class = NewsSerializer permission: class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.author == request.user