Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
request.data.get getting None in patch method
I am trying to get the id of user but request.get.data is not getting when i tried to print staff_user its showing None.but when use json.loads its working fine but reguest.data.get is showing None. class MyDetailsAPIView(RetrieveUpdateDestroyAPIView): permission_classes = [IsAuthenticated] parser_classes = [MyMultiPartParser` serializer_class = Myserializer model = Document lookup_url_kwarg = 'file_id' def patch(self, request, *args, **kwargs): staff_user_pk = request.data.get('staff_user_pk') if staff_user_pk: try: staffuser = Staffuser.objects.get(id=staff_user_pk) except Staffuser.DoesNotExist as exc: raise ValidationError({'detail': exc}) file = self.get_object() file.staffusers.add(staffuser) return super().patch(request, *args, **kwargs) -
City is not a valid model for User
I have extended my custom user model to include the fields; city and country. Problem is when I do a GET request to the appropriate end-point I get the error Field name `city` is not valid for model `User`. This is my code starting with urls.py router.register(r'users', views.UserViewSet) ... urlpatterns = [ path('', include(router.urls)), UserViewSet: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all().order_by('-date_joined') #changed name from UserSerializer to RegisterSerializer serializer_class = RegisterSerializer @action(detail=True, methods=['POST']) def set_password(self, request, pk=None): user = self.get_object() serializer = PasswordSerializer(data=request.data) if serializer.is_valid(): user.set_password(serializer.validated_data['new_password']) user.save() return Response({'status': 'password set'}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and RegisterSerializer: class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User #removed url from fields fields = ['username', 'email', 'password', 'first_name', 'last_name', 'city', 'country', 'bio'] extra_kwargs = { 'password': {'write_only': True}, } def create(self,validated_data): user = User.objects.create_user( username=validated_data['username'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], email=validated_data['email']) user.set_password(validated_data['password']) user.save() #added fields from profile user.profile.city = validated_data['city'] user.profile.country = validated_data['country'] user.profile.bio = validated_data['bio'] return user -
django image uploaded section doesnot shows up in production
I tried to upload image from the admin side in production but it doesn't shows up or stores in static/images but it used to work while working in local. However my static images are loaded and also those I've saved in development are also showing up but while adding new images it doesn't get added to static files. My model: class Gallery(models.Model): title = models.CharField(max_length=150) image = models.ImageField(upload_to='images/',null=True,default="avatar.svg") updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title Urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('base.urls')) ] urlpatterns +=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) Gallery .html {% for gallery in gallerys %} <!-- ITEM 1 --> <div class="col-xs-6 col-md-3"> <div class="box-gallery"> <a href="{{gallery.image.url}}" title="Gallery #1"> <img src="{{gallery.image.url}}" alt="" class="img-fluid" /> <div class="project-info"> <div class="project-icon"> <span class="fa fa-search"></span> </div> </div> </a> </div> </div> {% endfor %} Settings.py here i've uploaded only the required ones BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' AUTH_USER_MODEL = 'base.NewUser' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static/") MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "/static/images") DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' views.py def gallery(request): gallerys = Gallery.objects.all() context = {'gallerys':gallerys} return render(request, 'base/gallery.html',context) am i missing something here? Thanks in advance -
ModuleNotFoundError: No module named 'import-export' , but I have installed import-export
I'm using Django2.2.6, xadmin2. I want to use import-export, however, the error goes: ModuleNotFoundError: No module named 'import-export' but I have run this code successfully pip install django-import-export==2.7.0 Is there any way for me to fix it? -
Does bulk_upsert_models overwrite existing information
Does bulk_upsert_models from Django override if something already exists? -
How to add a CSS class to Django registration password form
I'm attempting to style (via classes) a Django password field. I've successfully styled every other field other than the new password fields (password1 & 2). screen shot of current results My html: <form method="post"> <ul> <li>{{ form.username }}</li> <li>{{ form.email }}</li> <li>{{ form.password1 }}</li> <li>{{ form.password2 }}</li> <li>{{ form.password }}</li> </ul> </form> My forms.py: class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('username', 'email', 'password1', 'password2', 'password') widgets = { 'username': TextInput(attrs={ 'class': "form-control text-lg h-8 rounded-full px-2 pt-1 border-2 border-black", 'placeholder': "Username" }), 'email': EmailInput(attrs={ 'class': "form-control text-lg h-8 rounded-full px-2 pt-1 border-2 border-black", 'placeholder': 'Email address' }), 'password1': PasswordInput(attrs={ 'class': "form-control text-lg h-8 rounded-full px-2 pt-1 border-2 border-black", 'type': 'password', 'name': 'password', 'placeholder': 'Password' }), 'password2': PasswordInput(attrs={ 'class': "form-control text-lg h-8 rounded-full px-2 pt-1 border-2 border-black", 'placeholder': 'Password' }), 'password': PasswordInput(attrs={ 'class': "form-control text-lg h-8 rounded-full px-2 pt-1 border-2 border-black", 'placeholder': 'Password' }), } Why are the new password and repeat password fields not displaying the style? I figured the name password1 was correct because I don't get any errors in forms.py as well as the HTML rending the input field. How can I add classes to those two troublesome password fields? Thank you very much for … -
Firefox processes not ending when django tests which use selenium are done running, even after driver.quit()
Here's some relevant code: class PpeLiveTest(LiveServerTestCase): def test_algamoil_incentives_table_total(self): options = webdriver.FirefoxOptions() options.add_argument("--headless") driver = webdriver.Firefox(options=options) driver.get('https://dev.redacted.com/pr-run-ppe?group=AL%2FGA%2FMO%2FIL&check_date=05%2F05%2F2022') # login first username_element = driver.find_element_by_id('id_login') username_element.send_keys('mjohnson@doozer.com') password_element = driver.find_element_by_id('id_password') password_element.send_keys(os.environ.get('ADMIN_PASS')) login_button = driver.find_element_by_xpath('/html/body/div/div/div/form/button') login_button.click() incentives_table = driver.find_elements_by_css_selector('#incentives-table > tbody')[0] georgia_row = incentives_table.find_elements_by_css_selector('tr')[4] georgia_total_cell = georgia_row.find_elements_by_css_selector('td')[2] alabama_row = incentives_table.find_elements_by_css_selector('tr')[12] alabama_total_cell = alabama_row.find_elements_by_css_selector('td')[2] missouri_row = incentives_table.find_elements_by_css_selector('tr')[16] missouri_total_cell = missouri_row.find_elements_by_css_selector('td')[2] illinois_row = incentives_table.find_elements_by_css_selector('tr')[21] illinois_total_cell = illinois_row.find_elements_by_css_selector('td')[2] total_row = incentives_table.find_elements_by_css_selector('tr')[22] total_cell = total_row.find_elements_by_css_selector('td')[2] algamoil_sum = ( int(georgia_total_cell.text.replace(',', '')) + int(alabama_total_cell.text.replace(',', '')) + int(missouri_total_cell.text.replace(',','')) + int(illinois_total_cell.text.replace(',','')) ) total_cell_value = int(total_cell.text.replace(',','')) driver.quit() self.assertEqual(total_cell_value, algamoil_sum) As you can see, driver.quit() is at the end of this test, but after each test (this is one of 6 like it), the firefox processes stay running. Why? Any help is appreciated, thanks in advance. -
Direct mail django
I am looking for the code to make personnalized letters with text editor from IHM, with insert elements from the database. It will be usefull for editing worker's contract. I think about an application like direct mailing from MS WORD. -
Integration of Front End and Backend
I am planning on creating a React/Django web application. I plan on creating an API on the backend to communicate with my React app. I understand you can integrate React with django by including your react app in the django project directory and pointing to the index.html in react. I'm still not sure what the benefits of this are. Would it be better just to separate the django and react application. Whenever I would need to store or retrieve data I could just make requests the django API? -
TypeError at /login Strings must be encoded before hashing
i am facing an error from this django project .... i have tried all the advices i can come across still its not working properly...... below is the error from the web Environment: Request Method: POST Request URL: http://127.0.0.1:8000/login Django Version: 2.2 Python Version: 3.9.7 Installed Applications: ['main', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_filters'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\INTROVERTED\Downloads\Compressed\FacialRecognitionForPolice-master\venv1\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\INTROVERTED\Downloads\Compressed\FacialRecognitionForPolice-master\venv1\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\INTROVERTED\Downloads\Compressed\FacialRecognitionForPolice-master\venv1\lib\site-packages\django\core\handlers\base.py" in _get_response 113.response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\INTROVERTED\Downloads\Compressed\FacialRecognitionForPolice-master\FacialRecognitionForPolice-master\main\views.py" in login 171.hashed = bcrypt.hashpw(request.POST['login_password'], bcrypt.gensalt()) File "C:\Users\INTROVERTED\Downloads\Compressed\FacialRecognitionForPolice-master\venv1\lib\site-packages\bcrypt_init_.py" in hashpw 79.raise TypeError("Strings must be encoded before hashing") Exception Type: TypeError at /login Exception Value: Strings must be encoded before hashing -
Como construir um sistema de repositório semelhante ao Github ou ao Google Drive para um projeto Web (Django)?
Estou construindo um site para portfólio e queria deixá-lo profissional. Quero construir um sistema de portfólio semelhante ao Github, mas sei que a implementação é complexa. Para exemplificar minha ideia, segue a imagem abaixo: enter image description here Outra dúvida seria como modelar o Banco de Dados e, por fim, como incorporar ao Django esta solução? -
Django not detecting language variations i.e. pt-br
I am trying to add Spanish and English variations to my site. Specifically: es-cl, es-pe, es-ar, pt-br. However, once I generate the translations and compile them, it only loads the es and pt values, not the country-specific ones. This is my config file GLOBAL_LANGUAGES = [ ('es', _('Español')), ('en', _('Inglés')), ('pt', _('Portugués')) ] COUNTRY_LANGUAGES = [ ('pt-br', _('Portugués (Brasil)')), ('es-cl', _('Español (Chile)')), ('es-ar', _('Español (Argentina)')), ('es-pe', _('Español (Perú)')), ] LANGUAGES = GLOBAL_LANGUAGES + COUNTRY_LANGUAGES # https://docs.djangoproject.com/en/3.1/ref/settings/#use-i18n USE_I18N = True # https://docs.djangoproject.com/en/3.1/ref/settings/#use-l10n USE_L10N = True This is the data when I access these values from my templates, where I can see that the code is repeated for English languages. {'BIDI': FALSE, 'CODE': 'ES', 'NAME': 'SPANISH', 'NAME_LOCAL': 'ESPAÑOL', 'NAME_TRANSLATED': 'ESPAÑOL'} {'BIDI': FALSE, 'CODE': 'EN', 'NAME': 'ENGLISH', 'NAME_LOCAL': 'ENGLISH', 'NAME_TRANSLATED': 'ENGLISH'} {'BIDI': FALSE, 'CODE': 'PT', 'NAME': 'PORTUGUESE', 'NAME_LOCAL': 'PORTUGUÊS', 'NAME_TRANSLATED': 'PORTUGUÊS'} {'BIDI': FALSE, 'CODE': 'PT-BR', 'NAME': 'BRAZILIAN PORTUGUESE', 'NAME_LOCAL': 'PORTUGUÊS BRASILEIRO', 'NAME_TRANSLATED': 'PORTUGUÊS BRASILEIRO'} {'BIDI': FALSE, 'CODE': 'ES', 'NAME': 'SPANISH', 'NAME_LOCAL': 'ESPAÑOL', 'NAME_TRANSLATED': 'ESPAÑOL'} {'BIDI': FALSE, 'CODE': 'ES-AR', 'NAME': 'ARGENTINIAN SPANISH', 'NAME_LOCAL': 'ESPAÑOL DE ARGENTINA', 'NAME_TRANSLATED': 'ESPAÑOL (ARGENTINA)'} {'BIDI': FALSE, 'CODE': 'ES', 'NAME': 'SPANISH', 'NAME_LOCAL': 'ESPAÑOL', 'NAME_TRANSLATED': 'ESPAÑOL'} In the views, I'm checking that the language is activating successfully, but even if I … -
Django Vue.js Axios PUT Not allowed 405
I am developing a small inventory management project. I am trying to update the stock amount when some kind of a product is being withdrawn. I am using Axios and .put() function, and when I send the request it says 405 not allowed. I can't seem to understand what the problem is. I am sending the product id to the backend and using it to identify the product which stock amount I want to upgrade. Hope you will be able to point my errors and teach me how to make it work. Here is the Views from Django: class materialWithdraw(APIView): authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.BasePermission] def update(self, request, *args, **kwargs): serializer = WithdrawFormSerializer(data=request.data) if serializer.is_valid(): material_id = serializer.validated_data['id'] quantity_to_withdraw = serializer.validated_data['quantity'] withdrawn_material = Listing.objects.get(id=material_id) withdrawn_material.quantity = withdrawn_material.quantity - quantity_to_withdraw serializer.save(quantity=withdrawn_material.quantity) return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is the urls.py: urlpatterns = [ path('all-materials/', views.allMarketingMaterials.as_view()), path('all-medical-lines/', views.allMedicalLines.as_view()), path('gastroenterologia/', views.gastroenterologiaMaterials.as_view()), path('withdraw/', views.materialWithdraw.as_view()), ] and this is my script from Vue.js: export default { name: "Gastroenterologia", components: {}, data() { return { gastroenterologiaMaterials: [], quantity: 0, id:'', } }, mounted() { document.title = "Gastroenterologia"; this.getGastroenterologiaMaterials() }, methods: { getGastroenterologiaMaterials() { axios .get('/api/v1/gastroenterologia/') .then(response => { this.gastroenterologiaMaterials = response.data console.log(this.gastroenterologiaMaterials) }) .catch(error => … -
How to fix error with related models serialization, that have HyperlinkedIdentityField?
I'm getting this error when I try to get /api/dishes-types/ page in my site: ImproperlyConfigured at /api/dishes-types/ Could not resolve URL for hyperlinked relationship using view name "category-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. I've tried to apply to my code all the solutions from this page, but nothing worked for me. How to solve this error ? I'm really got stuck... And here is my code. models.py: *I've replaced metaclasses and magic __str__ methods that are intended to admin panel from django.db import models class Category(models.Model): name = models.CharField(max_length=30, unique=True) class DishesType(models.Model): name = models.CharField(max_length=30, unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) class Dish(models.Model): name = models.CharField(max_length=64, unique=True) type_of_food = models.ForeignKey(DishesType, on_delete=models.CASCADE) description = models.CharField(max_length=1000) prices = models.JSONField() serializers.py: from rest_framework.exceptions import ValidationError from rest_framework.fields import SerializerMethodField from rest_framework.relations import HyperlinkedIdentityField from rest_framework.serializers import HyperlinkedModelSerializer from Pub.models import Category, DishesType, Dish class BaseSerializerMixin(HyperlinkedModelSerializer): @staticmethod def validate_name(name): if not name.replace(" ", "").isalnum(): raise ValidationError( "'name' field may contain only letters, numbers and spaces. Change it, please !" ) return name # # DISH SERIALIZERS # class DishSerializerMixin(BaseSerializerMixin): dish_url = HyperlinkedIdentityField(view_name="dish-detail", lookup_field="name") class DishesSerializer(DishSerializerMixin): class Meta: model = … -
Best Way To Store User Info separate from User model in django
Say I have a bunch of flags/options related to using my app. Stuff like firstSetupCompleted, tutorialCompleted, userExperienceLevel. What would be the best way to store these on a per-user basis? The options I've considered so far are django-constance package A profile model that's 1-1 with a User model a JSON field on the user model What would the best approach be to storing flags/info related to using the site, but not necessarily directly related to the user themselves (thus do not want to store in the User model) -
How can i use firebase cloud storage to handle static files
I am building a a Practice blog with django, after hosting it on heroku, i discovered that any images i upload using image field or fetch disappear after a while. Now i started using firebase cloud storage via django-storage gloud backend and it is working fine since then , but when i tried hosting my staticfiles storage from there is get this error cross origin request blocked the same-origin policy disallows reading the remote resource at? how do i fix this? -
Dynamic 'Order' column based on 'Datetime_submitted' is not updating when 'Datetime_submitted' is updated
I am creating a queue management system where patrons can sign-up in person for passport applications and the staff are able to see a queue of people based off of their form submission time. The code in my model.py is working for every scenario I have tried (New submissions, no-shows, cancelled, etc) except for if a staff were to change the form submission time to alter the order. When this occurs, the order number changes for the row modified but not any other rows. However, all I need to do to update the order on the rest of the rows is open up a row and click 'save' then all of the rows update. This is a very minor issue and I could simply disallow the modification of the 'datetime_submitted' feild. However, this is my first Django project so I would love to know why the 'order' column doesn't update when the 'datetime_submitted' is modified. Apologies in advance as this is also my first time asking a question as well. I am just including my model.py file because the forms and stuff do not matter and all editing and testing is currently being done through the Django admin login. model.py … -
DRF Error: 'str' object has no attribute 'decode'
Hi Everyone I am creating a login api using Jwt in django but i am getting error -'str' object has no attribute 'decode', if i remove decode('utf-8') then i am getting token in response but this token when i use other api then getting Error:-Given token not valid for any token views.py class LoginApiview(APIView): def post(self,request): user_name=request.data['user_name'] password=request.data['password'] user=EmpUser.objects.filter(user_name=user_name).first() if user is None: raise AuthenticationFailed('User not found') payload ={ "id":user.id, "exp":datetime.datetime.utcnow() + datetime.timedelta(days=1), "iat":datetime.datetime.utcnow(), "user_name":user.user_name } token=jwt.encode(payload,'secret',algorithm='HS256').decode('utf-8') return Response({"message": "login sucessfully","error":False,"code":200,"results":{"token":token}},status=HTTP_200_OK) -
How to display django data in multiple rows
So I am making a website using Django, HTML/CSS, and Bootstrap 5 to display books a user has. Currently, all the books are displayed in one row but I would like them to be split up into multiple rows with three on each row. How should I go about doing this? This is the model I'm using for the book: lass Book(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) isbn = models.CharField('ISBN', max_length=16, unique=True, help_text='10 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>') title = models.CharField(max_length=10, null=True, blank=True) image_src = models.CharField(max_length=400, null=True, blank=True) author = models.CharField(max_length=50, null=True, blank=True) desc = models.CharField(max_length=1000, null=True, blank=True) LOAN_STATUS = ( ('AVAILABLE', 'Available'), ('ON LOAN', 'On Loan'), ('ON HOLD', 'On Hold'), ) GENRES = { ('REALISTIC FICTION', 'Realistic Fiction'), ('HISTORICAL FICTION', 'Historical Fiction'), ('SCIENCE FICTION', 'Science Fiction'), ('ADVENTURE', 'Adventure'), ('FANTASY', 'Fantasy'), ('HORROR', 'Horror'), ('MYSTERY', 'Mystery'), ('NON-FICTION', 'Nonfiction'), } genre = models.CharField( max_length=30, choices=GENRES, blank=True, help_text='Book Genre', ) status = models.CharField( max_length=30, choices=LOAN_STATUS, blank=True, default='Available', help_text='Book Availabiliy', ) def __str__(self): #String representing model object return self.title And this is the HTML for the book list page: {% extends "base_generic.html" %} {% block content %} <div class="d-flex justify-content-around pt-4"> {% for book in object_list %} <div><a href="{% url 'book_detail' book.pk %}"> <img … -
How to set a timer in the backend for 10 minutes?
I have a ticket booking system for events. When someone wants to book a ticket, it should "reserve" it for n minutes for the person to purchase it. If he does not purchase it, then the ticket should be released after n minutes. How should I go about doing this sort of system? I am thinking of storing the timestamp of each entry on redis or something, then checking every 10 seconds and if it has been n minutes without a confirmed booking, then I release the ticket? I'm not sure if this approach will work and I don't know what to search on google on how to do this. Any help would be appreciated. My backend is django if that is useful. -
Error when assigning HyperlinkedIdentityField to a field with names other than "url"
I'm trying to apply HATEOAS to my Django REST framework API. I have a model called Coupon: class Coupon(models.Model): code = models.CharField( max_length=10, help_text='Promotion code to get free access to any product or service.' ) description = models.CharField(max_length=200, blank=True) expires = models.DateField() Then a HyperlinkedModelSerializer: class CouponModelSerializer(serializers.HyperlinkedModelSerializer): # the problem url = serializers.HyperlinkedIdentityField(view_name='market-api:coupons-detail') created_by = serializers.SlugRelatedField( read_only=True, slug_field='username' ) class Meta: model = Coupon exclude = ['modified', 'active'] read_only_fields = ['id', 'created_by', 'created'] Finally CouponsViewset: class CouponsViewSet(DestroyIotaModelMixin, viewsets.ModelViewSet): permission_classes = [AllowAny] queryset = Coupon.objects.filter(active=True) serializer_class = CouponModelSerializer The viewset is register with a DefaultRouter router = DefaultRouter() router.register(r'coupons', CouponsViewSet, basename='coupons') And in the project urls: path('market-api/', include(('iota.market.urls', 'market'), namespace='market-api')) The problem goes when I change the attribute name of the HyperlinkedIdentityField in the serializer. Whatever I set trows an error Evidence: I have tried debugging but have not found the cause. -
How to count views of blog in django
i am trying to count and show all views in every blog in my django project. What is the best way to do that?(pardon mistakes? -
How to implement CRUD operation with Django Rest mixins
I'm trying to implement CRUD operation with nested serializer with multiple data models so that I can write all field at once when I call the API endpoint. I use mixins from REST framework https://www.django-rest-framework.org/api-guide/generic-views/#mixins I have found some relevant examples but still, my serializer is only returning the fields from the Student model for CRUDoperation. I'm not able to see the Course models field in REst api ui. How can I do CRUD operation with using mixins ? How to display Data from two model without creating new model in Django? use of mixins class defined in Django rest framework models.py class Student(models.Model): student_id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) firstName = models.CharField(max_length=20) age = models.IntegerField(default=18) class Course(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) courseName = models.CharField(max_length=20) courseYear = models.IntegerField(default=2021) student = models.ManyToManyField(Student, related_name='courses') class Homework(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) hwName = models.CharField(max_length=20) hwPossScore = models.IntegerField(default=100) course = models.ForeignKey(Course, related_name='homeworks', on_delete=models.CASCADE, null=True, blank=True) students = models.ManyToManyField(Student) Serializers.py class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = "__all__" class HomeworkSerializer(serializers.ModelSerializer): class Meta: model = Homework fields = __all__ class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = "__all__" ###I combine both Student and Course into one class All_Serializer(serializers.ModelSerializer): students = serializers.SerializerMethodField() homeworks = … -
How to add comments without authentification required
i just done comments on my website,and i want to do non-authorized comments,and dont know how to.My models looks like this class Comment(models.Model): article = models.ForeignKey(Product, on_delete = models.CASCADE, verbose_name='Page', blank = True, null = True,related_name='comments' ) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE, verbose_name='Comment author', blank = True, null = True ) create_date = models.DateTimeField(auto_now=True) text = models.TextField(verbose_name='Comment text', max_length=500) status = models.BooleanField(verbose_name='Visible', default=False) and views.py like this def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): self.object = form.save(commit=False) self.object.article = self.get_object() self.object.author = self.request.user self.object.save() return super().form_valid(form) -
Django ORM: How to GROUP BY a field that "lives" in the bottom of a recursive model?
Let's say I have the following models: class Unit(models.Model): name = models.CharField(...) class PackageDescription(models.Model): lower_level = models.ForeignKey("self", null=True, ...) unit = models.OneToOneField(Unit, null=True, ...) class StockItem(models.Model): package_description = models.OneToOneField(PackageDescription, ...) I want to know the amount of unit names in a given StockItem queryset (qs). If we don't had this recursive nature, we could simply do something like: qs.values("package_description__unit__name").annotate(count=Count("package_description__unit__name")) However, a PackageDescription can have several levels, and the Unit "lives" in the bottom of the structure. How would I know, within DB level, the lowest level? And more than that: how can I GROUP BY such field? NOTE: I'm using PostgreSQL.