Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nest.js serializer like Django
I am currently using Nest.js, Postgresql, Typeorm for my backend. Now I am trying to do is to see an specific entity field differently by each user. For example there are 10 posts and one user has bookmarked 3 of them. Only a user who bookmarked the post can get isBookmarked = true, others isBookmarked = false. I used Django a bit and I used serializer to implement the same logic. I looked for Nest.js serializer (https://docs.nestjs.com/techniques/serialization) but I think it is a bit different than what I thought. Please tell me how to use this serializer as Django does, or any other ways to implement the logic. -
How can I get the username of each contact, using foreignkey
I'm working on a small project using Django / Multi Tenancy. i have a public table called ContactCenter ( where tenants can share contacts between theme ) This is my models : class CustomUser(AbstractUser): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) username = models.CharField(max_length=255, unique=True, blank=False, null=False) class ContactCenter(models.Model): contact = models.IntegerField(blank=False, null=False) contact_source = models.ForeignKey(CustomUser, to_field="id", on_delete=models.CASCADE, null=True, blank=False) shared_with = models.ForeignKey(CustomUser, to_field="id", related_name="sw", on_delete=models.SET_NULL, null=True, blank=False) how can i select the contact_source & shared_with & username I learned about prefetch_related, I tried to use it but it was hard for me to access the related records, using a loop -
Django widgets and date fields
In my creation template, the date field is rendered as a CharField and does not allow to select a date, while I need this validation date. My Model includes a DateField : class Interview(models.Model): date_planned = models.DateField(verbose_name="Planned Date", blank=True, null=True) My View calls the ModelForm quite normally: class InterviewCreateView(UserAccessMixin, CreateView): permission_required = "interviews.add_interview" model = Interview form_class = InterviewForm fields = ['date_planned', 'topics'] template_name = "interviews/interview_create_form.html" success_url = reverse_lazy("interviews:interviews_list") ``` My Form just calls the Meta and includes a widget: class InterviewForm(ModelForm): def init(self, *args, **kwargs): super().init(*args, **kwargs) self.fields['date_planned'].widget.attrs.update({'size': 40, 'type': 'date'}) class Meta: model = Interview fields=['topics', 'date_planned']``` Indeed the size of the input fields goes up to 40, however the date format is ignored by the system and lets my date_planned field being displayed as a CharField -
localhost: 3000 has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. REACT and DJANGO
I am able to get list of objects on http://127.0.0.1:8000/api/todos running on DJANGO, I wanna product detail page with id, http://127.0.0.1:8000/api/todos/14. http://127.0.0.1:8000/api/todos/14. works fine in POSTMAN, and even in chrome. but in react I get Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/todos/14' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I am using Axios. Product.js const [dataItems, setDataItems] = useState([]); useEffect(() => { axios .get("http://127.0.0.1:8000/api/todos/") .then((res) => { console.log(res); setDataItems(res.data); }) .catch((err) => { console.log(err); }); }, []); ProductDetail.js const [detailItems, setDetailsItems] = useState([]); useEffect(() => { axios.get("http://127.0.0.1:8000/api/todos/14").then((res) => { console.log(res); }); }, []); I have seen similar question, but I am able to make connection with localhost:3000 and get all the values here. it just for the detail object with id not showing up. -
"Couldn't find that process type (web)." when deploying to Heroku from Django
Trying to deploy my Django application on Heroku. When I try to add Dyno's, heroku ps:scale web=1, it gives me an error message stating "Couldn't find that process type (web)." I double checked the name of Procfile, the location, and the content, and it all appears correct. Any ideas? I attached a screen shot of my directory and the content. I have no clue what could be incorrect with this. Anyone have any ideas? enter image description here -
Unable to connect via websockets (daphne, django, nginx, docker)
Websocket with django, docker-compose, nginx, daphne. Regular http connections are working fine, but there's no output coming from websocket connections. The websocket doesn't appear to be active. Connecting through javascript produces an error: new WebSocket('ws://127.0.0.1:8000/ws/pollData'); // WebSocket connection to 'ws://127.0.0.1:8000/ws/pollData' failed: or when connecting to ws://localhost/ws/pollData: new WebSocket('ws://localhost/ws/pollData'); // Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist. docker-compose.yaml version: '3' services: volume_configurer: image: busybox volumes: - shared:/shared:z - static:/static:z command: ["/bin/sh", "-c", " mkdir -p /static; chmod -R 777 /static; mkdir -p /shared/sync; chmod -R 777 /shared/sync; echo STARTED > /shared/sync/volumesetter && chmod a+r /shared/sync/volumesetter"] db: container_name: postgresdb image: postgres:latest restart: always env_file: - project.env ports: - 5432:5432 volumes: - postgres-data1:/var/lib/postgresql/data1:z web: build: context: ./ dockerfile: ./mdb/Dockerfile container_name: django command: > daphne mdb.asgi:application -b 0.0.0.0 -p 8000 env_file: - project.env expose: - 8000 depends_on: - db volumes: - ./mdb:/home/app/web/:z - static:/home/app/web/static/:z - shared:/uploads/:z nginx: container_name: nginx image: nginx restart: always ports: - 80:80 volumes: - ./nginx:/etc/nginx/conf.d:z - static:/home/app/web/static/:z depends_on: - web - db volumes: postgres-data1: static: shared: nginx.conf: upstream mdb { server django:8000; } server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; server_name localhost; client_max_body_size 2000M; location /static/ { alias /home/app/web/static/; } location /ws/ { proxy_pass … -
Reverse url not working for ReadOnlyModelViewSet - Django Rest framework
I am getting a rather pesky error - reverse for 'myad-list' not found. 'myad-list' is not a valid view function or pattern name. The similar code is working when I used ModelViewSet My view set class:- class GetMyAdsViewSet(viewsets.ReadOnlyModelViewSet): """Get my ads""" serializer_class = serializers.BookSerializer authentication_classes = (TokenAuthentication,) permission_classes = (permissions.IsAuthenticatedOrReadOnly,) queryset = Book.objects.all() def get_queryset(self): """ Filtering according to query params """ queryset = Book.objects.all() queryset = queryset.filter(user=self.request.user.id) return queryset My url file:- router.register('myads', views.GetMyAdsViewSet) My code in test file:- MY_ADS_URL = reverse("book:myads-list") -
Django Not showing Static Images but shows its alternative text(alt) by displaying["GET /static/image/down.jpg HTTP/1.1" 404 1771] in console window
I just simply want to show my static image in template. I have looked every possible ways to solve this issue and try various approaches but could not get my static images in template. The alternative text of the respective image is shown but image itself not loaded and get this in terminal Window "GET /static/image/down.jpg HTTP/1.1" 404 1771 here how my Django project is laid out is given below project files hierarchy in urls.py from django.conf.urls import include,url from django.contrib import admin from django.urls import path from myapp import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ .......] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) in settings.py STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, '/static/') MEDIA_ROOT = os.path.join(BASE_DIR, "media/") MEDIA_URL= "/media/" in template question.html i have tried different approaches to access the image[with {% load static %} tag on the top of html page] like <img src="{% static 'image/down.jpg' %}"> <img style="width: 245px; height: 247px;" alt="Image description" src="{% static 'image/down.jpg' %}"/> <img src="/static/image/up.jpg" alt="Second-image" /> but could not get the problem solved -
Unable to connect background Imge with static file Django
I have following html template <div class="owl-slide cover" style="background-image: url({% static 'img/slides/slide_home_2.jpg'%});"> </div> But I am not able to load static background. my static directory is same as it is in django project path along with templates. here is my part of setting.py for static files STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/',) Everything seems look ok but my background is not working any suggestion will be helpful -
Django call_command test files, ModuleNotFoundError
I have a piece of celery code that runs Django test in the background, it looks like this: @shared_task() def execute_test_from(files): if isinstance(files, list): dir1 = ['app1.tests.' + file for file in files if file + '.py' in os.listdir(path1)] dir2 = ['app2.tests.' + file for file in files if file + '.py' in os.listdir(path2)] fs = dir1 + dir2 call_command('test', ' '.join(fs), verbosity=3, keepdb=True) path1 and path2 contain tests, files is a list of the specific file containing the test path1 = os.path.join(os.getcwd(), "app1/tests") path2 = os.path.join(os.getcwd(), 'app2/tests') # files will look like this files = ['app1.tests.test_1', 'app1.tests.test_2', 'app2.tests.test_1', 'app2.tests.test_2'] and my folder structure looks like this: |-- src |-- manage.py |-- myproject |-- __init__.py |-- settings.py |-- urls.py |-- app1 |-- __init__.py |-- tests |-- __init__.py |-- test_1.py |-- test_2.py |-- app2 |-- __init__.py |-- tests |-- __init__.py |-- test_1.py |-- test_2.py Naturally when I run ./manage.py test app1.tests.test_1 app2.tests.test_2 it works, I just ran two different files with tests. However, when I try this same process with call_command like in the celery code above, I run into ERROR: test_1 app1 (unittest.loader._FailedTest) ImportError: Failed to import test module: test_1 app1 My traceback most recent call reads: ModuleNotFoundError: No module … -
How to link an existing model with user model in Django
This is a quite simple question I think, but I'm new with Django and searching the best/correct way to do things. So forgive me if I'm asking stupid questions. I have a model called Person in my Django app. It contains just basic info of a person, no personal data involved yet: class Person(models.Model): birthday = models.DateField(null=True) gender = models.CharField(max_length=10) height = models.CharField(max_length=3) weight = models.CharField(max_length=3) Now I want to also add a feature for the person to register and log in. What is the correct way to do this? Many tutorials seem to suggest using the forms.py file, like this for example: from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegisterForm(UserCreationForm): birthdate = forms.DateField() discord_id = forms.CharField(max_length=100, help_text='Discord ID') zoom_id = forms.CharField(max_length=100, help_text='Zoom ID') class Meta: model = User fields = ["username", "password1", "password2", "birthdate", "email", "discord_id", "zoom_id"] How would I use/link my existing Person model with this built in User -model? Or do I need a separate model in Models.py at all? Do I just create the User-model like above in the forms.py and add my custom fields into it? -
Django rest framework update if item exists
I have the following model: class Item(models.Model): itemID = models.IntegerField(unique=True) url = models.CharField(max_length=300) name = models.CharField(max_length=300) price = models.FloatField() and the following Serializer: class ItemSerializer(serializers.ModelSerializer): class Meta: model= Item fields = ('id','itemID','url','name','price') When posting an item that already exists I get the following message: {"itemID":["item with this itemID already exists."]} Instead, however, I would like to update all other fields if the item already exists. -
Django - For loop brings QuerySet but can't get individual data (as if blank) in HTML template
I have a django project. Some tables with some info already in place. I can't see the individual data when applying a FOR LOOP I revised the code. Looked it up and found no apparent mistake. Can anyone help me? Views.py: from django.shortcuts import render from .models import Client, Address main_title = 'Company Name' def home(request): client_list = Client.objects.all() address_list = Address.objects.all() contex = { 'address_list' : address_list, 'main_title' : main_title, 'client_list' : client_list, } return render(request, 'home.html', contex) in home.html {% for i in address_list %} <li>{{ i }}</li> {% endfor %} And all I see when going in the browser are the bullet points * * The source code in the browser is loading as: <ul> <li></li> <li></li> </ul> Now if i change the html code for something without a for loop like {{ address_list }} Then the browser shows: <QuerySet [<Address: THIS IS THE FIRST ADDRESS >, <Address: THIS IS THE SECOND ADDRESS >]> In other words. The database data is coming trough, But when inside a for loop i gets empty. But I know there are two entries. Because it show two bullet points -
Authentication with React and Django REST Framework
I want to add a React frontend to a website with Django backend. For this I used the Django REST framework. But how can I prevent people who are not logged in from sending a POST action to add an article? I want to run the whole frontend as a React app and not redirect to a React app after a successful login. -
Accessing files from custom directories to Django
I am fairly new to Django. Currently, I am making a Django 3.2 web server. Here is the concerned directory structure: https://i.stack.imgur.com/5LtJ6.png Problem I want to display the images in the generated folder in results.html. What should I do to make it so? I really am new, so any help would be appreciated. Thanks! -
NoReverseMatch at / in Django How to pass url
<a class="nav-link active" aria-current="page" href="{% url 'tasks' %}">Tasks</a> When I'm using this template tag I get an error no ReverseMatch. but , <a class="nav-link active" aria-current="page" href="/tasks">Tasks</a> When I'm doing this I get no error. Can someone explain me? urls.py of the project from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('tracker.urls')), path('tasks/', include('tasks.urls')), ] urls.py of the tasks app from django.urls import path from . import views urlpatterns = [ path('', views.tasklist, name="tasklist"), ] views.py of the tasks app from django.shortcuts import render def tasklist(request): return render(request, 'tasks/task_list.html') -
Async function in django that returns a json response
I want to create an async function in django to return a json response but every time a call the function from ajax call i get 500 error cooroutine has no attribute get from asgiref.sync import sync_to_async from django.core.serializers import serialize def _get_data(request): context = {} poi_ids = request.GET.getlist('poi_ids[]') if len(poi_ids)> 0: poi_list = serialize('geojson', Poi.objects.filter(id__in=poi_ids).distinct('name'), geometry_field='geom', fields=('name',)) context['poi_list'] = poi_list return JsonResponse(context) get_poi = sync_to_async(_get_data, thread_sensitive=True) -
Object of type XYZ is not JSON serializable
I'm working on a small project using Django and i'm getting an error : Object of type CustomUser is not JSON serializable This is my code : def sharedContact(self, connectedUser): contactList = [] contacts = ContactCenter.objects.filter(contact_source=connectedUser) | ContactCenter.objects.filter(shared_with=connectedUser) for contact in contacts: users = CustomUser.objects.filter(id=contact.contact_source_id) | CustomUser.objects.filter(id=contact.shared_with_id) for user in users: with schema_context(str(user.username)): tenant = Contact.objects.filter(id=contact.contact) for x in tenant: contactList.append(x) return contactList -
Django cannot save blank value in FloatField
I have a simple model in Django: class Test(models.Model): name = models.FloatField(default=0.0, blank=True) In my views.py, I am fetching user input from a page. The html code is: <form action="{% url 'test' %}" method="POST"> {% csrf_token %} <input type="number" placeholder="Test" class="form-control mb-2" name="test"> <input type="submit" class="btn btn-primary" value="Submit"> </form> The views.py code is: name = request.POST.get('test', '0.0') #I have tried without the '0.0' as well. new_test = Test(name=name) new_test.save() I keep getting the error: ValueError at /test Field 'name' expected a number but got ''. How can I make django save a blank value or '0.0'(default value) or a null value when the user enters nothing. It seems to accept none of these. -
Django form make field readonly depending on Boolean field
I have two fields in models.py: class Post(models.Model): urgency = models.BooleanField(default=False) date_days = models.IntegerField(default=20, validators=[MinValueValidator(5), MaxValueValidator(40)]) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) In my views.py I have: class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['urgency', 'date_days'] def clean_field_1(self): if self.instance.urgency: return self.instance.date_days else: return self.cleaned_data.get('date_days') def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) I would like to make field 'date_days' 'readonly' if 'urgency == True', and to enable back again if 'urgency == False'. User can toggle between True/False. -
Django--"Enter a valid date." Error During Update A Model
But when I restart the server using "runserver" command, it works only once, But when I try to edit the model again, it shows the error again. The DateTime field shows no error, same thing happening for all of my model in my project Django Version: Django-3.2.3 Python Version: 3.8 My Error Image of the err My Model from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.utils.timezone import now from products.models import Products from organizations.models import Persons, Companies ORDER_STATUS_CHOICES = [ ('Processing', 'Processing'), ('Confirmed', 'Confirmed'), ('Delivered', 'Delivered'), ] def increment_order_number(): last_order = Orders.objects.all().order_by('id').last() if not last_order: return 'FEO-0001' order_number = last_order.order_no order_int = int(order_number.split('FEO-')[-1]) new_order_int = order_int + 1 new_order_no = '' if new_order_int < 10: new_order_no = 'FEO-000' + str(new_order_int) if 100 > new_order_int >= 10: new_order_no = 'FEO-00' + str(new_order_int) if 100 <= new_order_int < 1000: new_order_no = 'FEO-0' + str(new_order_int) if new_order_int >= 1000: new_order_no = 'FEO-' + str(new_order_int) return new_order_no # model for order class Orders(models.Model): order_no = models.CharField(max_length=10, unique=True, default=increment_order_number) person_name = models.ForeignKey(Persons, on_delete=models.CASCADE, null=True) company_name = models.ForeignKey(Companies, on_delete=models.CASCADE, null=True) product_name = models.ForeignKey(Products, on_delete=models.CASCADE, null=True) total_weight = models.FloatField(max_length=10) rate_per_kg = models.FloatField(max_length=10) percentage_of_fotka = models.FloatField(max_length=10) percentage_of_moisture = models.FloatField(max_length=10) delivery_deadline = models.DateField(default=now) … -
Django REST: How to return 500 error from custom middleware instead of the KeyError: '...' if a cookie is missing in request?
I have a custom middleware where I check whether incoming requests have a cookie present or not. If the cookie is not present, then it shows KeyError:. [15/May/2021 18:00:05] "GET /api/auth/profile/ HTTP/1.1" 500 62653 Internal Server Error: / Traceback (most recent call last): File "F:\<dir>\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "F:\<dirs\to\middleware>\middleware.py", line 49, in __call__ myCookie = request.COOKIES['my_cookie'] KeyError: 'my_cookie' I want it to return only a 500 Internal Server Error if the cookie is not present. How do I do this? This is my middleware: class AuthMiddleware: def __init__(self, get_response=None): self.get_response = get_response def __call__(self, request): if request.path == '/api/auth/profile/': try: myCookie = request.COOKIES['my_cookie'] // do something with the cookie return self.get_response(request) except jwt.ExpiredSignatureError: // do something return self.get_response(request) Here, I only check whether the token has expired but I couldn't add mechanism to handle a KeyError. How do I do this? -
All my html code of my django project is displayed in orange in pycharm
i'm working on my django project with pycharm and I've a small problem. All my html files are displaying in orange like on the picture. Need help please -
How we can implement debit/credit card implementation in django?
Please guide me on how I can do that. Or If there any tutorials or websites please share them. Thanks. -
history field don't appear in the rst api?
https://django-simple-history.readthedocs.io/en/latest/quick_start.html I am using django simple history and it didn't goes well with me because it is not showing the history table (in form of json of course) and I make a GET request. So, how to use things like singals to record the change and save them by my self? class UsersSerializer(DynamicFieldsModelSerializer): class Meta: model = User fields = '__all__' class User(AbstractUser, PermissionsMixin): username = models.CharField( max_length=30, unique=True, validators=[USERNAME]) email = models.EmailField(max_length=250, unique=True) history = HistoricalRecords() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', ] class UserView(APIView): serializer_class = serializers.UsersSerializer def get(self, request, pk, format=None, ): user = User.objects.get(id=pk) serializer = serializers.UsersSerializer(user) return Response(serializer.data) the api returns this without the hstory field? { "id": 1, "username": "ali", "email": "change@update.com", "first_name": "ali", }