Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can we overrider serializer.save() method in django rest framework?
I have update functional view. And i'm update profile instance with serializer.save() method. I want to override that default save method. and want to save that in to profile managers file. Can you tell me how can i do that ? functional view where i'm using that save method. if request.method=="PUT": request.data["update_time"] = timezone.now() serializer = UserProfileSerializer(profile, data=request.data,partial=True) if serializer.is_valid(): serializer.save() trying to move that in managers : def save_me(self,obj): obj = obj.save() return obj -
How to remove username and password2 fields from form errors
I have a problem with these fields in their output to the html template. I need to output only error text without field data in the Messages function. error on website Create messages in views.py messages.error(request, form.errors) -
Django HttpResponseRedirect sends request but doesn't actually render?
I am attempting to redirect a user to http://127.0.0.1:8000/register/Pro/success after a successful registration. This is my URLs code: from accounts import views from django.urls import path,re_path from django.contrib.auth import views as auth_views urlpatterns = [ # path('signup',views.signup_user,name='signup'), path('login', views.login_user, name="login"), path('logout', views.logout_user,name='custom_logout'), re_path(r'^password_reset/$', auth_views.PasswordResetView.as_view(), name='password_reset'), re_path(r'^password-reset/email-sent/$', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('password-reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), re_path(r'^password-reset/complete/$', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), path('register/<str:plan>/', views.register, name="register"), path('register/<str:plan>/success', views.success, name="redirect") ] And this is what I am attempting to redirect it with: return HttpResponseRedirect(f'/register/{plan}/success') This sends a get request, but it only shows up in the networks tab of developer tools, it doesn't actually render in the same way as if you went to the URL manually. How would I achieve this? -
Overriding a Django core class without modifying its import path
Is there a way to override a core Django class without modifying its import path? For example, the class BaseCommand is imported by django.core.management.base. I want to override/modify BaseCommand and still be able to import it from the same path. Is that possible? -
django Rest-framework serialize two tables
i have table "Books" with some fields, and i have table "Prices", each customer have self price, i don't know how get price for definitely client, how i must configure serializer? please, help me, class Book(models.Model): title = models.CharField('Заголовок', max_length=250) code = models.CharField('Код', primary_key=True, max_length=10) isbn = models.CharField('ISBN', max_length=18, null=True, blank=True) ean13 = models.CharField('EAN-13', max_length=13, null=True, blank=True) author = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Автор') class PricesName(models.Model): name = models.CharField('Вид цены', max_length=20) def __str__(self): return self.name class Price(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) PricesName = models.ForeignKey(PricesName, on_delete=models.CASCADE) price = models.FloatField() def __str__(self): return self.book.title+" "+self.PricesName.name ######### Serializers.py ########################## class BookSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField() class Meta: model = Book fields = #'__all__' #### API.py #### class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = BookSerializer filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter) filter_fields = ('title', 'author') search_fields = ('title', 'author') pagination_class = StandardResultsSetPagination -
DJANGO POSTGRES matching query does not exist
Hi i have a seller model that is related one to one field with user in DJANGO. Seller can create a "deal" and to become seller you first have to create a normal account as a user. I dont have any idea how to take to the view deals that are from the specyfic seller MY views. @user_passes_test(is_seller) def seller_page(request): if request.method == "GET": user = request.user _seller = Seller.objects.get(user_id=user) # TODO: doesnt work deals = Deal.objects.get(seller_id=_seller) form = forms.DealModelForm context = {'deals': deals, 'form': form} return render(request, 'seller_page.html', context) My models class Seller(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=255) address = models.CharField(max_length=255) city = models.CharField(max_length=255) post_code = models.CharField(max_length=6) phone = models.CharField(max_length=12) email = models.CharField(max_length=255) bank_account = models.CharField(max_length=255) nip = models.CharField(max_length=255) is_seller_active = models.BooleanField(default=False) sells = models.IntegerField(default=0) class Deal(models.Model): seller = models.ForeignKey(Seller, on_delete=models.CASCADE) title = models.CharField(max_length=255) description = models.TextField() image = models.ImageField() is_deal_on = models.BooleanField(default=True) sell_price = models.DecimalField(default=0, decimal_places=2, max_digits=6, help_text='Cena sprzedaży') origin_price = models.DecimalField(default=0, decimal_places=2, max_digits=6, help_text='Oryginalna cena', blank=True, null=True) time_valid = models.IntegerField(default=12) # ilość miesięcy ile warty jest deal unique_code = models.CharField(max_length=60, null=True, blank=True) quantity = models.IntegerField(default=0) province = models.IntegerField(choices=PROVINCES) ERROR : _seller = Seller.objects.get(user_id=user) -
Create a instance of another model on the basis of a value provided on the request of a view
Problem: I want to create a new instance of the DogAcknowledgement inside the serializer whenever a dog instance is created on the basis of the provided value(which can be true, false, or null) provided on the request. what I have tried: Create a custom_field on the serializer which will hold the value of the provided value. when the post-call is made for the dog on the to_internal_value I would add logic to create a dog_acknowledgement. if certain_value is not None: dog_ack, _ = DogAcknowledgement.objects.get_or_create(dog=???(object)) else: something But how do I access the dog object that is being created in the post request? when I send the object itself I get an error. -
How do I access a server's file manager using cwp simple terminal?
I am currently new to using CWP panel and understand it provides a user friendly file manager. However, I am trying to configure the Apache server to run Django and need to download mod_wsgi package on the server. -
post request body additional data from drf serializer
I need user to send me data in this format. Each items in the "data", mast contain "mandatory_key" and they can additionally send any other keys they want. { "data": [ { "mandatory_key": "Value", "key_1": "value_1", "key_2": "value_2", "key_3": "value_3", ... }, { "mandatory_key": "Value", "key_1": "value_1", "key_2": "value_2", "key_3": "value_3", ... }, { "mandatory_key": "Value", "key_1": "value_1", "key_2": "value_2", "key_3": "value_3", ... }, { "mandatory_key": "Value", "key_1": "value_1", "key_2": "value_2", "key_3": "value_3", ... }, { "mandatory_key": "Value", "key_1": "value_1", "key_2": "value_2", "key_3": "value_3", ... }, { "mandatory_key": "Value", "key_1": "value_1", "key_2": "value_2", "key_3": "value_3", ... }, { "mandatory_key": "Value", "key_1": "value_1", "key_2": "value_2", "key_3": "value_3", ... }, { "mandatory_key": "Value", "key_1": "value_1", "key_2": "value_2", "key_3": "value_3", ... } ] } since "mandatory_key" is the only key that I know, I can make my serializer like this. class MySerializer(Serializer): mandatory_key = CharField() When I initiate this serializer with data attribute, in the validated_data, it only gives me mandatory_key, not other keys. serializer = MySerializer(data=request.data) if serializer.is_valid(): print(serializer.validated_data) Is there any ways I can do this using serializer? I don't want to manually validate it. Because the use case is much different. Thanks! -
How to remove all symbols within a given string in Javascript?
Currently I am using the following Javascript code to convert a product title into URL-slug within the base template of my django project. document.getElementById("title").onkeyup = function () { document.getElementById("url_slug").value = document .getElementById("title") .value.toLowerCase() .replaceAll(" ", "-") .replaceAll("'", "") }; This is using consecutive replaceAll() methods to replace space with dash then remove apostrophes but i would like to prevent all other symbols (e.g. +=()[]$%@#... etc) as well. Surely there must be a better way? Thanks in advance for any suggestions! -
How can I override contrib.auth.LoginView permission?
how can I override default permission on contrib.auth.LoginView? I am working on a Django Rest Api using DRF. I am using django's default authentication methods from django.contrib.auth. And the problem is, I can't test login via Postman, because I don't have csrf token(yes, I am using SessionAuthenctication). How am I getting csrf, if I'm not allowed to login? -
I can not fetch Datas from Django Rest Frame work Api
I made a pagination on API. After that I got a problem. I cant display my datas that I fetched from api. So after implementation of pagination , Displaying is stopped. pagination.py from rest_framework.pagination import PageNumberPagination class SmallPagination(PageNumberPagination): page_size =5 List Api class MeetingList(generics.ListAPIView): queryset = CreateNewMeeting.objects.all() pagination_class = SmallPagination serializer_class = MeetingSerializer Permission_Classes = [permissions.IsAuthenticatedOrReadOnly] filter_backends = (SearchFilter, OrderingFilter) search_fields = ('meeting_name', 'id') index.html def MeetingViewSearch(request): meeting = "http://127.0.0.1:8000/meetingdetails/?page=1" read_meeting = requests.get(meeting).json() context = {'meetings': read_meeting} return render(request, 'index.html', context) I'll be glad If someone could help me ... -
Django site not loading using Apache2 and mod_wsgi
Trying to deploy a Django site using Apache and wsgi on an AWS EC2 instance. When running the site using python manage.py runserver 0.0.0.0:8000 everything works perfectly when connecting via the elastic ip. I was under the impression that using Apache and wsgi the site would automatically start and be kept up even after closing the shell. I may be wrong about that though so please correct me if so. I followed the official documentation for setting up the files, and also checked out some other tutorials to try and get it to show but nothing. They all say once the 000-default.conf file is setup and Apache is restarted, to check the site IP, but mine never loads the connection eventually times out. my file structure is: home └── ubuntu/ └── django/ └── portfolio/ ├── portfolio/ │ ├── base │ ├── portfolio/ │ │ ├── settings.py │ │ └── wsgi.py │ ├── static/ │ ├── templates/ │ └── manage.py └── venv/ └── lib/ └── python3.8/ └── site-packages/ my Apache 000-default.conf is <VirtualHost *:80> ServerAdmin YourEmail@yourProvider.com DocumentRoot /home/ubuntu/django/portfolio/portfolio ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/django/portfolio/portfolio/static <Directory /home/ubuntu/django/portfolio/portfolio/static> Require all granted </Directory> <Directory /home/ubuntu/django/portfolio/portfolio/portfolio> <Files wsgi.py> Require all granted </Files> </Directory> … -
Why does Django not find a field added to the AbstractBaseUser
I've inherited from the AbstractBaseUser as follows: class User(AbstractBaseUser): """ Main User model, inherits from AbstractBaseUser """ # Meta email = models.EmailField(verbose_name='email', max_length=60, unique=True) username = models.CharField(max_length=40, unique=True) # equals to email date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) employee_of = models.OneToOneField(Customer, on_delete=models.SET_NULL, null=True) So each User is linked to one and only one Customer. Now within a view I want to access the instance of the current logged in user within the request object and get the employee_of value to get a queryset that contains all users of that customer. def render_employees(request): """ Renders the employees page of the dashboard :param request: :return: """ # Return the value for the current site for css specific classes dashboard_site = 'employees' # Query the employees qs_employees = User.objects.filter(employee_of=request.user.employee_of) # doesn't find field ... However the filter doesn't work because request.user.employ_of doesn't seem to return anything. My IDE even suggests e.g. username, date_joined etc. but not employee_of. Why's that? class Customer(models.Model): """ A table that stores static data about a customer, usually a legal company """ legal_name = models.CharField(max_length=50) street = models.CharField(max_length=30) street_number = models.CharField(max_length=3) def __str__(self): return self.legal_name -
Can't save InMemoryUploadedFile to S3 in Django Admin
I'm using the django-storage package, and trying to upload multiple images at once. So I overwritten the add_view and save_model methods in ModelAdmin, in order to remove the original image field and use a custom one (with a multiple flag in the input tag) given in the template HTML: MODELS.PY class Media(AbstractCreatedUpdatedDateMixin): uuid = models.UUIDField(unique=True, default=uuid4, editable=False, db_index=True) user = models.ForeignKey(User, related_name="uploaded_media", on_delete=models.CASCADE) title = models.CharField(max_length=255) image = models.ImageField(upload_to=uuid_directory_path) ADMIN.PY class MediaModelAdmin(admin.ModelAdmin): def add_view(self, request, form_url='', extra_context=None): self.exclude = ('image', "is_approved") extra_context = extra_context or {} extra_context['show_save_and_add_another'] = False extra_context['show_save_and_continue'] = False return super().add_view(request, form_url, extra_context) def save_model(self, request, obj, form, change): for file in request.FILES.values(): obj.user = User.objects.filter(id=request.POST.get("user")).first() obj.title = request.POST.get("title") obj.image.save(file.name, file.file) obj.save() It uploads correctly to S3, but it doesn't save the instance and throws this error: TypeError at /admin/media/media/add/ expected string or bytes-like object I'm not sure what is wrong here, maybe the fact that the upload is not done yet so the DB transaction is rolled back, but I can't figure out what do to. -
Python / Django Static files not load when debug is False
I have Django project and I deployed this project on Web Host. But I have a problem. Static files do not load when I set the debug variable in the settings file to False. Host control panel: cPanel Web Server: LiteSpeed -
Openpyxl how scroll to cell A1
I have a .xlsx file in a DJANGO project used as a template to the user download insert some data upload and populate some stuffs in the system, so far so good. Sometimes a dev need edit this file, change some description or add a value, anything. Some of then finish the edition, for all sheets set the A3 cell as active scroll to top and for the last select the "initial" sheet, but must of the developers forget this step and i'm trying to create some thing like a set_initial_state. What i have so far: def set_initial_state(workbook: Workbook) -> Workbook: # Set A3 cell as active [working well] for ws in workbook: for selection in worksheet.sheet_view.selection: selection.activeCell = "A3" selection.sqref = "A3" # Set the initial worksheet [working well] workbook.active = workbook["@Instructions"] # set the scroll position to A1 [Not working] for ws in workbook.worksheets: ws.sheet_view.topLeftCell = "A1" OBS: All the worksheets have some column or row frozen. -
splitting all the functions in Django rest framework to separate fils
I am creating an app and it has alot of serializers and views at first I was working in the default way but later I have created a folder name (seriliazers then more folders name (auth,Profile,Payment) and serializers related to each part is inside these folders, I did same with views folder is it a good way to work or not, found out a lot of critics on not using views.py file. -
Accessing result of Django Celery tasks whenever they finish
When a user clicks a button on my webpage 2 celery tasks are started (using RabbitMQ): views.py def btn_clicked(request): task1 = task1.delay() task2 = task2.delay() tasks.py @shared_task def task1: #do something return result1 @shared_task def task2: #do something return result2 I want to use htmx to update the html on my webpage when the results of task1 and task2 are available (as they come in, task1 may be quicker than task2). The tasks will take ~30 seconds. In order to pass the info to the html I need to access the result as soon as it's available but I'm not sure how. From what I've read elsewhere it may be through using AsyncResult but I'm not sure on this - and if it is I'm not sure how I access the id of each task to pass it into AsyncResult (I've tried task.id without success) -
Boostrap.min.css not loading in django app after deploying to Azure Cloud
My Site is running perfectly running on localhost but when i uploaded my code to Azure cloud it doesn't loading boostrap.min.css due to which its theme is not loading on local host: Local host image on Azure site Azure Screenshoy why it is not fetching the boostrap themes on site -
Python/Django Test Framework: Response code was 200 (expected 200)
So I am using Django's test framework, and in this case im testing update_password_view that I ve created on top of the built-in PasswordChangeForm. Could someone please help me with the error from below? After I run tests I get the following error: AssertionError: [] is not true : Response didn't redirect as expected: Response code was 200(expected 200) Here is the code: #views.py class UpdatePassword(PasswordChangeView): form_class = PasswordChangeForm success_url = reverse_lazy('posts:home') template_name = 'accounts/password.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # get the number of unseen messages context['inbox_count'] = Message.objects.filter( ~Q(sender=self.request.user), Q(seen=False), (Q(chat__user1=self.request.user) |\ Q(chat__user2=self.request.user))).count() return context #tests.py def test_update_password_view(self): credentials = { 'old_password': '123secret', 'password1': '321secret', 'password2': '321secret', } response = self.client.post('http://127.0.0.1:8000/users/change-password/', credentials, follow=True) self.assertRedirects(response, '/posts/', status_code=200, target_status_code=200) -
Page not found (404) Request Method: GET
Request Method: GET Request URL: http://127.0.0.1:8000 Using the URLconf defined in DjangoAPI.urls, Django tried these URL patterns, in this order: admin/ ^ ^department$ ^ ^department/([0-9]+)$ ^ ^employee$ ^ ^employee/([0-9]+)$ ^ ^employee/savefile ^ ^Photos/(?P.*)$ The empty path didn't match any of these Yesterday the Django portion of the project was fine and now I'm getting this error message. I've tried adding /home/ at the end of 127.0.0.1:8000 and still getting the same thing. Any help would be greatly appreciated. -
Why does sql skip rows in my own django bulk create?
I have created a method to overwrite bulk_create for certain queries, so that I get an pk returned from my MYSQL database. def dict_fetch_all(cursor): """Return all rows from a cursor as a dict""" columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for row in cursor.fetchall() ] class BulkQueryManager(models.Manager): def bulk_create_return_with_id(self, objs, batch_size=2000): self._for_write = True fields = [f for f in self.model._meta.concrete_fields if not isinstance(f, AutoField)] created_objs = [] with transaction.atomic(using=self.db): with connections[self.db].cursor() as cursor: for item in [objs[i:i + batch_size] for i in range(0, len(objs), batch_size)]: query = sql.InsertQuery(self.model) query.insert_values(fields, item) for raw_sql, params in query.get_compiler(using=self.db).as_sql(): cursor.execute(raw_sql, params) print('last row id: ', cursor.lastrowid, 'count: ', cursor.rowcount) raw = "SELECT * FROM %s WHERE id >= %s ORDER BY id DESC LIMIT %s" % ( self.model._meta.db_table, cursor.lastrowid, cursor.rowcount ) print(raw) cursor.execute(raw) created_objs.extend(dict_fetch_all(cursor)) print(created_objs) post_save.send(item.__class__, instance=item, created=True) return created_objs However, created_objs isn't always the same as my input objs. Very rarely the wrong objects get returned. My cursor.lastrowid is always correct, but it seems like the first few rows sometimes get skipped. For example: print output: last row id: 155407411 count: 22 print output: SELECT * FROM product_research_offer WHERE id >= 155407411 ORDER BY id DESC LIMIT 22 … -
pip not found on virtual environment
I created a virtual environment which called "hekim_venv". But when I try the install django in it, it gives "pip not found error". When I check the pip location there are no pip. When I check pip3 it indicates homebrew location. So there are no pip for venv's. How can I install libraries in virtual env? I can not understand and figure out the configuration. (hekim_venv) cucal@CANER-MacBook-Air dentist_project % pip install django zsh: command not found: pip (hekim_venv) cucal@CANER-MacBook-Air dentist_project % pip3 install django DEPRECATION: Configuring installation scheme with distutils config files is deprecated and will no longer work in the near future. If you are using a Homebrew or Linuxbrew Python, please see discussion at https://github.com/Homebrew/homebrew-core/issues/76621 Requirement already satisfied: django in /opt/homebrew/lib/python3.9/site-packages (4.0.2) Requirement already satisfied: asgiref<4,>=3.4.1 in /opt/homebrew/lib/python3.9/site-packages (from django) (3.5.0) Requirement already satisfied: sqlparse>=0.2.2 in /opt/homebrew/lib/python3.9/site-packages (from django) (0.4.2) DEPRECATION: Configuring installation scheme with distutils config files is deprecated and will no longer work in the near future. If you are using a Homebrew or Linuxbrew Python, please see discussion at https://github.com/Homebrew/homebrew-core/issues/76621 (hekim_venv) cucal@CANER-MacBook-Air dentist_project % which pip pip not found (hekim_venv) cucal@CANER-MacBook-Air dentist_project % which pip3 /opt/homebrew/bin/pip3 -
permission() for permission in self.permission_classes -> TypeError: 'str' object is not callable
does anybody know why do I get this error? I set default permission to IsAuthenticated. Only register has AllowAny, to allow users to register. Not Found: / [21/Feb/2022 21:43:06] "GET / HTTP/1.1" 404 2278 Not Found: /account [21/Feb/2022 21:43:11] "GET /account HTTP/1.1" 404 2317 Internal Server Error: /account/register Traceback (most recent call last): \venv\lib\site-packages\rest_framework\views.py", line 278, in <listcomp> return [permission() for permission in self.permission_classes] TypeError: 'str' object is not callable [21/Feb/2022 21:43:14] "GET /account/register HTTP/1.1" 500 106055 My views.py class: @api_view(['POST']) @permission_classes(['AllowAny']) def registration_view(request): serializer = RegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): account = serializer.save() data['response'] = "successfully registered a new user." data['email'] = account.email data['username'] = account.username else: data = serializer.errors return Response(data) I am using SessionAuthentication and IsAuthenticated as default authentication and permission in my settings.py file. CustomUser model just inherits from AbstractUser. No addition.