Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to ssend data to django dispatcher url with AJAX?
so i was trying to send category to django url (that takes category when visited through url) with ajax in this website, but i am getting this error which i don't seem to understand. Please help! urls.py path('category/<str:category>', views.getcategory, name = 'get_category'), ] views.py: #To get category if requested via AJAX if request.is_ajax and request.method == "GET": category = request.GET.get("last_joke_id", category) if category!=None: return HttpResponse('\n Received via Json. \n') else: return HttpResponse('\n Received via URL. \n') index.html: function send_category(category){ $.ajax({ type: 'POST', *url:"{% url 'get_category' %}"*, /*Error in this line*/ data: {'category':category}, success: function(response) { console.log("\n\nCategory data Successfully recived.\n"); console.log( response ); //displayJokes(response); }, error: function (response) { console.log('\n\n error in retriving category data:'); console.log(response); //return 'her'; } }) } </script>``` ***Error Message:*** ```django.urls.exceptions.NoReverseMatch: Reverse for 'get_category' with no arguments not found. 1 pattern(s) tried: ['jokes/category/(?P<category>[^/]+)$']``` -
How to set up an Amazon S3 bucket in secure way to serve media and static files to django
I'm using Amazon S3 to serve my static and media files to my django website. Do I need to Allow Public access in my Amazon S3 bucket or is there any secure way to do this -
Django read choices from a database table
I have an api that accepts requests of the form { "name": "John" "year": "2021" "product":"mask" } I would like to check if the product value is present in a list and reject or accept the request. Furthermore I need to be able to update the values of that list. Right now I am using django choices to implement the above but the prblem is that the list values are hardcoded. from django.db import models class Order(models.Model): product_choices = [ ('mask', 'Mask'), ('mask2', 'Mask1'), ('mask3', 'Mask2'), ('', 'Nothing') ] name = models.CharField(max_length=100, blank=False) year = models.CharField(max_length=4, blank=False) crop = models.CharField(max_length=100, blank=False, choices=crop_choices, default=crop_choices[-1][0]) Is there something I can do? -
'dict' object has not attribute 'pk' when using Django bulk_update()
I have the following code: obj = Products.objects.filter(dump__product_name = 'ABC, dump__product_color = 'black').values() new_price = [100, 200, 300] for item in range(len(obj)): obj[item]['price'] -= new_price[item] Products.objects.filter(dump__product_name = 'ABC, dump__product_color = 'black').bulk_update(obj, ['price']) But I am getting the error, Exception inside application: 'dict' has no attribute 'pk' The value of obj looks like this: <QuerySet [{'id': 1, 'product_name': 'Acer - Laptop', 'price': 350}, {'id': 1, 'product_name': 'Dell - Laptop', 'price': 450}, {'id': 1, 'product_name': 'Samsung- Laptop', 'price': 650}]> I am unable to figure out what's wrong with the code. Any help would be much appreciated. Thanks a lot in advance -
MongoDB doesn't work locally because of SRV error (no answer)
Situation We are working on the backend of our project consisting of two services written in Django and FastAPI. Both services use MongoDB as their database system. In Django we use djongo==1.3.0 for ORM compatibility. In FastAPI we use odmantic==0.3.4. Both of these libraries use pymongo==3.11.3 underneath. This MongoDB SRV error has been an issue for our Django service ever since we created it, but we managed to somehow work around it by not using the latest packages, such as: Django==2.2.20 djongo==1.3.0 pymongo==3.11.3 Recently due to security risks we had to upgrade: urllib3 from 1.25.8 to 1.26.5 pydantic from 1.8.1 to 1.8.2 Django from 2.2.20 to 2.2.22 Those were suggested by GitHub's dependabot. Problem When we run any of these services locally now they break with the following base exception: dns.resolver.NoAnswer: The DNS response does not contain an answer to the question: _mongodb._tcp.cluster0.k1eh0.mongodb.net. IN SRV Full log for Django: > python manage.py test Creating test database for alias 'default'... Traceback (most recent call last): File "/home/bk/inz/backend/authservice/venv/lib/python3.8/site-packages/djongo/database.py", line 10, in connect return clients[db] KeyError: 'djongo_test' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/bk/inz/backend/authservice/venv/lib/python3.8/site-packages/dns/resolver.py", line 212, in __init__ rrset = response.find_rrset(response.answer, qname, File "/home/bk/inz/backend/authservice/venv/lib/python3.8/site-packages/dns/message.py", … -
Django mark_safe and translation
I'm trying to test mark_safe and translation in a Django form. I've added style in help_text of a field in a form by adding mark_safe and everything works as expected. However i cannot figure out how to translate. For example i have: help_text=mark_safe(_('<p style="font-style:Italic; font-size:10px;">Enter your first name</p>')) If i run makemessages inside .po file i see the whole string as '<p style="font-style:Italic; font-size:10px;">Enter your first name</p>')) for translation. Is there any way so i can keep the style and also translate Enter your first name? Thank you! -
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