Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Project created but its fields are empty when sent from React to Django API
I've been working on this React + Django APP. And I have been making a simple CRUD functionality into this app. everything goes fine but when i came to create project and send it to the django database, it gets created but when i look at it at projects/list it only shows the delete button and and image field which is not important, i only want the title and body fields to be shows This is views.py class CreateProjectView(viewsets.ModelViewSet): serializer_class = ProjectSerializer def post(self, request): project = ProjectSerializer(data=request.data) if project.is_valid(raise_exception=True): project.save() return Response(project.data) urls.py create_project = CreateProjectView.as_view({"get": "post"}) urlpatterns = [ path("project/create", create_project, name="create-project"), ] Now React CreateProject.js import React, { useState } from 'react' const CreateProject = () => { let [project, setProject] = useState([]) let [title, setProjectTitle] = useState("") let [body, setProjectBody] = useState("") const handleChangeTitle = (value) => { setProjectTitle(project => ({ ...title, 'title': value})) console.log("Title:", value) } const handleChangeBody = (value) => { setProjectBody(project => ({ ...body, 'body': value})) console.log("Body: ", value) } let createProject = async () => { fetch('http://localhost:8000/api/project/create', { method: "POST", headers: { 'Content-Type': "application/json" }, // title: JSON.stringify(project_title), // title: project_title, // body: project_body, // image: "hello", // title: title, // body: … -
Class-based Django API only GET method. It's possible?
I'm building a class-based only GET method API with Django and Rest Framework. However, looking on internet, it seems to be impossible to do that. Here is my urls.py: from django.urls import path, include from rest_framework import routers from . import views api_router = routers.DefaultRouter() api_router.register(r"get_foo_id", views.GetFooIdViewSet) urlpatterns = [ path( "", include(api_router.urls)), ] views.py from app.models import * from app.serializers import * from rest_framework import viewsets from django_filters.rest_framework import DjangoFilterBackend class GetFooIdViewSet(viewsets.ModelViewSet): queryset = Foos.objects.all() serializer_class = FoosSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['foo_id'] It's really impossible? -
Return html tag by calling python function in django template
Guys actually i am expecting the django view should return only the tag like def load_tags(): return httpresponse("<span>span tag</span>") def home(request): return render(request, 'index.html',{"func":load_tags()}) html file <h2>Calling python function {{ func }} </h2> -In browser it displayed as Calling python function <HttpResponse status_code=200, "text/html; charset=utf-8"> -But i am expecting as Calling python function span tag Guys can you help me to achieve this functionality -
Print dictionary value having a letter '
Sorry for the basic question. But I cannot find a solution of this problem. I'd like to print dictionary value at the Django terminal. Here, I have a dictionary c={'code': '12'} I just want to print 12 at the terminal But when I enter print(c.values()) in the terminal, nothing appears. I think the latter ' is the problem. What should I do? -
How to transform th function into decorator in Django?
I have the fucntion header which values I need to put into 3 urls, I don't want to request the values in every view and render the context, because it takes some lines. How can I make the decorator? def acc_profile(request): refferals, balance= header(request) context = {'refferals':refferals,'balance':balance} return render(request, 'accounts/profile.html') def header(request): user_id = request.user.id refferals = Customer.objects.filter(name_id=user_id).values("refferals").first())['refferals'] balance = Customer.objects.filter(name_id=user_id).values("nickname").first())['nickname'] How can I make the def header into decorator and upper def acc_profile just put @header for example -
how to filter with django_filter object stored in filter_class
Is it possible to filter with filter_class object in methods of ViewSet class? class ClassViewSet(mixins....., DefaultApiViewSet): filter_class = ClassFilter Something like: filtered = self.filter_class.base_filters.get('something_severity').filter(queryset, "value") -
Serializing Many to Many DRF
So I have predefined database structure like this: User: id User_1: user_=ForeignKey(User) User_2: user_1=ForeignKey(User_1) Something: owner=ForeignKey(User_2) users=ManyToMany(User_2) Well, I need to fill the table Something. Short story is that from front end I receive the ids of model User but to store I need User_2. One way I see right now is to write custom create method is serializer and do all manually. Are there other ways to solve it? And is it correct to use serializers.PrimaryKeyRelatedField to deal with ForeignKey when payload has next format? { "user": 1 } -
Multiple and single selection with pop up
I have a django project and I have a form in this project. After the selection is made, the pop-up will close and I want the form to appear as written before the form is refreshed. How can I do that ? -
Django custom user model does not work on live server
I am extending the user model, and it works on my local server but does not work on Heroku, nor does it work on Python anywhere. I am using Postgres. It's a fresh database. I can't even run a makemigration due to this error. My setting file also have the error: (mysite-virtualenv) 06:21 ~/go-all-nations-2-backend (main)$ python manage.py makemigrations /home/evolvingtech/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages/environ/environ.py:784: UserWarning: Error reading /home/evolvingte ch/go-all-nations-2-backend/.env - if you're not configuring your environment separately, check this. warnings.warn( Traceback (most recent call last): File "/home/evolvingtech/go-all-nations-2-backend/manage.py", line 22, in <module> main() File "/home/evolvingtech/go-all-nations-2-backend/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/evolvingtech/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_f rom_command_line utility.execute() File "/home/evolvingtech/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/evolvingtech/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/evolvingtech/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/evolvingtech/.virtualenvs/mysite-virtualenv/lib/python3.9/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 855, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/home/evolvingtech/go-all-nations-2-backend/app_backend_api/models.py", line 8, in <module> from django.contrib.auth.models import User, AbstractBaseUser, _user_get_all_permissions, AbstractUser, AbstractBaseUser, Group, Permission, … -
how can I default a model that is already defaulted to the CurrentUserDefault()
I am creating a bar API where users can create their own bar fractions I want a way by which a user will create a bar contact that will automatically default to the bar that the user has created I already tried overriding the create method in my view models.py class Bar(models.Model): name = models.CharField(max_length=100) barOwner = models.OneToOneField(user, on_delete=models.CASCADE) secondaryUsers = models.CharField(max_length=255, default='jonathan', null=True) def __str__(self): return self.name # Bar contact Info class StoreContact(models.Model): options =( ("MTN", "MTN"), ("ORANGE","ORANGE"), ("NEXTEL", "NEXTEL") ) numberType = models.CharField(max_length=200, choices=options, default='MTN') number = PhoneNumberField(blank=True) bar = models.ForeignKey(Bar, related_name='contact', on_delete=models.CASCADE) def __str__(self): return self.numberType serializers.py class BarContactSerializer(serializers.ModelSerializer): bar = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = StoreContact fields = ('numberType', 'number', "bar") class BarSerializer(serializers.ModelSerializer): storeOwner = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) contact = BarContactSerializer(many=True, read_only=True,) class Meta: model = Bar fields = ('name', 'storeOwner','contact') views.py class BarContact(generics.ListCreateAPIView): queryset = StoreContact.objects.all() serializer_class = BarContactSerializer def perform_create(self, serializer): user = self.request.user.id try: serializer.save(bar_barOwner=user) except IntegrityError: raise ValidationError('something is wrong') -
Query database only on a particular column django ORM
I am new to Django and couldnt find the answer i was looking for so bear with me I have a model class called bid on an auction app that stores all bids that were placed on all items: class Bid(models.Model): title = models.CharField(max_length=64, blank=True) date_time = models.DateTimeField(default=timezone.now, blank=True) price = models.DecimalField(max_digits=4, decimal_places=2) user = models.CharField(max_length=64) now i want to query this table and have it return to me ALL the bid prices that were placed on a particular item, i have this line: bids = Bid.objects.all().filter(title=title) that returns all objects with that title, but i dont care for the other columns of this object, i just want the prices this is kinda stupid but i did try it: bids = bids.price ofcourse it didnt work -
Faust Streaming retry topic mechanism
I have two topics main_topic retry_topic I want if the logic fails in main_topic it should call retry_topic and if that fails so there should be max 3 retries that it should do. I've tried using sink in faust streaming what it does is that it yield result from my main topic to retry_topic but I'm still not able to limit it to 3 retries. Is there a way to do that in faust/kafka streaming because I know that celery has this feature. -
how to group other group permissions in django?
I'm creating e-commerce website using django and drf. My project has many apps like, products, sales, logistics, warehouses and etc... I'm also making new admin dashboard (not using django's built-in). Now I want to make fully dynamic role-based authentication in my admin page. I made group authentication for each apps. Now I want to make such a function that SuperAdmin can create roles (such as: Operator, Driver and etc...) and give them group permissions (like operator should have access on products and warehouses). How can I group two or three groups together? or are there any better methods? -
Conditional Model Creation
I'm creating a form creation web app and I've got it to the point I'm ready to start handling data from the front-end and creating models, but it's looking like it's not possible to do what I want. From the front the user is capable of submitting an image of a form and create fields by drawing rectangles on the image and giving them names and sending everything needed to the back-end in JSON. What I want to do is create models based off this data, but the only answers I've found are creating the models beforehand then setting conditionals for which apps are loaded which isn't something I can use in my case. Is what I'm trying to do possible and if so can I get some advice? -
how to fixed this error ,,( please help me,)
Error running WSGI application ModuleNotFoundError: No module named 'project' File "/var/www/sanjoy_pythonanywhere_com_wsgi.py", line 14, in application = get_wsgi_application() wsgi.py # To use your own django app use code like this: import os import sys # ## assuming your django settings file is at '/home/sanjoy/mysite/mysite/settings.py' ## and your manage.py is is at '/home/sanjoy/mysite/manage.py' path = '/home/sanjoy/project' if path not in sys.path: sys.path.append(path) # os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings' # ## then: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() -
What is even use of Django Nested Atomic?
I recently came across nested atomic blocks in Django and it looks like even if error occurs in any of those blocks, all of them will be rollbacked. So, why do people use nested atomic block? Specifically, what is the difference between with transaction.atomic(): do_something with transaction.atomic(): do_something_more and with transaction.atomic(): do_something do_something_more ? If there is no overall difference, then in what scenario first should be used instead of second? -
Make form field dropdown dependable in Django
I am currently working on Django admin modification. I made an app which has an inventory model containing some fields. There I have category and subcategory fields as dropdown. I have some category and under those category I have corresponding subcategory. What I want is to when I select category say for example I choose category-1 it should populate the subcategory dropdown fields with only those subcategory which is under the category-1. I found some explanation regarding this, they were working with ajax and stuffs with the custom form but not with the admin generated forms. As I am new to admin modification I found it hard to where I need to change and etc. -
Issue with bcrypt, py-bcrypt and django-bcrypt
i have installed bcrypt==4.0.1 , py-bcrypt==0.4 and django-bcrypt==0.9.2 in my django project virtual env. When am trying to run createsuperuser command then its giving me following error AttributeError: module 'bcrypt._bcrypt' has no attribute 'encode_base64' Any idea how can i fix this? I have tried multiple versions of bcrypt module but it did not worked -
Why get i message `side of a many-to-many set is prohibited. Use ....set() instead` in django-pytest?
I'm a learning the django - pytest. I'm read the forum? but i don't find the answered. Pleas help me. Task: create a test for the api request (django-pytest). I use the two basic library: Model Bakery Pytest-Django , and other classes, it's API Client, random. The 'Course' model has the relation many-to-many I generating the content for db through - 'Model Bakery' and after i insert when filling the db But i'm can't understand When i start the test, i get error short test summary info FAILED tests/students/test_courses_api.py::test_example - TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use student.set() instead. 1 failed, 1 warning in 9.86s Why get i message side of a many-to-many set is prohibited. Use student.set() instead ? What did i wrong if in documentation writes about make_m2m=True: By default Model Bakery doesn’t create related instances for many-to-many relationships. If you want them to be created, you have to turn it on as following: @pytest.mark.django_db() def test_example( name_stude = get_name_random, # the example is down title = get_courses_random, username = getUser, # the example is down api_client = api_client # the example is down ): #Arrange student = baker.make( "students.Student", name … -
how to install xhtml2pdf in python 3.11
i was using xhtml2pdf in django python 3.10 which was working well. now i upgraded my python version to 3.11. i tried to install pip intall xhtml2pdf, i get error ********************************************************************************* Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed? ********************************************************************************* I already updated pip, setuptools and installed pillow, wheel.i already installed microsoft visal c++ 2015. i am unable to install libxml2. I do not know where to find a currect file and how to install. i am using windows 11 pro 64 Bit. Please help me. to install xhtml2pdf in python 3.11 -
How to find way of automatic delete tem dir and files after debagging tests in Django?
Django project. In this project unittests. After debagging process have made temp dir and files, and don'n delete automatically. sys MacOs. After test temp dir and files are deleted, but after debugging this test they still there. test example: @override_settings(MEDIA_ROOT=TEMP_MEDIA_ROOT) class PostCreateFormTests(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.small_gif = ( b'\x47\x49\x46\x38\x39\x61\x02\x00' b'\x01\x00\x80\x00\x00\x00\x00\x00' b'\xFF\xFF\xFF\x21\xF9\x04\x00\x00' b'\x00\x00\x00\x2C\x00\x00\x00\x00' b'\x02\x00\x01\x00\x00\x02\x02\x0C' b'\x0A\x00\x3B' ) cls.uploaded_image = SimpleUploadedFile( name='small.gif', content=cls.small_gif, content_type='image/gif' ) @classmethod def tearDownClass(cls): super().tearDownClass() shutil.rmtree(TEMP_MEDIA_ROOT, ignore_errors=True) def test_create_post_form_valid_by_authorized_user(self): posts_count = Post.objects.count() form_data = { 'text': 'Тестовая запись', 'group': self.group.id, 'image': self.uploaded_image } response = self.authorized_client.post( reverse('posts:post_create'), data=form_data, follow=True ) self.assertEqual(Post.objects.count(), posts_count + 1) self.assertTrue( Post.objects.filter( text=form_data['text'], group=form_data['group'], image='posts/small.gif' ).exists() ) redirect = reverse( 'posts:profile', kwargs={'username': self.user.username}) self.func_redirect_and_tests_post_correct_created_form_fields( response, form_data, redirect) Find a way to make delete process temp files automatically . -
DRF How to perform additional operations on an instance
Which of the given ways of writing additional logic is technically correct? The example includes changing the status of the document. After a quick reserach of similar questions, I understand that there are 3 possibilities described below. However, no answer describes which solution is used during daily practicals, and the examples from the documentation do not dispel doubts. Please help. Providing custom data to the serializer and the standard model serializer: class PZSaveAPIView(APIView): @transaction.atomic def patch(self, request, pk, format=None): document = get_object_or_404(PZ, pk=pk) print(request.data) serializer = PZModelSerializer( document, data={'status': 'E'}, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) After the object is serialized, change the status: class PZSaveAPIView(APIView): @transaction.atomic def patch(self, request, pk, format=None): document = get_object_or_404(PZ, pk=pk) serializer = PZModelSerializer( document, data=request.data, partial=True) if serializer.is_valid(): pz = serializer.save() pz.status = 'S' pz.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Contain the logic in the serializer, and the view stays basic: class PZUpdateSerializer(serializers.ModelSerializer): class Meta: model = PZ fields = '__all__' def update(self, instance, validated_data): instance.status = 'S' instance.save() return instance Is it even necessary to use a serializer in such cases? Example: class PZSaveAPIView(APIView): def patch(self, pk): document = get_object_or_404(PZ, pk=pk) document.set_status_saved() document.save() return Response('Document saved') -
Calculating the sum of TimeField values in Django
Here I am using Django 3.0 and Python 3,7 Here I need to calculate all the values of TimeField whose day_type='Weekdays' Here is my models.py class WorkTime(models.Model): client = models.ForeignKey(Client,on_delete=models.CASCADE) day_type = models.CharField(max_length=200, blank=True, null=True, choices=DAY_TYPE_CHOICES) start_time = models.DateTimeField() finish_time = models.DateTimeField() total_time = models.TimeField(blank=True, null=True) class ProductionCapacity(models.Model): client = models.ForeignKey(Client,on_delete=models.CASCADE) date = models.DateTimeField(blank=True, null=True) number_of_people = models.IntegerField(blank=True, null=True) capacity = models.TimeField(blank=True, null=True) work_time = models.ForeignKey(WorkTime,on_delete=models.CASCADE,blank=True,null=True) Here is my views.py class ProductionCapacityCreateView(CreateView): template_name = 'manufacturing/production_capacity_form.django.html' form_class = ProductionCapacityForm context_object_name = "production_capacity" model = ProductionCapacity def get_form_kwargs(self): kwargs = super(ProductionCapacityCreateView, self).get_form_kwargs() kwargs["client"] = self.request.user.client kwargs["request"] = self.request return kwargs def form_valid(self, form): self.client = self.request.user.client self.object = form.save(commit=False) self.object.client = self.request.user.client num_of_people = form.cleaned_data['number_of_people'] date = form.cleaned_data['date'] myDate = datetime.datetime.strptime(str(date), "%Y-%m-%d") weekno = myDate.weekday() if weekno < 5: print("Today is a Weekday") work_time = WorkTime.objects.filter(client=self.client,day_type='Weekdays').values_list('total_time',flat=True) c_time = sum(work_time) self.object.capacity = number_of_people * c_time else: pass try: self.object.save() messages.success(self.request, 'Day created successfully.') except BaseException as e: logger.exception(e) messages.error(self.request, 'Failed to create a day.') return HttpResponseRedirect(reverse("capacity_list")) Here is my error traceback Traceback (most recent call last): File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/harika/lightdegree/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = … -
filtering products by categories [PROBLEM]
I got a problem with filtering products by categories. My issue is I want to order my products by "category" as I've made in my JSON file. If a customer would click "Amulets" the page shows only products with category "Amulets". How to do that? I guess I should to use "Filter" but I'm a beginner so I don't know how to. Thanks a lot for any help! much appreciate it! I've tried to use product.filter but I can't ;/ thanks for help! -
django.db.utils.OperationalError: no such table: product, django cannot import form.py into view.py
I've 3 pages Model, Forms and View In model.py i define my table #model.py class Prod(models.Model): id = models.CharField(primary_key=True, max_length=10, blank=False, null=False) description = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'product' verbose_name = 'PROD' now I move to forms.py #forms.py from .models import Prod class ProdForm(forms.ModelForm): #some code to fill class Meta: model = Prod exclude = [...] widgets = { ... } labels = { ... } and finally with view.py #view.py from .forms import ProdForm When i execute python manage.py makemigrations, I get an error saying no such table: product my app was hosting locally with postgres, now i used db.sqlite3 to test, i don't undestand why views.py can't import the table forms or at least why It's not creating them? I don't understand why, specially that this code was running locally with a postgres.