Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get param in permission.py django
I want to work with 'start' param in permissions.py How I can take it ? My model class Quiz(models.Model) : title = models.CharField(max_length=50) start = models.DateTimeField(default="2021-10-10") end = models.DateTimeField(default="2021-10-11") description = models.CharField(max_length=250) permissions.py from rest_framework import permissions class IsTimeNotDefined(permissions.BasePermission) : def has_permission(self, request, view): if request.method in permissions.SAFE_METHODS: return False return False -
p y manage.py run server not working in vscode editor
recently started learning Django and not to run this command "p y manage.py run server" I am using windows 10 and vs code(power shell) as terminal it's showing me again and again that i have no such file in the directory -
Django-filters, q objects & searching "contains" in manytomany & textfields at the same time
does anyone know anything about q objects and searching many to many fields? class tags(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Item(models.Model): item_id = models.CharField(default = random_string,max_length=5) tags = models.ManyToManyField(tags, verbose_name="tags") description = models.TextField() topic = models.TextField() I am using django-filters to create a filter / search area, below if filters.py: class ItemFilter(django_filters.FilterSet): multi_name_fields = django_filters.CharFilter(method='filter_by_all_name_fields') class Meta: model = Item fields = ['description','topic','tags'] def filter_by_all_name_fields(self, queryset, name, value): return queryset.filter( Q(description__contains=value) | Q(topic__contains=value) | Q(tags__contains=value) ) When I render the form field "multi_name_fields" I get an error " Related Field got invalid lookup: contains " The search form functions perfectly without the manytomany field added in but when I add in the "tags" manytomany field it gives me the above error. Does anybody have any ideas where I am going wrong or what I am missing? -
Docker configuration for Django+Vuejs+Gunicorn+Nginx lead to 502 Bad Gateway
Context I'm developing an application that will have to be deployed once per customer (it's not a multi-tenant app that all my customers would use). Ultimately, it will be deployed on AWS with services like RDS (DB), S3 (storage) and ECS (container service). You can see how I imagined it with the image below if it can help to answer me: My application is working well locally without Docker. But I want to use a dockerized version of it locally before trying to deploy it on AWS, because I want to be able to run it locally with Docker before trying to do it on AWS (...). Since all my customers would have their own instance (and customer1 could have a different version than customer2 at some time), I thought about a single container with everything needed, as you can see on the image : the Django application, the Vue built files, gunicorn and nginx. Question 1 : Is it a good idea to do it like this ? Or should I use a docker-compose thing with multiple services (backend (django) & nginx). Would it lead to multiple containers ? To do so, I did the following configuration : Dockerfile: … -
Django switch database user
Assume I got different database users, and each of them have different permissions (already settled in db side). How can I switch between different db users? 'ENGINE': 'django.db.backends.postgresql', 'NAME': '****', 'USER': '****', # i got several users here and want to switch them 'PASSWORD': '****', 'HOST': '*****', 'PORT': '***', -
Video not playing on ios (safari)
Video Link This video is playable on windows as well as android. But not in ios. I am using Django (python framework) for backend. What should i do ? -
Can we use class create view to build multiple forms in django?
class formsView(CreateView): model= dummy fields= "__all__" template_name= "index/page1.html" success_url="page1" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['dummy'] = dummy.objects.all() context['tummy']= tummy.objects.all() return context Using this code, I am able to render a form based on the model 'dummy', and am able to get the context from another model 'tummy' to use in my html code. However, I was wondering if there was a way to include more than one form using the create view. -
How to run tests for specific django apps when you have a conftest in a root folder
I work on a Django project and we have dozens of different apps. We a have a global conftest in the root folder and conftests in each app's folders. Sometimes we need to run tests for separate apps and not wait for all tests to complete. How can I run tests for a specific app if they don't work without running the global conftest? So command pytest -v apps/app_one won't work because it loads only a conftest in the app_one folder and does not load a global conftest. -
Problem with getting data from input for django
I have a problem with getting data from the tag on the page with the Django form. templates: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input id="result" type="hidden"> <script type="text/javascript"> const upload = document.querySelector('#inputGroupFile01'); const result = document.querySelector('#result'); upload.addEventListener("change", (e) => { previewFunc(e.target.files[0]); }); function previewFunc(file) { if (!file.type.match(/image.*/)) return false; const reader = new FileReader(); reader.addEventListener("load", (e) => { const label = document.createElement('label'); label.for = 'photo'; const input = document.createElement('input'); result.name = 'photo'; result.value = 'e.target.result'; result.src = e.target.result; result.type = 'image'; result.id = 'result'; {#result.innerHTML = '';#} {#result.append(input);#} }); reader.readAsDataURL(file); } </script> <button type="submit">{% trans 'Apply' %}</button> </form> Views: class LoadPhotoView(BaseMixin, generic.CreateView): model = Photo template_name = 'load_photos/load_photo_page.html' form_class = PhotoUploader def post(self, request, *args, **kwargs): print(request.POST.get('photo')) print(request.FILES.getlist('photo')) print(request.FILES.get('photo')) return render(request, self.template_name, {'form': self.form_class}) After executing javascript code page has next structure at the screen: But I still can't get photo in method post in my view(I get None or empty list) -
Django: Number the integer fields of the filtered queryset in order (efficiently)
It is possible to assign sequential numbers to the integer fields in the filtered queryset I am looking for by doing the following, but the query is issued every time I save(). How is it possible to save it? queryset = Model.objects.filter(user=user) for i, item in enumerate(queryset, start=1): item.order = i item.save() -
Run separate threads along Django web server
I'm fairly new to the Django framework and also far from being an expert Python programmer, so sorry in advance if my request may sound trivial. I set up my web server in Diango, but what I would like to do now, is to have two python threads, one sending messages on a socket to another process (e.g. after some requests are performed on the web server) and the other receiving them from the same process (e.g. it receives a request that have some effect on the web server). So, down to my question, where should I place this code? I need it to be initialized when the web server starts up, and I want it to be accessible anywhere (e.g. when the code of a certain view is processed I want to signal the tx thread to send a message on the socket). I don't know if there is something django-specific to help me with this task or not. Thanks in advance for any help! -
how to filter data from two django class
I have two Django class,I want to filter VCDUnavailAudit by site_key in Django Get method, how could I do enter code here class VCDUnavailAudit(models.Model): user_key = models.IntegerField() user_name = models.CharField(max_length=40) class User(models.Model): user_key = models.AutoField(primary_key=True) site_key = models.IntegerField() @api_view(['GET']) def get_unavail_audit_records_by_site(request, site_key: int): availability_audit_records = VCDUnavailAudit.objects.filter serializer = VCDUnavailAuditSerializer(availability_audit_records, many=True) return Response(serializer.data, status=status.HTTP_200_OK) -
Postgres backup database
I'm working on a django project and i'm using postgres for database. I want to backup the database and i tried to use dbbackup library. While in development env works fine in production i got an error of no password. The command i'm running is the same in both environments and also the configuration, the only difference is the database credentials Backing Up Database: database CommandConnectorError: Error running: pg_dump --host=localhost --username=databaseuser --no-password --clean database pg_dump: error: connection to database "database" failed: FATAL: password authentication failed for user "databaseuser" FATAL: password authentication failed for user "databaseuser" Any suggestions? -
How to Force Current User to a Field in Django Rest Framework
Consider I have models, a serializer and a viewset as below: # models.py class Foo(models.Model): owner = models.ForeignKey(User, models.CASCADE, related_name="bars") # serializers.py class FooSerializer(serializers.ModelSerializer): owner = serializers.PrimaryKeyRelatedField( default=serializers.CurrentUserDefault(), queryset=User.objects.all(), ) class Meta: fields = ["pk", "owner"] # viewsets.py # registered to /api/foos/ class FooViewSet(viewsets.ModelViewSet): serializer_class = FooSerializer permission_classes = [permissions.IsAuthenticated] queryset = Foo.objects.all() So, when I send a POST request to /api/foos/ with an empty body, it creates a Foo instance with its owner field set to the current logged-in user, which is fine. However, I also want to totally ignore what the currently authenticated user sends as a value to owner. For example, if I do a POST request to /api/foos/ with body user=5 (another user, basically), CurrentUserDefault sets the Foo.owner to that user, which is not the behavior I want to have. I always want to have the current authenticated user as the value of the field owner of a new Foo instance, or, in other words, I want FooSerializer.owner field to be set as currently authenticated user as a value and ignore what is sent on POST request as a value of owner. How do I do that? Thanks in advance. Environment django ^2.2 djangorestframework ^3.12.4 -
Django-python3-ldap problem to connect admin/login - SyntaxError at /admin/login/
I've just tried to connect to my Active Directory LDAP server. I'm sure, that everything in configuration (like IP and DN) is OK. But If I want to go to admin page, it shows me error (it's below). I don't know how to do it. AUTHENTICATION_BACKENDS = ( 'django_python3_ldap.auth.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) LDAP_AUTH_URL = "ldap://srv.ext.cz" LDAP_AUTH_USE_TLS = None LDAP_AUTH_SEARCH_BASE = "OU=Users,OU=Temp,OU=SRC,DC=example,DC=cz" LDAP_AUTH_OBJECT_CLASS = "user" LDAP_AUTH_USER_FIELDS = { "username": "sAMAccountName", "first_name": "givenName", "last_name": "sn", "email": "mail", } LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",) LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data" LDAP_AUTH_SYNC_USER_RELATIONS = "django_python3_ldap.utils.sync_user_relations" LDAP_AUTH_FORMAT_SEARCH_FILTERS = "django_python3_ldap.utils.format_search_filters" LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_active_directory_principal" LDAP_AUTH_ACTIVE_DIRECTORY_DOMAIN = "xxx.cz" LDAP_AUTH_CONNECTION_USERNAME = None LDAP_AUTH_CONNECTION_PASSWORD = None LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "class": "logging.StreamHandler", }, }, "loggers": { "django_python3_ldap": { "handlers": ["console"], "level": "INFO", }, }, } Error: > File > "C:\Users\fc\.virtualenvs\projekt-O8yDgQSj\lib\site-packages\django\core\handlers\exception.py", > line 47, in inner > response = get_response(request) File "C:\Users\fc\.virtualenvs\projekt-O8yDgQSj\lib\site-packages\django\core\handlers\base.py", > line 181, in _get_response > response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\fc\.virtualenvs\projekt-O8yDgQSj\lib\site-packages\django\views\decorators\cache.py", > line 44, in _wrapped_view_func > response = view_func(request, *args, **kwargs) File "C:\Users\fc\.virtualenvs\projekt-O8yDgQSj\lib\site-packages\django\contrib\admin\sites.py", > line 398, in login > **self.each_context(request), File "C:\Users\fc\.virtualenvs\projekt-O8yDgQSj\lib\site-packages\django\contrib\admin\sites.py", > line 316, in each_context > 'available_apps': self.get_app_list(request), File "C:\Users\fc\.virtualenvs\projekt-O8yDgQSj\lib\site-packages\django\contrib\admin\sites.py", > line 505, in get_app_list > app_dict = self._build_app_dict(request) File "C:\Users\fc\.virtualenvs\projekt-O8yDgQSj\lib\site-packages\django\contrib\admin\sites.py", > line 450, … -
Access Django context data in get_initial
I have an expensive call in my view's get_context_data to calculate a field for the template. I would like to use this result in the view's get_initial_data to set the initial value of my_field but I cannot see how to access the context_data from within get_initial_data or how to pass it as a parameter. def get_context_data( self, *args, **kwargs ): context = super().get_context_data( **kwargs ) context['expensive_result'] = expensive_function() return context def get_initial( self ): initial = super().get_initial( **kwargs ) # Initialise my_field with expensive result calculated in get_context_data initial['my_field'] = context['expensive_result'] # How to do this? return initial -
Failed - network error when downloading a file
I have configured the apache webserver for my Django application for https redirection and its working fine. When i was testing my application I found out that it sometimes shows Failed -Network error when trying to download a xlsx file .Downloading a tarfile does not give any error.. Tried in different browser but got the same result.. Not sure what is wrong Please Help. Thanks -
Posting Dynamic table Form values using Jquery and fetching that post in django view
I know this is not the conventional method but I wanted to try this out and make it successful. Here is a html file that I am rendering using a django view. {% extends 'base.html' %} {% block table_name %}Invoice{% endblock %} {% block table_view %} <form method="POST" action="/submit" id="myForm"> {% csrf_token %} <table border="1" class="center table-responsive table table-striped" width="100%" cellspacing="0" style="padding-left:418px" id="table"> <thead> <tr> <th colspan="6">INVOICE</th> </tr> </thead> <tr> <th COLSPAN="3">INVOICED TO</th> <td colspan="4" class="center"> <input list="show" type="text" class="center" style="width:100%" name="client_name"> <datalist id="show"> {% for client in clients %} <option value="{{ client.first_name }}"></option> {% endfor %} </datalist> <br><br><textarea type="text" name="client_address" placeholder="Address" style="width:100%" rows="3"></textarea></td> </tr> <tr> <th COLSPAN="3">INVOICED FROM</th> <td colspan="4" class="center"><input type="text" name="company_name" style="width:100%" placeholder="Company Name"><br> <br><textarea type="text" name="company_address" placeholder="Address" rows="3" style="width:100%"></textarea></td> </tr> <tr> <th COLSPAN="3">VESSEL NAME</th> <td colspan="4" class="center"><input name="vessel_name" style="width:70%" type="text" placeholder="Vessel Name"></td> </tr> <tr> <th COLSPAN="3">PO NUMBER</th> <td colspan="4" class="center"><input type="text" name="po" style="width:70%" placeholder="PO number"></td> </tr> <tr> <th COLSPAN="3">INVOICE NUMBER</th> <td><input name="invoice_number" type="text" placeholder="#/2021" disabled></td> <th>DATE</th> <td colspan="" class="center"><input type="date" name="date"></td> </tr> <tr CLASS="CENTER"> <th>S. NO.</th> <th COLSPAN="2">PARTICULARS</th> <th COLSPAN="1">GST</th> <th colspan="2">TOTAL AMOUNT</th> </tr> <tr CLASS="CENTER"> <td class="center">1</td> <td COLSPAN="2" class='center'><input type="text" name="product1" placeholder="Name of product"></td> <td><input type="number" name="gst1" placeholder="gst"></td> <td COLSPAN="2"><input name="cost1" type="number" placeholder="cost"></td> </tr> … -
Filter model by datetime in django
I need to filter model with (datetime.now() < end) My model class Quiz(models.Model) : title = models.CharField(max_length=50) start = models.DateTimeFieldField(default="2021-10-10") end = models.DateTimeFieldField(default="2021-10-11") My view class GetQuizView(generics.ListAPIView) : def get_queryset(self): now = datetime.now() return Quiz.objects.filter(start = now) serializer_class = QuizListSerializer But I can only filter with equal time, I can't use > or < -
compare objects in views.py of 2 different models objects in Django
I am trying to compare 2 objects (skills of a job posting such as web development, marketing, etc to the same skills of a logged-in user), if matched will display that job posting. The goal is to display multiple job postings that match the user. Currently, jobmatch.html does not display any jobs. Thank you for taking the time!! views.py from apps.job.models import Job from apps.userprofile.models import User_profile def match_jobs(request): match_jobs = {} for job in Job.objects.all(): if job.product_management == User_profile.product_management: match_jobs['product management'] = job elif job.web_development == User_profile.web_development: match_jobs['web development'] = job elif job.user_experience == User_profile.user_experience: match_jobs['user experience'] = job elif job.marketing == User_profile.marketing: match_jobs['marketing'] = job elif job.finance == User_profile.finance: match_jobs['finance'] = job return render(request, 'jobmatch.html', match_jobs) Job.models.py class Job(models.Model): title = models.CharField(max_length=255) location = models.CharField(max_length=255, blank=True, null=True) description = models.TextField() requirements = models.TextField(blank=True, null=True) product_management = models.BooleanField(default=False) web_development = models.BooleanField(default=False) user_experience = models.BooleanField(default=False) marketing = models.BooleanField(default=False) finance = models.BooleanField(default=False) User.models.py class User_profile(models.Model): user = models.OneToOneField(User, related_name='userprofile', on_delete=models.CASCADE) is_employer = models.BooleanField(default=False) resume = models.ImageField(default='default.jpg', upload_to='resume') full_name = models.CharField(max_length=255, default='Enter full name') relevant_background = models.TextField() product_management = models.BooleanField(default=False) web_development = models.BooleanField(default=False) user_experience = models.BooleanField(default=False) marketing = models.BooleanField(default=False) finance = models.BooleanField(default=False) jobmatch.html {% for job in match_jobs %} <div class="colum is-4"> … -
Difficult to run VS code
PS E:\learning\project\django\restaurant> python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. October 22, 2021 - 09:21:08 Django version 3.2.8, using settings 'restaurant.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. -
Django REST Framework: How do I save query set if I use the same Prepetch object multiple times in prefetch_related?
We need to use the queryset saved by annotate in two models in prefetch_related as follows, but if we use it as follows, the prefetch queryset will be called unnecessarily as many times as specified in prefetch_related If you use Is this the correct behavior? #views.py prefetch = Prefetch( "user", queryset=User.objects.annotate( is_verified=Max( Cast( "emailaddress__verified", output_field=IntegerField(), ) ) ), ) queryset = queryset.prefetch_related( Prefetch( "reply_set", queryset=Reply.objects.prefetch_related(prefetch) ), prefetch, ) #serializers.py class UserDetailSerializer(serializers.ModelSerializer): is_verified = serializers.SerializerMethodField() class Meta: model = User fields = ( "is_verified", ) def get_is_verified(self, user): return bool(user.is_verified) class CommentSerializer(serializers.ModelSerializer): user = UserDetailSerializer(read_only=True) replies = serializers.SerializerMethodField() class Meta: model = Comment fields = ( "replies", ) def get_replies(self, obj): queryset = obj.reply_set if queryset.exists(): replies = ReplySerializer(queryset, context=self.context, many=True).data return replies else: return None class ReplySerializer(serializers.ModelSerializer): user = UserDetailSerializer(read_only=True) class Meta: model = Reply fields = ("user") -
How to pass data to serializers in django
I want to pass user_id from view to serializer I have model Answer class Answer(models.Model) : text = models.CharField(max_length=500) question_id = models.CharField(max_length=25) user_id = models.CharField(max_length=25, default=1) This is my Serializer class CreateAnswer(generics.CreateAPIView) : def get_serializer_context(self): context = super().get_serializer_context() context["id"] = self.request.user.id return context serializer_class = AnswerQuestionSerializer queryset = Answer.objects.all() What I need to write in my view to take user_id and create model with this user_id ? -
ModuleNotFoundError: No module named 'dj_rest_authcore' => dj-rest-auth
I have followed the documentation(https://dj-rest-auth.readthedocs.io/en/latest/installation.html). Installed the package using pip install dj-rest-auth Added dj_rest_auth app to INSTALLED_APPS in your django settings.py: Added path('dj-rest-auth/', include('dj_rest_auth.urls')) in urls.py When I am doing python manage.py migrate. I am getting the below issue. return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'dj_rest_authcore' What I am doing wrong here? -
Can't change user password for Django user model using ModelViewSet
I was using Django user model using the ModelViewSet. When I am making a request to update the password for the current user that is logged in. Although I get a 200 OK response but my password never changes to the new one that I changed. I also tried making the request from my admin user and when I made the PUT request with the password, it got changed to something else and I was logged out from the django admin panel. Here is my views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [IsAuthenticated, IsOwnerOfObject] authentication_classes = (TokenAuthentication,) serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'password'] extra_kwargs = { 'password' : { 'write_only':True, 'required': True } } def create(self, validated_data): user = User.objects.create_user(**validated_data) Token.objects.create(user=user) # create token for the user return user urls.py router = DefaultRouter() router.register('articles', ArticleViewSet, basename='articles') router.register('users', UserViewSet, basename = 'users') urlpatterns = [ path('api/', include(router.urls)), ] permissions.py class IsOwnerOfObject(permissions.BasePermission): def has_object_permission(self, request, view, obj): return obj == request.user Here is how I am making the request, with Authorisation token in the Headers field Response :