Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework custom permission not working
I want users to have access only to the records that belong to them, not to any other users' records so I've created the following view: class AddressViewSet(viewsets.ModelViewSet): authentication_classes = (TokenAuthentication,) permission_classes = [IsAuthenticated, IsOwner] queryset = Address.objects.all() def retrieve(self, request, pk): address = self.address_service.get_by_id(pk) serializer = AddressSerializer(address) return Response(serializer.data, status=status.HTTP_200_OK) I want only the owner of the records to have access to all the methods in this view ie retrieve, list, etc (I'll implement the remaining methods later) so I created the following permissions.py file in my core app: class IsOwner(permissions.BasePermission): def has_object_permission(self, request, view, obj): print('here in has_object_permission...') return obj.user == request.user this wasn't working, so after going through stackoverflow answers I found this one Django Rest Framework owner permissions where it indicates that has_permission method must be implemented. But as you can see in that answer, it's trying to get the id from the view.kwargs but my view.kwargs contains only the pk and not the user. How can I fix this? Do I need to implicitly pass the user id in the request url? that doesn't sound right. Here's the test I'm using to verify a user cannot access other user's records: def test_when_a_user_tries_to_access_another_users_address_then_an_error_is_returned(self): user2 = UserFactory.create() … -
How to set up different weekday/weekend schedules for celery beat in Django?
How do I go about scheduling my tasks differently for weekdays and weekends in celery beat? The schedule is set as follows in my settings.py file { "task_weekday": { "task": "tasks.my_regular_task", "schedule": crontab(minute="0-30", hour="4,5", day_of_week="mon-fri"), "options": {"queue": "queue_name"}, }, "task_weekend": { "task": "tasks.my_regular_task", "schedule": crontab(minute="0-5", hour="10,12", day_of_week="sat,sun"), "options": {"queue": "queue_name"}, }, } However when I set it up, it ran the weekday schedule today (3/21/2021 Sunday) instead of picking up the weekend schedule. I have the app timezone set to 'US/Pacific' and the CELERY_ENABLE_UTC is set to False. After setting it up I see the following log entry but it runs the weekday tasks schedule. [2021-03-21 17:57:50,082: DEBUG/MainProcess] Current schedule: <ScheduleEntry: task_weekday tasks.my_regular_task() <crontab: 0-30 4,5 mon-fri * * (m/h/d/dM/MY)> <ScheduleEntry: task_weekend tasks.my_regular_task() <crontab: 0-5 10,12 sat,sun * * (m/h/d/dM/MY)> <ScheduleEntry: celery.backend_cleanup celery.backend_cleanup() <crontab: 0 4 * * * (m/h/d/dM/MY)> I have tried running the tasks every few minutes as well to test which schedule it picks up and picks up the weekend schedule: { "task_weekday": { "task": "tasks.my_regular_task", "schedule": crontab(minute="*/2", hour="*", day_of_week="mon-fri"), "options": {"queue": "queue_name"}, }, "task_weekend": { "task": "tasks.my_regular_task", "schedule": crontab(minute="*/3", hour="*", day_of_week="sat,sun"), "options": {"queue": "queue_name"}, }, } [2021-03-21 18:03:27,075: DEBUG/MainProcess] Current schedule: <ScheduleEntry: task_weekend tasks.my_regular_task() <crontab: */3 … -
Django serilizator object updating problem
I would like to ask where it could be a problem with my serializer or using it. I want to update serialized data inside object personal info but it keeps throwing me an error: Traceback (most recent call last): File "C:\School\LS_2020_2021\MTAA\app\backend\env\lib\site-packages\django\core\handlers\exception.py", line 47, i n inner response = get_response(request) File "C:\School\LS_2020_2021\MTAA\app\backend\env\lib\site-packages\django\core\handlers\base.py", line 181, in _g et_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\School\LS_2020_2021\MTAA\app\backend\env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\School\LS_2020_2021\MTAA\app\backend\env\lib\site-packages\django \views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\School\LS_2020_2021\MTAA\app\backend\cryptoeasy\api\views.py", line 45, in register personal_info.save() File "C:\School\LS_2020_2021\MTAA\app\backend\cryptoeasy\api\views.py", line 45, in register personal_info.save() File "C:\School\LS_2020_2021\MTAA\app\backend\cryptoeasy\api\views.py", line 45, in register personal_info.save() File "C:\School\LS_2020_2021\MTAA\app\backend\cryptoeasy\api\views.py", line 45, in register personal_info.save() File "C:\School\LS_2020_2021\MTAA\app\backend\env\lib\site-packages\rest_framework\serializers.py", line 200, in s ave self.instance = self.update(self.instance, validated_data) File "C:\School\LS_2020_2021\MTAA\app\backend\cryptoeasy\api\serializers.py", line 48, in update instance.user = attrs.get('user', instance.user) AttributeError: 'PersonalInfoSerializer' object has no attribute 'user' Here's my model PersonalInfo: class PersonalInfo(models.Model): user = models.ForeignKey('User', models.DO_NOTHING, db_column='user', blank=True, null=True) firstname = models.CharField(max_length=255) lastname = models.CharField(max_length=255) card_id = models.CharField(unique=True, max_length=255) street = models.CharField(max_length=255) postal_code = models.IntegerField() city = models.CharField(max_length=255) photo = models.BinaryField(blank=True, null=True) debet_card_number = models.CharField(max_length=16) created_at = models.DateTimeField() last_update = models.DateTimeField() class Meta: managed = False db_table = 'Personal_info' Here's my serializer class: class PersonalInfoSerializer(serializers.Serializer): user = serializers.IntegerField(required=False) firstname = … -
Is it a good practice to customize ListCreateAPIView in Django rest framework?
I tried to use ListCreateAPIView with has_object_permission function and it didn't work. So i customized ListCreateAPIView instead. I want to know if it is a good practice or not? Here is my code: from rest_framework.response import Response from .models import Post from .serializers import PostSerializer from rest_framework.generics import ListCreateAPIView class MyList(ListCreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer def post(self, request, *args, **kwargs): author = request.data.get('author') if int(author) == request.user.pk: return self.create(request, *args, **kwargs) return Response('Bad request') -
how to get data from an api ... is it used flask or django?
How are you? I hope you are well ........... I have studied python and I have used your flask and django framework and I have been learning on my own I am starting in programming and a friend tells me to obtain the data from an api to keep learning .... but he told me only that..... to get the data from an api ... in which I have to solve incomplete methods ... and that's fine ... but I can do it, no problem. .. but it asks me to get the data from an api https://dogs.magnet.cl/ .... and .... there is the problem, I have never interacted with an api ... is flask used? or django ??? I really don't know ... pls any documentation or video is well received -
Create a database record with a new data instance in same view
I have two models i. AppUserModel class AppUserModel(AbstractUser): email = models.EmailField(_('email address'), unique=True,) company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True, blank=True) user_type = models.ForeignKey(UserType, on_delete=models.CASCADE,null=True, blank=True) joined = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email ii. Company Model class Company(models.Model): company_name = models.CharField(max_length=100) company_slug = models.SlugField(null=True, blank=True) company_address = models.TextField(blank=True,null=True) company_email = models.EmailField(blank=True,null=True) company_email_cc = models.EmailField(blank=True, null=True) company_phone = models.CharField(max_length=30,blank=True,null=True) company_RC = models.CharField(max_length=20,blank=True,null=True) company_registered_on = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): self.company_slug = slugify(self.company_name) super(Company, self).save(*args, **kwargs) def __str__(self): return self.company_name What I want to do i. Allow user to register with email, password and company name ii. Create a Company instance with the company name provided iii. Create a database instance of the user using the company instance created earlier. this is my view def post(self, request): register_form = RegisterUserForm(request.POST) if register_form.is_valid(): email = register_form.cleaned_data['email'] user_company = register_form.cleaned_data['company'] password1 = register_form.cleaned_data['password1'] password2 = register_form.cleaned_data['password2'] new_company = Company.objects.create( company_name=user_company, user_type='Admin') new_user = AppUserModel( email=email, password=password1, user_type='Admin', company=new_company ) new_user.save() context = { } return render(request, 'account/register.html', context=context) -
Django os.getenv('SECRET_KEY') throwing "The SECRET_KEY setting must not be empty."
I'm setting up Django using os.getenv to prepare it for deploying using Docker but it seems it is not reading the .env file. Any idea why is not reading it? Here is the setup: .env SECRET_KEY=foo DEBUG=True ALLOWED_HOSTS=localhost,127.0.0.1 settings.py abstraction import os from pathlib import Path BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.getenv('SECRET_KEY') DEBUG = os.getenv('DEBUG') ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS') -
How to access other model fields from new View
I'm trying to build a Wish list, I have a model for the listings, and a model for the wish list, I have succeeded in making it work but.. I have to loop over all the listings first and match with the product id in my wish list so i can access the fields such as title and image.. is there any easier way to do this than looping over all the listings until finding the matched ones ? views.py def add_to_wishlist(request, product_id): product = WishList.objects.filter(listing_id=product_id, user=request.user.username) if product: product.delete() else: product = WishList() product.listing_id = product_id product.user = request.user.username product.save() return HttpResponseRedirect(request.META['HTTP_REFERER']) def wishlist(request): product = WishList.objects.filter(user=request.user) all_listings = AuctionListing.objects.all() return render(request, "auctions/wishlist.html", { 'wishlist': product, 'all_listings': all_listings }) models.py class AuctionListing(models.Model): title = models.CharField(max_length=100) description = models.TextField() start_bid = models.IntegerField(null=True) image = models.CharField(max_length=1000, blank=True) category = models.CharField(max_length=100) seller = models.CharField(max_length=100, default="Default_Value") class WishList(models.Model): user = models.CharField(max_length=64) listing_id = models.IntegerField() wishlist.html {% extends "auctions/layout.html" %} {% block title %}Users Wishlist {% endblock %} {% block body %} <div class="col-12 mx-auto"> <h1 class="h3">My Wishlist</h1> <div>Manage your wishlist</div> {% if wishlist %} {% for listing in all_listings %} {% for product in wishlist %} {% if listing.id == product.listing_id%} <div class="card-mb-3"> … -
How to solve Method "POST" not allowed 405
I'm using Django Rest Framework for API and I faced this problem. In views.py my class inherits from ModelViewSet, but for some reason it doesn't allow making a POST request. For frontend I'm using React JS and I make a POST request from there. And in the end I'm getting an error like this: POST http://127.0.0.1:8000/api/software/3/ 405 (Method Not Allowed). Here's views.py: from rest_framework.viewsets import ModelViewSet from .serializers import ( CategorySerializer, SoftwareSerializer, SoftwareListRetrieveSerializer, CategoryDetailSerializer, CustomPaginatorSerializer ) from ..models import Category, Software class CategoryViewSet(ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer pagination_class = None action_to_serializer = { "retrieve": CategoryDetailSerializer, } def get_serializer_class(self): return self.action_to_serializer.get( self.action, self.serializer_class ) class SoftwareViewSet(ModelViewSet): queryset = Software.objects.all() serializer_class = SoftwareSerializer pagination_class = CustomPaginatorSerializer action_to_serializer = { "list": SoftwareListRetrieveSerializer, "retrieve": SoftwareListRetrieveSerializer } def get_serializer_class(self): return self.action_to_serializer.get( self.action, self.serializer_class ) Here's urls.py: from rest_framework import routers from .views import CategoryViewSet, SoftwareViewSet router = routers.SimpleRouter() router.register('category', CategoryViewSet, basename='category') router.register('software', SoftwareViewSet, basename='software') urlpatterns = [] urlpatterns += router.urls -
Django 3: Setting user email to be unique, minimal viable solution
I'm writing a simple app, and I'm totally happy with Django User model, except that I want a user email to be unique and obligatory field. I have developed a solution, but I'm wondering if I'm missing something. a) If you think that something is missing in the solution below please let me know b) If you think that you have a better solution please share This is what I did Created a custom user model # customers/models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): email = models.EmailField(verbose_name='Email', unique=True, blank=False, null=False) EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['email'] Added AUTH_USER_MODEL = 'customers.User' to settings.py Changed a reference to User model: User = get_user_model() Modified admin.py in order to be able to add users using Django admin. # customers/admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth import get_user_model User = get_user_model() class CustomUserAdmin(UserAdmin): list_display = ('username', 'email', 'is_staff') add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('username', 'email', 'password1', 'password2'), }), ) admin.site.register(User, CustomUserAdmin) -
Data from django form is not being posted in Postgressql Database despite getting 200 OK from the server
I am using Django version 3.0 to create a sign up application for various departments at my school. I have connected the form to a model and the model is stored in a postgressql database. After I start the server using python manage.py runserver and I complete the form and click save, the form refreshes and I get the OK HTTP Code 200 from the server accessed through the terminal, but when I query the postgressql database using pg Admin interface the data has not been stored. Can anyone see where I am going wrong? This process worked before, I'm not sure if the data is just being stored in another table. Please help out if you can. This is my base.html file: {% load static %} <!DOCTYPE html> <html> <head> <title>Signup Prototype</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <link href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="{% static 'js/jquery.js' %}"></script> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <script src="{% static 'js/bootstrap.js' %}"></script> <link type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/redmond/jquery-ui.css" rel="Stylesheet" /> <script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js"></script> <script type="text/javascript"> $(function(){ $("#id_date").datepicker(); }); </script> {{form.media}} </head> <body> <header class="page-header"> <div class="container"> <a href="{% url 'Engineering' %}" class="top-menu"> </a> <h1><a href="/">Signup </a></h1> </div> </header> <main class="content container"> … -
self.assertContains fails; Couldn't find *word* in response
I'm having difficulty completely rendering the template of TopicsPage. It's suppose to render sub_heading.html which extends listing.html (both templates reside in the same templates folder). The test passes the self.assertTemplateUsed() assertion. However an AssertionError is raised at the point of: self.assertContains(response, "Looking for more?") AssertionError: False is not true : Couldn't find 'Looking for more?' in response How can I get the sub_heading.html content to render for the test to pass when the template is being used already? test_views.py class TestTopicsPage__002(TestCase): '''Verify that a topic and associated information is displayed on the main page once the topic is created''' @classmethod def setUpTestData(cls): user = User.objects.create_user("TestUser") python_tag = Tag.objects.create(name="Python") js_tag = Tag.objects.create(name="JavaScript") content = { 'heading': "Test Title", 'text': "Mock text content", 'posted': datetime.datetime.now() } cls.topic = Topic(**content) cls.topic.author = user cls.topic.save() cls.topic.tags.add(python_tag, js_tag) def test_topics_main_page_rendered_topics(self): response = self.client.get( reverse("listing") ) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "topics/sub_listing.html") self.assertContains(response, "Looking for more?") views.py class AbstractListingPage(TemplateView): template_name = "topics/sub_listing.html" extra_content = { 'query_links': ['interesting', 'hot', 'week', 'month'] } def get_context_data(self): context = super().get_context_data() context['topics'] = Topic.objects.all() context['search_form'] = SearchForm() context['login_form'] = UserLoginForm return context def post(self, request): context = self.get_context_data() form = context['login_form'](data=request.POST) if form.is_valid(): resolver = resolve(request.path) login(request, form.get_user()) if resolver.namespace: url = f"{resolver.namespace}:{resolver.url_name}" … -
how we can delete an element from ManyToMany realtion in django models?
i create a models in django , with ManyToMany relation , and i have a problem : class KeyCat(models.Model): category = models.CharField(max_length=255) def __str__(self): return self.category class Keyword(models.Model): category = models.ManyToManyField(KeyCat) that create two table : "keycat", "keyword" and "keyword_category" i want to delete from "keywords_keyword_category" a row where id=1 -
how to change model fields value in CreateView
I currently have the following in my CreateView: class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ["title", "content", "quiet_tag", "camera_tag"] def form_valid(self, form): form.instance.author = self.request.user user = self.request.user.profile print("hello") # print(form.instance.title) <--- what I want to pass into user.participating_in # user.participating_in = Post(form.instance.title) <--- where I'm stuck print(user.participating_in) <--- returns nothing even though form.instance.title gives me the correct title return super().form_valid(form) In my models I have the following class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) participating_in = models.ForeignKey(Post, on_delete=models.CASCADE, default=None) image = models.ImageField(default="default.jpg", upload_to="profile_pics") def __str__(self): return f"{ self.user }'s Profile" When the user is created they automatically get a profile and their participating_in field is set to null. When the user makes a post I want participating_in to be set to the title of the post they're making but I can't seem to figure out how to change the value for participating_in inside of PostCreateView. -
How to import stl file from s3 for numpy stl properties evaluation?
I have my django application running on localhost. STL files get uploaded to aws S3 and I need to evaulate their properties, but I cannot get past getting the right path for numpy stl stl_file = mesh.Mesh.from_file(unknown path) Any help much appreciated -
Django REST Framework Object of type PhoneNumber is not JSON serializable
So, I have this error. I use a third party package named PhoneNumber. Now when I want to serialize my data I get this error: Object of type PhoneNumber is not JSON serializable I can guess what the problem is, but not how to solve it :/ Has anyone had this/similar problem before? :) serializer.py from rest_framework import serializers from phonenumber_field.serializerfields import PhoneNumberField from user.models import Account class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) # country = serializers.ChoiceField( # choices=['US', 'DE', 'FR', 'CH', 'AT', 'GB', 'SE', 'NO', 'FI', 'DK', 'IT', 'ES', 'PT'] # ) phone_number = PhoneNumberField() class Meta: model = Account fields = ['phone_number', 'username', 'first_name', 'country', 'email', 'password', 'password2'] extra_kwargs = { 'password': {'write_only': True}, } def save(self): account = Account( email = self.validated_data['email'], username = self.validated_data['username'], first_name = self.validated_data['first_name'], country = self.validated_data['country'], phone_number = self.validated_data['phone_number'], ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords must match.'}) account.set_password(password) account.save() return account views.py from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view from .serializers import RegistrationSerializer @api_view(['POST', ]) def registration_view(request): if request.method == 'POST': serializer = RegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): account = serializer.save() data['response'] = 'successfully registered new user.' … -
Django authenticate username not working with USERNAME_FIELD
I'm making a login for my app, with a custom user model and form, using an e-mail as username field in the model, and asking for email and password during the login process. The problem is that no matches are found in the authenticate method in my view, so I can't log in my users. Here is the code: user model class usuarios(AbstractBaseUser): nombre = models.CharField(max_length=32, null=False) apellido = models.CharField(max_length=32, null=False) correo = models.EmailField(null=False, unique=True) password = models.CharField(max_length=200, null=False) fecha_nacimiento = models.DateField(null=False) USERNAME_FIELD = 'correo' objects = userManager() def __str__(self): return self.correo+' '+self.nombre+' '+self.apellido login form class loginForm(forms.Form): correo = forms.EmailField() password = forms.CharField( widget=forms.PasswordInput() ) class Meta: model = usuarios fields = ("correo","password") login view class usuario_login(FormView): template_name = "user/usuario_login.html" form_class = loginForm success_url = reverse_lazy('user:crear') def form_valid(self, form): usuario = authenticate( username=form.cleaned_data['correo'], password=form.cleaned_data['password'] ) if usuario is not None: login(self.request, usuario) else: return HttpResponseRedirect( reverse_lazy('user:login') ) return super(usuario_login, self).form_valid(form) As you can see, in the login view I try to authenticate username (that's the email) and password before doing the login. I appreciate any help and then you. -
Docker compose with nginx, django backend and react frontend
I have some problem with configuring nginx with docker-compose (as production) for django+react project. I have followed the guide to configure django+postgres, nginx and gunicorn: Dockerizing Django with Postgres, Gunicorn, and Nginx Finally my backend is working correctly with staticfiles and gunicorn. I have some problem with configuring my frontend part. I was trying to follow Docker-Compose for Django and React with Nginx reverse-proxy and Let's encrypt certificate but still have some problems with my frontend. At this moment I have access to backend app using address 127.0.0.1:1337 (api/, admin/, auth/). So as I understand I should set up the frontend to be available using 127.0.0.1:1337, and the backend e.g. 127.0.0.1:1337/backend/. I'm not familiar with these topics at all. Maybe is there someone who would like to give me some tips? I have added my current configuration below: Docker-compose: version: '3.7' services: db: image: postgres:13.2 volumes: - ./postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.prod.db django_bot_backend: build: context: ./backend/django_dashboard dockerfile: Dockerfile.prod command: gunicorn django_dashboard.wsgi:application --bind 0.0.0.0:8000 expose: - 8000 depends_on: - db env_file: - ./.env.prod restart: "on-failure" volumes: - static_volume:/home/backend/django_dashboard/django_bot_backend/staticfiles django_bot_frontend: image: frontend build: context: ./frontend/dashboard dockerfile: Dockerfile.prod volumes: - ./frontend/dashboard:/usr/src/frontend/dashboard expose: - 3000 env_file: - '.env.front' nginx: build: ./nginx ports: - 1337:80 depends_on: … -
how to handle relation fields in django_rest_framework
so i have product model and a ProductImage model, and they have a 1 to 1 relation, i want to have it so when i wanna add a product i can upload the image right their and not in a different page or something and i don't know how to go about it. class Product(models.Model): name = models.CharField(verbose_name=_("product Name"), help_text=_("Required"), max_length = 255, blank=False) category = models.ForeignKey(Category, on_delete=models.RESTRICT) class ProductImage(models.Model): product = models.ForeignKey('products.Product', on_delete=models.CASCADE, related_name="product_image") image = models.ImageField( verbose_name=_("image"), help_text=_("upload a product image"), upload_to="api/images", blank=False, null=True, max_length=None, ) and my very basic serializer from rest_framework import serializers from products.models import Product class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id', 'name', 'category', 'description', 'slug', 'regular_price', 'discount_price', 'stockAmount') I've tried to import the productimage model and just add it to the field but it gives me a drop-down to choose from previously uploaded image and wont let me upload one right their. -
django inlineformset_factory does not validate empty extra forms
So, I don't understand why my inlineformset is not being validated when the extra forms are empty. I mean, I do need the user to enter values for both 'host_type' and 'host_score', but Django throws an error asking for values in the fields for the empty extra forms! Isn't it supposed to ignore forms that have not been changed? Here is the code: class AddressPropertyForm(ModelForm): ''' Creates a modelform that contains fields from both property and address models ''' error_css_class = 'error' building_number = forms.IntegerField(min_value = 0, required = True) street_direction = forms.ChoiceField(choices = ( ('', '----'), ('E', 'East'), ('W', 'West'), ('N', 'North'), ('S', 'South'),), required = True) street_name = forms.CharField(max_length = 30) street_type = forms.ChoiceField(choices = STREET_TYPES) class Meta: model = Property fields = ['host_type', 'host_score'] field_order = ['building_number', 'street_direction', 'street_name', 'street_type', 'host_type', 'host_score' ] def __init__(self, *args, **kwargs): super(AddressPropertyForm, self).__init__(*args, **kwargs) self.fields['building_number'].widget.attrs.update({'placeholder': '(Optional)'}) self.fields['building_number'].required = False self.fields['street_direction'].widget.attrs.update({'placeholder': '(Optional)'}) self.fields['street_direction'].required = False self.fields['street_name'].widget.attrs.update({'placeholder': '(Optional)'}) self.fields['street_name'].required = False self.fields['street_type'].widget.attrs.update({'placeholder': '(Optional)'}) self.fields['street_type'].required = False self.fields['host_type'].required = True self.fields['host_score'].required = True def clean(self, *args, **kwargs): cleaned_data = super(AddressPropertyForm, self).clean(*args, **kwargs) return cleaned_data class BaseAddressPropertyInlineFormSet(BaseInlineFormSet): def __init__(self, *args, **kwargs): super(BaseAddressPropertyInlineFormSet, self).__init__(*args, **kwargs) def clean(self, *args, **kwargs): cleaned_data = super(BaseAddressPropertyInlineFormSet, self).clean(*args, **kwargs) assert False … -
'ImageField' object has no attribute '_committed'
I'm trying to add data to a model class from the django admin panel. After clicking the "Save" button, I get this error: AttributeError at /admin/filmapp/movies/add/ 'ImageField' object has no attribute '_committed' I tried this solution, but unfortunately it doesn't work for me: override save method - 'ImageFile' object has no attribute '_committed' This is my code: admin.py from django.contrib import admin from .models import Movies admin.site.register(Movies) models.py class Movies(models.Model): title = models.CharField(max_length=50, null=True, blank=False) year = models.PositiveIntegerField(null=True, blank=False) description = models.TextField(null=True, blank=False) rating = models.FloatField(null=True, blank=True) img = models.ImageField(upload_to='static/img') url = models.CharField(max_length=1000, null=True, blank=False) img_video = models.ImageField(upload_to='static/img/imgvideo', default=img) This is full Traceback: https://codeshare.io/21wAD3 -
Django how to set or update data from filtered data
my code like this def change_order_status(request): user = request.user teacher = Teacher.object.get(id = user.teacher.id) today = datetime.now() today = today + timedelta(minutes=30) today = today.strftime("%Y-%m-%d %H:%M") test = [] if request.method=="POST": teacher_time = Student_Time.object.filter(teacher_id = teacher.id, paid=0, status=2) for tt in teacher_time: if tt.order_date < today: **tt.update(paid=1)** return HttpResponseRedirect(reverse('teacherStatistic')) return HttpResponseRedirect(reverse('teacherStatistic')) i want set or update that tt.paid to 1(default 0). How can i do it using for loop with if. tt.paid = 1 or tt.update(paid = 1) both are not working pls help me; -
How to access self in Model validator django
I have a Model in django with a field: child = models.ForeignKey(Child, on_delete=models.SET_NULL) def validate_child(child): if child.parent = self: RAISE ERR HERE As you can see, I want to access self in the validate_child method. How can I do this? Thanks. -
Django - Saving function value to every model instance
So I have this model: class Profile(models.Model): ip = "placeholder" user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") image = models.ImageField(default='default.jpg', upload_to='profile_pics') location = models.CharField(max_length=100, default=ip) def __str__(self): return f'{self.user.username} Profile' and the following function: def get_ip_address(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip ip = get_ip_address(request) What what I need to do to make it so that every time an instance of the model is created, the function runs and saves the returned value in the field called location. I assume that I have to put the function in the views.py file but how do I link it to the model instances. -
Trying to set user field in the nested form of a django nested inline formset - fails
I followed this: https://www.yergler.net/2009/09/27/nested-formsets-with-django/ and this: django inline formsets with a complex model for the nested form and overall my code works great. class Account(models.Model): user_username = models.ForeignKey(User, on_delete=models.CASCADE) account_name = models.CharField(max_length=30) class Classification(models.Model): user_username=models.ForeignKey(User, on_delete=models.CASCADE) data_id=models.ForeignKey(ImportData, on_delete=models.CASCADE) class ImportData(models.Model): user_username = models.ForeignKey(User, on_delete=models.CASCADE) data_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) ClassificationFormset = inlineformset_factory(ImportData, Classification, exclude=('user_username',), extra=1) # below is just what came from the nested formset links above: pasted here for easy reference. class BaseNestedTransactionFormset(BaseInlineFormSet): def add_fields(self, form, index): # allow the super class to create the fields as usual super(BaseNestedTransactionFormset, self).add_fields(form, index) try: instance = self.get_queryset()[index] pk_value = instance.pk except IndexError: instance=None pk_value = hash(form.prefix) transaction_data = None if (self.data): transaction_data = self.data; # store the formset in the .nested property form.nested = [ CategoryFormset(data=transaction_data, instance = instance, prefix = 'CAT_%s' % pk_value)] def is_valid(self): result = super(BaseNestedTransactionFormset, self).is_valid() for form in self.forms: if hasattr(form, 'nested'): for n in form.nested: # make sure each nested formset is valid as well result = result and n.is_valid() return result def save_new(self, form, commit=True): """Saves and returns a new model instance for the given form.""" instance = super(BaseNestedTransactionFormset, self).save_new(form, commit=commit) # update the form’s instance reference form.instance = instance # update the …