Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form.save method gives error AssertionError at /post/new/ Credentials file not found
I have a django view method that just wont submit a file on post request Here is the view method:- @login_required def create_post(request): user = request.user if request.method == "POST": form = NewPostForm(request.POST, request.FILES) if form.is_valid(): data = form.save(commit=False) data.user_name = user data.save() messages.success(request, f'Posted Successfully') return redirect('home') else: form = NewPostForm() return render(request, 'feed/create_post.html', {'form':form}) the data.save() function gives the credentials error. What could be the problem? -
Authenticating with DRF API key in unit tests return error: "Authentication credentials were not provided"
After recently discovering (and loving!) test driven development, I've started working on an API for a project of mine using Django with Django REST Framework and Django REST Framework API Key. However, I'm getting stuck trying to unit test some basic API functionality: every time I attempt to do a GET request to the API, it returns a 403: "Authentication credentials were not provided." Which is odd; I am adding the credentials in the header of the request before I send it off. When I print out the header of the RequestsClient, I am getting this result: {'User-Agent': 'python-requests/2.25.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'X-Api-Key': 'ADtIa4s9.joEWAwZH47uowolz60c1hYnskVujO8lQ'} Should work... yet for some reason my code will not see it. I've been going through a ton of Questions on here already and I am left completely baffled. Can you help me out a bit? Thanks in advance. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_api_key', 'core', 'base', 'api', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework_api_key.permissions.HasAPIKey', ] } API_KEY_CUSTOM_HEADER = "HTTP_X_API_KEY" urls.py from django.contrib import admin from django.urls import path from rest_framework import routers from … -
Why am I getting and error saying expected a ';' at 'cout' in visual studio code?
I am creating a hangman game and I used 'cout' and I am getting errors saying that I have to include ';' but 'cout' does not need that. Why am I getting this? #include<iostream> #include<time.h> #include<stdlib.h> using std::cout; using std::endl; using std::cin; [This is the beginning of my code. I did not include using namespace std; because I was getting a lot of errors using 'cout' and'cin'.] -
how to migrate the second db in django
I have two dbs one is default and the other one as first what i want is made some changes in first_db and now i wanna migrate In my settings.py: DATABASE_ROUTERS = ('app.router.DatabaseRouter',) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'primary_name', 'USER': 'root', 'PASSWORD': 'password', }, 'first': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'secondary_name', 'USER': 'root', 'PASSWORD': config('DB_MIDDLE_PASSWORD'), } } I tried the command python manage.py --database=first it showed it got migrated then when i tried to do python manage.py makemigrations it said all migrations are done and when i tried to run server and trying to insert some value in some table of first it started giving me error like the coloumn i added is not there can anyone help me. I think the migration didn't happend actually so anyone can show me how correctly migrate when having multiple database. -
How can I specify the group where I posted something on a template?
I'm a beginner in a Django and I've stumbled upon a problem. So I have a template where I detail all my posts(like who posted, at what time the post was created, and in what group I have posted something. How can I implement the following? When I click on that group, I want to redirect me to that actual group. models.py class Group(models.Model): name = models.CharField(max_length=255,unique=True) slug = models.SlugField(allow_unicode=True,unique=True) description = models.TextField(blank=True,default='') description_html = models.TextField(editable=False,default='',blank=True) members = models.ManyToManyField(User,through='GroupMember') urls.py from django.urls import path from . import views app_name = 'groups' urlpatterns = [ path('',views.ListGroups.as_view(),name='all'), path('new/',views.CreateGroupView.as_view(),name='create'), path('posts/in/<slug>/',views.SingleGroup.as_view(),name='single'), path('join/<slug>/',views.JoinGroup.as_view(),name='join'), path('leave/<slug>/',views.LeaveGroup.as_view(),name='leave'), ] _post - the template in my views app <div class="container"> <h3>{{ post.message_html|safe }}</h3> <div class="media-body"> <!-- --> <h5 class="mt-0"> <span class="username"> <a href="{% url 'posts:for_user' username=post.user.username %}">@{{ post.user.username }}</a> </span> <time class="time"> at <a href="{% url 'posts:single' username=post.user.username pk=post.pk %}">{{ post.created_at }}</a> </time> {% if post.group %} <span class="group-name">in <a href="{% url 'groups:single' %}">{{ post.group.name }}</a></span> {% endif %} -
Can I use flask for larger application
Everywhere i can see that Flask is used for only small application. Actually it is easy to scale and we can arrange code well as Django. Can someone tell me why flask is not used in larger application. If possible then how should i deploy or write code? Any changes is needed? -
Django ajax: How to pass a jquery variable to url
I have to make an ajax call from my template.html. The view takes in an id parameter which I have obtained from the jquery part. How do I append it to my url? Thank you Here is the code: <script> ..... #some codes app_div_id = $(this).closest('div').attr('id') var index = app_div_id.lastIndexOf("_"); var result = app_div_id.substr(index+1); var app_id = parseInt(result); $.ajax({ url:"{% url 'update_status' %}", #this url takes in an id param data:{ 'new_app_status':app_status, }, success: function (response) { }, error: function (response) { console.log(response.errors); }, }); }); </script> -
DjangoREST APIView - different url params for different methods
I got a DjangoREST APIView that supports Read and Create operations. Something like this: class FirebaseUser(APIView): ... get(request): ... post(request): ... urls.py: ... path('user/', views.FirebaseUser.as_view()), ... I need an API that would accept a read request with user id as url param GET .../api/user/<userId> But for create operation there's no user ID yet and I need something like this POST .../api/user/ What is the best way to make my APIView treat url params differently depending on method? -
Django graphene JWT on multiple users
I do have a user email account on django id email user_type 1 app@user.com 0 2 app@user.com 1 previously email account was set as unique, and change to unique_together = ('email', 'user_type') I want to hit the graphene_jwt createtoken and in my mutation def mutate(cls, root, info, **kwargs): try: result = super().mutate(root, info, **kwargs) ... I get a multipleobjectreturn because I do have 2 users, my question, how can I add user_type on the result so I the return token is base on the object user_type. Thanks in advance -
Django filter using time lookup doesn't work as expected
I want to filter the objects according to time only, regardless of the date part. Django has the time lookup for datetime fields, but when I use it the value is converted to the current timezone before filtering is done (this is mentioned on the official Django doc). For example, I have these sample records on PostgreSQL db (these are all in UTC): name datetime entry1 2021-04-03 11:00:00 entry2 2021-05-05 12:00:00 entry3 2021-05-06 12:00:00 entry4 2021-06-06 14:00:00 And with this model I want to get the all objects that have the datetime starting from 12:00 onwards, I use the query with the time lookup (and considering that USE_TZ=True): class Entry(models.Model): name = models.CharField(max_length=100) datetime = models.DateTimeField() >>> Entry.objects.filter(datetime__time_gte=datetime.time(12, 0)) I am expecting that the output would return the objects entry2, entry3 and entry4, but the actual response only returned entry4, which is +2 hours the filter value and the local timezone I have, which follows what was explained by the doc. This is the problem I've been experiencing, and so far I don't have any way over it. How can I filter the objects according to time only, without being affected by time lookups conversion i.e. conserve the filter value? -
Django post save function not able to save role id in profile model
I am creating user in django, on post save using reciever signal to save the Profile, I have profile model like this: class Profile(models.Model): user = models.OneToOneField( base_settings.AUTH_USER_MODEL, on_delete=models.CASCADE) has_sharkpod = models.BooleanField( "The users organization has a sharkpod", default=False) role = models.ForeignKey(Role, on_delete=models.DO_NOTHING, default=1) def __str__(self): return "Profile: " + self.user.username Now I want to save role as well that is passed in the request body of user creation, But I am not able to do that. This is my post save function for profile: @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) anyone can help ? -
How to protect my django content from directly accessing by url?
I am using queryset filter in my Blog page. Right now it’s only displaying blog those passed queryset filter. If I change any blog status = “pending” then it will hide from my blog page but user can still see the blog by accessing url. How to prevent them to see my “pending” status content? any idea? -
django-moderation trying to get unmoderated items to use in a view
I am using Django 3.2 and Django Moderation 0.7. According to the documentation, the attribute unmoderated_objects is a ModelManager which returns unmoderated objects. From the documentation: YourModel.unmoderated_objects.get(pk=your_model.pk) I am writing a view to allow me to list unmoderated items: /path/to/views.py class FooModerationQueueList(ListView): http_method_names = ['get'] model = Foo context_object_name = 'unmoderated_foos_list' def get_queryset(self): return self.model.unmoderated_objects.all() However, when I run the code above - the queryset returns the list of ALL objects (unmoderated AND moderated). Is there a way to fetch/return only unmoderated objects? Note: I am using my local version of django-manage) since the current version doesn't work with Django 3.2. I made minor changes such as removing references to six library, and removing previous migrations and making them again etc. (i.e. nothing that should result in the current strange behaviour). -
django app on ubuntu nginx not serving static files or media files
Trying to deploy django app on ubuntu. Everything is fine but static files or media files shows 404 error. here is part of my settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') in urls.py urlpatterns = [ .... ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) the file 'default' at /etc/nginx/sites-available/ looks like upstream django { server 127.0.0.1:8000; } server { listen 80; location /static/ { root /home/django; try_files $uri =404; } location / { try_files $uri @send_to_django; } location @send_to_django { proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://django; } } At first I thought its a problem of static files only, so I tried adding images through django admin and checked my page but has same error. Tried checking nginx error log, its like 2021/06/10 11:57:54 [crit] 34336#34336: *378 stat() "/home/django/static/images/slider/slide2-home1.jpg" failed (13: Permission denied), client: 74.125.212.233, server: , request: "GET /static/images/slider/slide2-home1.jpg HTTP/1.1", host: "mydomain.com" 2021/06/10 11:57:54 [crit] 34336#34336: *379 stat() "/home/django/static/images/testi1.png" failed (13: Permission denied), client: 74.125.212.235, server: , request: "GET /static/images/testi1.png HTTP/1.1", host: "mydomain.com" Here it says permission denied in all the files those are missing. Tried giving permission to static folder as well as staticfiles … -
Django Rest Mocking a Get request
I have a viewset for services and an action method defined as: @action( methods=['patch'], detail=True, url_name='deploy', url_path='deploy') def deploy(self, request, pk=None): """ An extra action for processing requests """ # Gets current instance instance = self.get_object() [...] # Sends GET request get = APIServiceRequestRouter() item_list = get.get_data_request() My get_data_request() method will send a get request to a url, which will return a json response. But of course, this goes out to a third-party api, which I want to mock in my unit test. I have this unit test for my deploy action endpoint on my viewset: def test_valid_deploy(self) -> None: """Test an valid deploy""" mock_request response = self.client.patch( reverse('services-deploy', kwargs={'pk': self.service2.pk}), data=json.dumps(self.deploy_payload), content_type='application/json' ) self.assertEqual(response.status_code, status.HTTP_206_PARTIAL_CONTENT) What I'm not sure is how to add a mocked get response into this unit test. The error I'm getting when I run my unit tests is that in my test_valid_deploy is that the get_data_request() method I have this: response = http_get_request.delay(api_url) response_obj = response.get() item_ids = response_obj['item_id'] But of course response_obj is empty or of NoneType and therefore the ['item_id'] key does not exist, I get a TypeError: 'NoneType' object is not subscriptable error. My thoughts then turned to mocking the get to … -
debug django docker dont work postgresql os.getenv don't work with VSCode
Hi i have worked nginx and app local server dockers. And all work fine but when i use VSCode debugger its dont load my .env file. This is my files: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.getenv('NAME'), 'USER': os.getenv('USER'), 'PASSWORD': os.getenv('PASSWORD'), 'HOST': os.getenv('HOST'), 'PORT': os.getenv('PORT'), } } and my debug files: version: "3.9" services: docker_app: image: docker_app build: context: . dockerfile: ./Dockerfile command: [ "sh", "-c", "pip install debugpy -t /tmp && python /tmp/debugpy --wait-for-client --listen 0.0.0.0:5678 manage.py runserver 0.0.0.0:8000 --nothreading --noreload", ] ports: - 8000:8000 - 5678:5678 tasks.json { "version": "2.0.0", "tasks": [ { "label": "echo", "type": "shell", "command": "echo Hello" }, { "type": "docker-build", "label": "docker-build", "platform": "python", "dockerBuild": { "tag": "docker:latest", "dockerfile": "${workspaceFolder}/Dockerfile", "context": "${workspaceFolder}", "pull": true } }, { "type": "docker-run", "label": "docker-run: debug", "dependsOn": ["docker-build"], "python": { "args": ["runserver", "0.0.0.0:8000", "--nothreading", "--noreload"], "file": "manage.py" } } ] } launch.json { "configurations": [ { "name": "Docker: Python - Django", "type": "docker", "request": "launch", "preLaunchTask": "docker-run: debug", "python": { "pathMappings": [ { "localRoot": "${workspaceFolder}/app", "remoteRoot": "/app" } ], "projectType": "django" } } ] } I don't have idea why debugger dont load .env i add to my docker-compose.debug.yml env_file: - .env and this don't … -
Django Admin Inlines with different fieldsets when "add another"
I'm having a lot of troubles while trying to modify the fields that my Inline model has. Here's what I have right now: models.py class A(models.BaseModel): name = models.TextField(verbose_name = _("Name"), blank=False) description = models.TextField(verbose_name = _("Description"), blank=False) class B(models.BaseModel): name = models.TextField(verbose_name = _("Name"), blank=False) description = models.TextField(verbose_name = _("Description"), blank=False) foreign = models.ForeignKey("A", verbose_name = _("A")) admin.py class BInline(admin.StackedInline): model = B extra = 0 readonly_fields = ['name'] fields = ['name'] class AAdmin(admin.ModelAdmin): fieldsets = ( ("Information", { "fields": ('name', 'description',), }), ) inlines = [ BInline ] pass As this is generating a panel where all the B elements are displayed into A with the name as read only, whenever I click the "Add another B" button, it will only display the name field as a read only mode, but as you can see, my model requires the name and description to not being blank, how can I change the fields just in that "Add another B" section and let everything else in read only? -
Running library with shared object files Django
I have a library that is using shared object files cagui.so cspb.so cspe.so cspib.so and I tried to run this library on my Django server but it didn't work. All files are in /static/. Do I need a special location for them? -
Django query set variable of type None
I have to run a code to get list of matching tags from car model for tag_list in tag_id_list: car_filter = (car_filter | car.filter(tag_in=[tag_list]) ).distinct() In the above code car is of type <class 'django.db.models.query.QuerySet'> How do I declare variable car_filter of type <class 'django.db.models.query.QuerySet'> to do the union of the car_filter and car Tried with car_filter = None and <class 'django.db.models.query.QuerySet'>None -
How to release memory resources after django-background-task completes its execution?
I'm executing some of the long-running tasks with Django-background-tasks. Background task takes some data from DB and process it internally which requires memory of 1 GB for each task. The task is running in the async way. When any task runs and completes its execution, Django-background-tasks does not release the memory after completing execution. Which causing memory issues to the Dameon pod. Any solution around deallocation of memory resources in Django-background-task? E.g. Note: resources available are fixed. so need a workaround on resource deallocation of tasks. @background() def my_task(): """ a long-running task that takes time of 20-30 mins, which includes some DB interactions. """ pass -
502 Bad Gateway nginx/1.18.0 (Ubuntu) in DigitalOcean Server
I have apache2 not nginx in my server but my site show me 502 Bad Gateway nginx/1.18.0 (Ubuntu) in DigitalOcean and I have django framework in my server. Please tell me how can I solve this problem. -
How do I use a string as the keyword in a values_list() statement?
I have an input variable and how can i assign it to value_list() options = "name, code" Model.objects.values_list(options) -
Django lock product read based on quantity
I'm new to Django been learning great stuff I'm stuck to one point. So I've been building a project like eCommerce, here each product has a certain quantity. I had made a custom API in ModelViewSet Here is my reference code def product(self, request): product_obj = Product.objects.filter(some_filter).first() product_resp = ProductSerializer(product_obj) return Response(product_resp, 200_ok**) So my issue is when a simultaneous call occurs, I saw people suggesting locks and approaches to update the count on right after gaining the instance how do we restrain a particular object/row to not appear in the simultaneous API call while lock/update on status is being carried out? Thank you in Advance! -
How to create a custom Pagination Class with page numbers?
I'm trying to create a custom pagination class. Here is my try: class CustomPagination(PageNumberPagination): page_item_count = 10 page = 1 def get_paginated_response(self, data): page = self.page next_page = None previous_page = None if page.has_next(): next_page = page.next_page_number() if page.has_previous(): previous_page = page.previous_page_number() return Response({ "page_count": page.count, "result_count": len(data), "next": next_page, "previous": previous_page, "has_next_page": page.has_next(), "has_previous_page": page.has_previous(), "result": data, }) This code is not properly working now and it's not what I want. I want give queryset parameter with query as page_item_count and page. I want to return something like that: return Response({ "page_count": page.count, # Page count. i.e. there are 100 items, and we show 10 per page, then it must be 10. "result_count": len(data), # object count. i.e. 100 "next": next_page, # Next page number. It's a number like 2,3,4,5... Not a link "previous": previous_page, # Prev page number, like 2,3,.... "has_next_page": page.has_next(), # boolean "has_previous_page": page.has_previous(), # boolean "result": data, # objects to be returned }) How can I achieve this? -
Python: Regex matching query, find matching digits inside the string
We have created an invoice numbering rule, in which the default pattern is AA-{num(x)}/{YYYY}. So let's say the first user which logged in didn't care about his pattern, and he started creating invoices. He has created few invoices and the last one that he managed to create had a numbering rule which is AB-003/2021. Everything seems cool and the back-end validation is pretty much working, but as I little did know the user is still able to make a custom pattern, for example, let's say that he can set the pattern to SZ{num(x)}. So let's say that the user wants to change the rule to this pattern and he starts using this SZ51 rule. The main problem is that our back-end server would eventually crash because we have only created a validation for this default AA-{num(x)}/{YYYY} pattern. As I spoke to one of our senior team lead back-end developers, he told me that we can start cutting the string from the right and loop every char and see if it is a digit or not. But if the user is able to set every pattern that he wants, that's a difficult thing to maintain. What if the user wants this …