Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to manage admins in a django website?
i'm trying to make a realtor website , every real estate has an owner , and its possible to have multiple admins class RealEstate(models.Model): owner = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) admins = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='managers') code = models.UUIDField(unique=True,default=uuid.uuid4,editable=False) real_estate_name = models.CharField(max_length=40,unique=True) when a user register as a realtor there is an option to fill out RealEstate form , to create his/her real estate profile , and he/she can add several admins to his/her RealEstate , whenever a real estate owner adds a new admin to his/her real estate profile , it has to show add new post option in the navbar , but it only show when the user request is owner the real estate this is the template <div class="dropdown-menu" aria-labelledby="navbarDropdown"> {% if request.user.realestate %} <a class="add-new" href="{% url 'new-post' %}">add new post</a> {% endif %} </div> what tag should i use to display add new post whenever the logged in user is a member of a real estate ? thank you .. -
Remove null fields from within an array in a Django Rest Framework response
I have a question, which is simiar to this one. I'm using django-rest-framework to build an API, using ModelSerializer to return data from a model. The models holds Arrays (using the PostgreSQL ArrayField). models.py class FashionData(models.Model): image_urls_norm = ArrayField(models.TextField(null=True), null=True) serializers.py class ProductLineSerializer(serializers.ModelSerializer): def to_representation(self, instance): result = super(ProductLineSerializer, self).to_representation(instance) return OrderedDict([(key, result[key]) for key in result if result[key] is not None]) class Meta: model = FashionData fields = ('image_urls_norm', ) (I'm overriding the to_representation function to remove any null fields from the response as outlined in Simon's response to the original question above) output "image_urls_norm": [ "https://somewebsite.com/image.jpg", null, null, null ], The first item in the array is always going to be populated, but the subsequent items can be null My question is, how can I remove the null items from array in the API response? -
Column not updating in django?
I am trying to update user data in Django but it's not updating. Code : customer = Customer.objects.get(email=request.POST["customer_email"]) agent = Agent.objects.get(email=request.POST["customer_agent"]) if request.POST.get("verify"): agent.no_of_verified_customer += 1 agent.save() import django.utils.timezone as tz customers.verified = True #this particular field is not updating customer.verified_on = tz.now() customer.verified_by = request.session["email"] customer.save() -
CSRF errors in Django Fargate Docker when using HTTPS Application Load Balancer
I have implemented a Django web app on AWS Fargate using Docker behind Application Load balancers. When I try to log in to the web app I get the following: Error 403 CSRF verification failed. Request aborted. Environment: I am using Application Load Balancer (ALB) as per the best practices of AWS. The ALB also has a TLS certificate to properly handle HTTPS when I run multiple instances of the web app. I tried to resolve the issue by forcing stickiness of the ALB targets assuming that the Round-Robin lands the requests on different servers. I also reduced the number of docker instances to one (so there is no Round-Robin). None of this made any difference. I managed to log in (to get CSRF to work well) was when I connected directly to a docker instance (no Load Balancer) and when I used only HTTP on the Application Load Balancer - disabling redirect to HTTPS. This leads me to believe that the issue is between the HTTPS part of the load balancer and the Django web app. Disabling HTTPS is not production ready, so I am back at square one. I saw a similar question posted here, without answers: django … -
Why is VSCode intellisense type hints different for these 2 Django model objects?
In the views.py after importing the Video model I am testing how intellisense works in VScode. This is the views.py from django.shortcuts import render from .models import Video # Create your views here. video1: Video = Video.objects.get(id=1) video2: Video = Video.objects.filter(id=1).first() this is the models.py: class Video(models.Model): ''' info about videos ''' video_id = models.TextField(blank=True, null=True) title = models.TextField() description = models.TextField() tags = models.TextField() is_uploaded = models.BooleanField() date_uploaded = models.DateField(null=True) filename = models.TextField() thumbnail_filename = models.TextField() When I start typing I get this for video1 which is from video1: Video = Video.objects.get(id=1): As you can see it offers model fields but for video2 which is from video2: Video = Video.objects.filter(id=1).first(): it doesn't offer model fields. Why is that and how can we fix it? -
external SQL to Django Models
I'm trying to figure out how to convert an external SQL database (that keeps updating) to models in Django. Any help would be greatly appreciated! I have an SQL database that gets updated every day. I have a Django web app that displays information from the SQL database and I'm trying to apply a filter (FilterView) to the displayed information but I need the information to be saved as models for that, right? I'm still pretty new to Django, thanks in advance for any help! -
I can't import css file using 'static' template in django
I'm trying to develop my first web application using Django, so the site looks like that: Site without changes On the other hand, I would like to apply some changes and put it in a CSS file called: cabecalho.css cabecalho.css file (with the changes) - path: (project/static/css/cabecalho.css): <style> body { font-family: Segoe UI; } .logo { float: left; } .logo img { width: 250px; padding: 20px; } .menu { float: right; padding: 40px; font-size: 15pt; } .menu a { margin-left: 15px; margin-right: 15px; } .bemvindo { clear: both; padding: 0 20px; } </style> These changes make the site look like that: Site with CSS changes In my HTML file called cabecalho.html, I tried to import with the line code: 1 try: <link rel="stylesheet" href={% static 'css/cabecalho.css' %}/> 2 try: <link rel="stylesheet" type="text/css" href={% static "css/cabecalho.css" %}/> 3 try: <link rel="stylesheet" type="text/css" href="css/cabecalho.css"> In this way, nothing happens! HTML file (cabecalho.html) - path: (project/templates/django/cabecalho.html): <!DOCTYPE html> {% load static %} <!-- Nova linha que carrega os arquivos estáticos --> <html> <head> <title>Django Form Exemplo</title> <link rel="stylesheet" href={% static 'css/cabecalho.css' %}/> </head> <body> <div class='logo'> <img src="{% static "images/logo.png" %}" alt="Logo da Hacked" /> </div> <div class='menu'> <a href="/app/sobre/">Sobre</a> <a href="/app/sair/">Sair</a> </div> … -
Polymorphic relationships in Django models
I am a newcomer in the Django framework and need some help. How can I create a polymorphic relationship between models? I am building an api in which I need to have a model that belongs to several models at once, let's say we have a comment model and I want it to belong to any model that can be commentable, in this case, the post and video models, but at the same time I want to have some referential integrity, I've tried with The contenttypes framework from Django and I get what I need but it allows me to create comments to videos or posts that don't exist, I've also tried with the django-polymorphic package together with django-rest-polymorphic, in this case I create a commentable model that extends from PolymorphicModel and the post and video models inherit from commentable, Doing it this way I get referential integrity but I see that the autoincrementable id is affected by the other models that also inherit from commentable, for example, if I create a post it is assigned the id 1, when I create a video it is assigned the id 2 even though they are two different tables, this does not … -
WSGIRequest body attribute contains two characters "\n" in place of newline
Noticed after upgrading Python3.7 + Django3.1, in attribute _request.body, newline was converted to two characters of "\n". PyCharm hint shows that _request is an object in class of WSGIRequest. As the partial log shows below, the text record contains "\n" in place of the newline. I suspect this is related to encoding of the new version of Python, and the issue doesn't exist in Python2.7. Any pointers will be highly appreciated. Partial logs: [09/Dec/2020 08:22:37] INFO [application.soap.views:34] b'<?xml version="1.0" encoding="UTF-8"?>\n<env:Envelope ... >...</env:Envelope>\n' [09/Dec/2020 08:22:37] INFO [application.soap.views:28] <HttpResponse status_code=200, "application/soap+xml"> More details of source code: >>> in file main_url.py: ... urlpatterns = [ url(r'^validation/$', soap_views.receive_validation_request, name='validation_request'), ... >>> in file view.py: ... def validate_request(_request, is_fulfillment=False): ... logger.info(_request.body) ... ... -
send message from bot to direct message after typing /slash command
I'm trying to make SlackBot and if I call him in some channel it works fine but when I call him (type slash-command) in any direct message I receive "The server responded with: {'ok': False, 'error': 'channel_not_found'}". Here is some part of my code: if slack_command("/command"): self.open_quick_actions_message(user_id, channel_id) return Response(status=status.HTTP_200_OK) def open_quick_actions_message(self, user, channel): """ Opens message with quick actions. """ slack_template = ActionsMessage() message = slack_template.get_quick_actions_payload(user=user) client.chat_postEphemeral(channel=channel, user=user, **message) Here are my Event Eubscriptions Here are my Bot Token Scopes Can anybody help me to solve this? -
Deploying python API heroku
I've deployed my python API which worked on localhost to heroku. Whenever I do any requests to API it doesn't work. Why is this happening? Site link: http://testapipythonf4.herokuapp.com/api/offers/ OperationalError at /api/offers -
Apply concurrency to allow only user to edit a document at a time
I would like to implement a simple document editor web app, where only one user can be editing one document at a time. Ie., if another user views that document, he will only be able to read it, but won't be able to modify it, until the first user finishes editing it. What would be the best approach for this? This looks like a concurrency problem -- what tools do Python 3 and Django 3 provide in order to tackle this in the best possible way? -
Django custom user model. Deleting user from admin panel
I have been experimenting with creating a custom user model in django. Everything seems to work fine, however, some of the admin panel commands seem to be erroring out. For example. I can delete a user through code using user = User.objects.filter(email="j@j.com").first().delete(). However, if i try to delete the user through the admin panel I get the following error. Internal Server Error: /admin/account/user/ Traceback (most recent call last): File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\admin\options.py", line 607, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\admin\sites.py", line 231, in inner return view(request, *args, **kwargs) File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File … -
I am heaving trouble in uploading the static files to the Django app. What i am missing i don't understand
{% extends 'base.html' %} {% load static %} {% block title %}Home{% endblock %} {% block content %} Template homepage {% endblock %} -
List multiple objects in Django UpdateView
Is there a way to update multiple objects at once in Django updateview. I'm trying to do this, when I put UpdateView nothing appears, but I put ListView they appear. Here's the View. class UpdateAllUsers(UpdateView): model = User context_object_name = 'users' paginate_by = 5 fields = ( 'first_name', 'last_name', 'job_title', 'twitter' ) template_name = 'users/edit-users.html' How do I get them listed as in the picture below in update mode? -
What should I choose php or Django
Which is easier django or Php for backend develop and which has bright future?(Note: I have basic knowledge of python) -
DRF - Create and Update - Requests with Nested Objects
I am trying to conduct PUT, PATCH, and POST requests with nested objects using django-rest-framework. Scouring StackOverflow - it seems that the best way to do this is to override the create and update methods on either the ModelSerialzier or ViewSet classes. However, there does not seem to be any consistency on when a ModelSerializer's create or update method is invoked. Furthermore - the ViewSet's update method seems to be invoked multiple times during a single a request which requires a lot of extraneous logic to prevent unwanted behavior. Ideally I would like a backend solution that is generic enough to be applied to any nested relationship - currently I have split my nested object into its individual components on the frontend and can successfully create and update objects this way - but again this requires (what seems like) a lot of unnecessary code. Suppose I have two models related like so: models.py class Sponsor(...): email = models.CharField(...) class Coupon(...): code = models.CharField(...) sponsor = models.OneToOneField(..., related_name=coupon) And serializers like so: serializers.py class CouponSerializer(): class Meta: model = Coupon fields = ['id', 'code'] class SponsorSerializer(...): coupon = CouponSerializer() class Meta: model = Sponsor fields = ['id', 'email', 'coupon'] Now suppose … -
Pick data from a file matching the right month
def dashboard(request) #some code to merge and align data in a correct way I have a bot that makes a directory every month with new data. Every file ends with the number of the month. For example: data01 (January) (file path: ../location/data01) data02 (February) (file path: ../location/data02) . . . data11 (November) (file path: ../location/data11) data12 (December) (file path: ../location/data12) I want to make an if-statement where basically the following happens: if month = current month select datafile with the current month example: if month = December select datafile '../location/data12' After the correct file has been selected, I want to run the code in def dashboard(request) on the data. Does anybody know how to do that the correct way? -
Django Rest-Framework Serialization Error
So this is the model that I want to serialize: from django.db import models class Concurs(models.Model): name = models.CharField(max_length=50) date = models.DateTimeField(auto_now_add=True) bio = models.TextField(max_length=5000, blank=True, null=True) participants = models.PositiveIntegerField(blank=True, null=True) medals = models.PositiveIntegerField(blank=True, null=True) done = models.BooleanField() link = models.CharField(max_length=1000, blank=True, null=True) class Meta: verbose_name="Concurs" ordering = ['-date'] def __str__(self): return self.name This is the serialization process: from rest_framework import serializers from .models import Concurs class ConcursSerializer(serializers.ModelSerializer): class Meta: model = "Concurs" fields = "__all__" This is the views.py: from django.shortcuts import render from .models import Concurs from .serializers import ConcursSerializer from rest_framework import generics class ConcursList(generics.ListCreateAPIView): queryset = Concurs.objects.all() serializer_class = ConcursSerializer class ConcursDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Concurs.objects.all() serializer_class = ConcursSerializer The error that I get whenever I navigate to the list or the detail view is: 'str' object has no attribute '_meta' I think I have made a mistake in the serialization process, I am new to RESTFramework so I really do not know. -
ImageField upload_to attribute not calling a function that it's supposed to call
I'm having a very strange error. I have the following model in my models.py: def get_upload_path_profile_picture(instance, filename): extension = filename.split('.')[-1] folder_name = instance.name folder_name = folder_name.replace(" ", "-") return "employers/{0}/profile_picture.{1}".format(folder_name, extension) class Employer(models.Model): # user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) name = models.CharField(max_length=100, unique=True) # location = models.CharField(max_length=MAXIMUM_LOCATION_LENGTH, choices=COUNTRY_CITY_CHOICES, blank=True) short_bio = models.TextField(blank=True, null=True) website = models.URLField(blank=True) profile_picture = models.ImageField(upload_to=get_upload_path_profile_picture, blank=True, null=True) admin_approved = models.BooleanField(default=False) def __str__(self): return self.name The code above works. However, when I change the get_upload_path_profile_picture function to: def get_upload_path_profile_picture(instance, filename): print("Here in the get_upload_path_profile_picture function") extension = filename.split('.')[-1] employer_name = instance.name employer_name = folder_name.replace(" ", "-") to_return = "employers/" + str(employer_name) + "_profile_picture." + str(extension) print("to_return") print(to_return) return to_return The line Here in the get_upload_path_profile_picture function never gets printed. I changed nothing in the view that handles this model. Why does this happen? What am I doing wrong? -
When pausing a video, how to get the current frame as a number?
I am struggling with a problem. I am rendering a video with video.js and this is awesome. But I want to get the current frame number when I pause the video or if I click on a button, doesn't really matter. It is about getting the frame number of the exact moment from the video when it is paused or clicked. I tried the normal method (time already played * fps) but this gives a number with a lot of decimals. So this is no option because it gives different numbers with the exact same frame. Does anyone have a clue? I am using Django frame work to te get the video from the database to html. -
django AUTH_USER_MODEL error while deploying to heroku
I am deploying my project on heroku. When i got this error: $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 178, in get_model return self.models[model_name.lower()] KeyError: 'customuser' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/init.py", line 157, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 211, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 181, in get_model "App '%s' doesn't have a '%s' model." % (self.label, model_name)) LookupError: App 'stock' doesn't have a 'CustomUser' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/init.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/init.py", line 377, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 24, in ready self.module.autodiscover() File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/init.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/app/.heroku/python/lib/python3.6/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, … -
I get an Api error from django back because of wrong date format?
//i have a django backend with sql database, with a date field //date format in the sql database 2020-12-10 13:10:20" //my kotlin code for parsing the date var formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd H:mm") val date = LocalDateTime.parse("2020-10-10 10:30", formatter) //the date field will be passed in the post request. //I get a 400 respons back, without the date field the post call is working fine ! //So i need to know how to parse the date to the right format which sql will accept. //Strange thing is that if i change the datefield with a put request it works just fine with the datefield. So i can change the field with a put request and the same code as posted above. But making a new date field with a post request is not working. -
Password Resetting view displays the django framework template
Password Resetting view displays the Django framework template instead of my HTML template. Even after adding template name in my urls.py, I still don't get any improvement urls.py from django.urls import path from .views import UserRegisterView, AddProductView, CategoryView, UserEditView, PasswordsChangeView from django.contrib.auth import views as auth_views from . import views from .views import * app_name = 'members' urlpatterns = [ # path('signup/', UserRegisterView.as_view(), name='signup'), # path('account/', UserEditView.as_view(), name='edit_account'), path('account/', views.edit, name='edit_account'), path('signup/', views.signup, name='signup'), path('activate/<slug:uidb64>/<slug:token>/', views.activate, name='activate'), # path('password/', auth_views.PasswordChangeView.as_view(template_name='registration/change_password.html')), path('password/', PasswordsChangeView.as_view(template_name='registration/change_password.html'), name='password'), path('add_product/', AddProductView.as_view(), name='add_product'), path('add_category/', CategoryView.as_view(), name='add_category'), path('password_reset/', auth_views.PasswordResetView.as_view(template_name='registration/password_reset.html'), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='registration/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='registration/password_reset_confirm.html'), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_complete.html'), name='password_reset_complete'), ] Tho, It only works for this path('password_reset/', auth_views.PasswordResetView.as_view(template_name='registration/password_reset.html'), name='password_reset'), Thanks for your help,:) -
Use data from GET request in get_intial() and get_form_kwargs() of FormVIew
I am trying to refactor my code to inherit FormView instead of View. The view I'm working with receives values in the GET request. I retrieve the values in the get_context_data method and pass them through different functions to end up with a set of variables that I can pass in the context. For the sake of example, this includes variables FOO and BAR. I need to initialise my form by passing variable FOO in the kwargs and additionally set my form field's initial value to BAR. I understand I should use the get_initial() and get_form_kwargs() methods to do this. I am just struggling with how to get FOO and BAR from the get_context_data method. I tried adding FOO and BAR to the context dictionary: context = super().get_context_data(**kwargs) context["FOO"] = foo context["BAR"] = bar return context And then calling it from the other methods: def get_initial(self): """ Get initial value for the form field """ initial = super(NameOfView, self).get_initial() context = self.get_context_data() initial_value = context["BAR"] initial.update({'name': inital_value}) return initial and the same for get_form_kwargs. But I get a RecursionError: maximum recursion depth exceeded while calling a Python object Any help understanding how I can acheive this will be appreciated