Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
username with `james i. adams` not accepted with django routers
I have registered routers for user model, which has viewset that has lookup_url as username. The username james adams is accepted by the router, but getting below error for james i. adams django.urls.exceptions.NoReverseMatch: Reverse for 'user-detail' with keyword arguments '{'username': 'james i. adam', 'version': 'v1'}' not found. 4 pattern(s) tried: ['(?P<version>(v4))/users/(?P<username>[^/.]+)/?\\.(?P<format>[a-z0-9]+)/?$', '(?P<version>(v4))/users/(?P<username>[^/.]+)/?$', '(?P<version>(v1))/users/(?P<username>[^/.]+)/?\\.(?P<format>[a-z0-9]+)/?$', '(?P<version>(v1))/users/(?P<username>[^/.]+)/?$'] Can someone guide me, how can I allow such username for url patterns with routers registered? Thanks in Advance -
How to Filter foreign key related models using datetime range
I'm trying to create a reservation system and I want to query all available tables. So, what I did is as follows, ... date_time = request.data.get('date_time') date_time = datetime.strptime(date_time, '%b %d %Y %I:%M%p') num_of_attendees = request.data.get('num_of_attendees') tables = Table.objects.filter(~Q( tablereservation__date_time__range=[date_time, date_time + timedelta(hours=2)]), num_of_chairs__gte=num_of_attendees ) ... But it returns all the table objects. My models, class Table(models.Model): """ Holds table details """ num_of_chairs = models.PositiveSmallIntegerField(default=1) def __str__(self): return str(self.id) class TableReservation(models.Model): """ Holds table reservation details """ date_time = models.DateTimeField() table = models.ForeignKey(Table, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return '{}-{}'.format(self.table, self.user) But I want is to get only the table objects that aren't reserved in the given date-time range. Any help is greatly appreciated. -
Django-Import-Export assign Field to specific column
I have a working form which exports all data to xls using Resource and Fields from the django-import-export package. But now I need to go a bit further and make it a bit more advanced. I need to export all data to an existing Excel template, assigning each field to a specific column, as in, for instance: Field 1 needs to be filled in B3, Field 2 in C4 etc. etc. I'm thinking after_export() can be used here but the docs dont go into detail how to use this method. Does anyone have some experience with this package? I'm not using the admin integration. -
ListCreateAPIView is not letting post data
I'm trying to create an API where I will upload image throw API end point, My Model has only one imageField. Please checkout the code below Model: class Image(models.Model): image = models.ImageField(upload_to="media", default="default.png", blank=True, null=True) def __str__(self): id = self.id return f'image-{id}' Serializer: class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = ['image'] Views: from rest_framework.generics import CreateAPIView, ListCreateAPIView from home.models import Image from .serializers import ImageSerializer class ImageListCreateView(ListCreateAPIView): queryset = Image.objects.all() serializer_class = ImageSerializer Urls: from django.urls import path from .views import ImageListCreateView urlpatterns = [ path('image/', ImageListCreateView.as_view(), name='image'), ] But if I visit the url '127.0.0.1:8000/api/image/' It only shows the data. not letting me post new data. -
How to integrate django to Elastic App Search
I have doing a project of e-commerce and I need to integrate Django and Elastic App Search. How to integrate -
django many to many queriying
I am building an e-commerce website using Django, my models is like bellow : class ProductAttribute(models.Model): product=models.ForeignKey(Product,on_delete=models.CASCADE) attributes_values = models.ManyToManyField(AttributeValue,verbose_name="Liste des attributs") stock = models.PositiveIntegerField() price = models.PositiveIntegerField(verbose_name="Prix") image = models.ImageField(blank=True,null=True,upload_to="products") class AttributeValue(models.Model): attribute=models.ForeignKey(Attribute,on_delete=models.CASCADE,verbose_name="Attribut") value = models.CharField(max_length=50,verbose_name="Valeur") class Attribute(models.Model): name = models.CharField(max_length=50,verbose_name="Nom") my view.py def getatts(request,product_id): products_with_attributes=ProductAttribute.objects.filter(product__id=product_id) res=#..... missing code to get attributes with values return res In the front end i want to retrieve attributes of a particular product to get them by order, to use them in select (ex:size,color choices) , for example if the query set of ProductAttribute is like: [{id:1,product:1,attributes_values:[3,4],...},{id:1,product:1,attributes_values:[5,6],...}] the result in JSON would be like so: { result:[ { key: "color", values: [ {id: 1, value: "Red", choices:{ key:"size", values:[{id:3,value:"L"},{id:4,value:"XL"}] } }, {id: 2, value: "Black", choices:{ key:"size", values:[{id:5,value:"M"},{id:6,value:"XXL"}] } }, ] } ] } -
Problem while trying to create dynamic html
Why don't I get the dynamic text that used in the views.py? My views.py code: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): context = { 'name' : 'Amlan', 'age' : 23, 'nationality' : 'Indian' } return render(request, 'index.html', context) My index.html code: <h1> Hello {{name}}<br>You are {{age}} years old<br>You are {{nationality}} </h1> When I run the server I get: Hello You are years old You are -
DRF - from django.conf.urls import url in Django 4.0
I've a project in django 3.2 and I've updated (pip install -r requirements.txt) to version 4.0 (new release) and I've currently the below error when I run the server in a virtual environment. I use DRF. Can't import => from rest_framework import routers in urls.py from django.conf.urls import url ImportError: cannot import name 'url' from 'django.conf.urls' -
Disable querying a field in Django Rest Framework
Here is the model class. Where categories is a nested mptt model tree. class MyModel(models.Model): categories = models.ManyToManyField(Category) # to another nested model (self referncing tree) The serialzier is a simple one class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel exclude = ['categories', ] When serializing the Model object, on sql queries are executed to fetch categories. I dont want the categories field in the response, so I excluded it in the serializer but the categories table is queried when serializing. serializer = MyModelSerializer(MyModel.objects.first()) How can I disable queries to that table when doing this particular operation? Thanks. -
Applying date filter on a char-field that stores the date-time in string in django?
I have this field on a model X: class Details(models.Model): start_time = models.CharField(max_length=25, null=True, blank=True) Now, one problem arises that I need to apply the date filter on this. is there any way to solve this. I want to do something like this Details.objects.filter(start_time__time=some_time) -
How to return back to the same page when we use user_passes_test decorator in Django
When I sign in or log in to my account, I do not want to go back to the login page or registration page by giving the URL in the address bar. What I want is to stay on the same page even after giving the registration or login page URL. For that, I have used the user_passes_test decorator in the views.py file. Also, I set login_url in the user_passes_test decorator as return redirect(request.META['HTTP_REFERER']). At that time I got a Page not found (404) error. views.py from django.contrib.auth.decorators import user_passes_test @user_passes_test(user_is_not_logged_in, login_url="return redirect(request.META['HTTP_REFERER'])", redirect_field_name=None) def register(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: form = UserForm() return render(request, 'register.html', {'form': form}) Can anyone suggest a solution to solve this issue? -
style.css file is not working nor any error message is displaying in terminal in django
I have looked around on this site as well as others and still have not found a solution that works for why django is not loading my css file even not showing any error in terminal even in debug console. my settings.py file: STATIC_URL = 'static/' my html file: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}" /> My file tree: App -static -css -style.css -templates -index.html INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'App', ] Any help would be greatly appreciated. I tried using the STATIC_ROOT as shown on a different thread but there was no change with that. -
Database data is not updating on my apache2 website unless I restart apache2 service
I have Django installed and am using Apache2 to host the website (using WSGI). I have checkboxes on my website and when I click a checkbox and then click submit it saves the change to the SQLite3 database and refreshes my website. If I log out of my website and then back in the checkbox is no longer clicked but the related database item is showing TRUE in the Django admin site. If I restart Apache2 using "sudo service apache2 restart" and refresh the website it then has the proper boxes checked. I am brand new to Django/Apache2 so I apologize if this is a stupid mistake, but restarting apache2 every time I make a change seems wrong. my views.py from django.shortcuts import render from django.http import HttpResponse from .models import RelayList from .forms import RelayControl from django.contrib.auth.decorators import login_required # Create your views here. @login_required def index(response): curList = RelayList.objects.get(id=1) #retrieves the database object and places it into a variable if response.method == "POST": form = RelayControl(response.POST) if form.is_valid(): curList.relay1 = form.cleaned_data["relay1"] curList.relay2 = form.cleaned_data["relay2"] curList.relay3 = form.cleaned_data["relay3"] curList.save() else: form = RelayControl() # creates an instance of the for defined in class RelayControl in forms.py #return HttpResponse('<h1>Hello World, … -
How can I render a Django Formset with some data for update process?
I am using Dajngo formset with inlineformset_factory What I need it when the user click in the update like It should render formset with the value. This is the code I did but nothing works: This is how I create a formset OrderItemFormset = inlineformset_factory( Order, OrderItem, fields='__all__', extra=1, can_delete=False) And here how I tried to render the formset with the queryset=my_query_set. if 'id' in kwargs.keys(): order = Order.objects.get(id=kwargs.get('id')) order_items = OrderItem.objects.filter(order_id=kwargs.get('id')) else: order = None order_items = None order_form = OrderForm(instance=order) print(order_items) order_item_form = OrderItemFormset(queryset=order_items) When I click in the update link Django render the Parent form with the data I need, but this does not work with formset it just give me one row with empty data. -
TemplateDoesNotExist at /product/1/ productDetail.html
I am making an about page for every item. There is a problem that occurred when I am pressing 'View' on my store page: TemplateDoesNotExist at /product/1/ productDetail.html I have tried specifying the directory by putting {{% extends store/main.html %}}, it did not help. Please assist me. store/views.py from django.shortcuts import render, redirect from django.http import JsonResponse import json import datetime from django.urls import reverse from .forms import CommentForm from .models import * from .utils import cookieCart, cartData, guestOrder def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() context = {'products': products, 'cartItems': cartItems} return render(request, 'store/store.html', context) def cart(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items': items, 'order': order, 'cartItems': cartItems} return render(request, 'store/cart.html', context) def checkout(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items': items, 'order': order, 'cartItems': cartItems} return render(request, 'store/checkout.html', context) def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('Product:', productId) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + 1) elif action … -
Django admin login page redirects to same page on login credentials
i hosted Django app in AWS sever properly and there no error in server. after login from Django admin login page redirects to same page on correct login credentials. but it works on local server. 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', # 'debug_toolbar.middleware.DebugToolbarMiddleware', # AxesMiddleware should be the last middleware in the MIDDLEWARE list. # It only formats user lockout messages and renders Axes lockout responses # on failed user authentication attempts from login views. # If you do not want Axes to override the authentication response # you can skip installing the middleware and use your own views. 'axes.middleware.AxesMiddleware', ] AUTHENTICATION_BACKENDS = [ # AxesBackend should be the first backend in the AUTHENTICATION_BACKENDS list. 'axes.backends.AxesBackend', # Django ModelBackend is the default authentication backend. 'django.contrib.auth.backends.ModelBackend', ] can anyone help me??? -
Deploy React and Django, same domain but different sub-domains, while on the same server
I am building a React js Application with the Django backend. with API integration I have one server and 1 Domain, and using nginx I suppose to do Run my React app on www.my-domain.com and Django backend on services-api.my-domain.com which scenario should I choose? Should I go with 2 Different Domains and Different servers? or I can do on this way what I discussed above & guide me how I can do this. How i can setup React and Django on the same server with same domain but in different sub-domain -
How to solve TypeError: Object of type HttpResponse is not JSON serializable?
I am trying to return a model.pkl file using postman from an API made in django rest framework. However the response I get is TypeError: Object of type HttpResponse is not JSON serializable. The following code is what I am using to return the file, but I cannot understand what is going wrong (this was inspired by this post). from rest_framework.status import HTTP_200_OK import pickle from django.http import HttpResponse from wsgiref.util import FileWrapper # views.py ... model_pickle_path = f'/path/model_state.pkl' #model_pickle_trained = pickle.load(open(model_pickle_path, 'rb')) model_pickle_trained = open(model_pickle_path, 'rb') response = HttpResponse(FileWrapper(model_pickle_trained), content_type='application/octet-stream') response['Content-Disposition'] = 'attachment; filename=%s' % model_filename_defined return Response(data=response, status=HTTP_200_OK) Traceback: TypeError: Object of type HttpResponse is not JSON serializable -
Get MIME type of file that is in memory - Python Django
I have a form where users can upload files. I only want them to be able to upload images. I have added that in the HTML form but need to do a server side check. I would like to do this check before I save the file to AWS S3. Currently I have this: from .models import cropSession, cropSessionPhoto import magic def crop(request): if request.method == 'POST': data = request.POST images = request.FILES.getlist('photos') crop_style = data['style'] if len(images) <= 0: messages.error(request, "At least one photo must be uploaded.") return redirect(reverse('crop-form')) crop_session = cropSession(crop_style=crop_style) crop_session.save() for image in images: mime = magic.Magic(mime=True) mime.from_file(image.file) upload = cropSessionPhoto(crop_session=crop_session, photo_file_name=image, photo_file_location=image) upload.save() else: messages.error(request, "An error has occured.") return redirect(reverse('crop-form')) return render(request, 'crop/crop.html') However, I get this error: TypeError: expected str, bytes or os.PathLike object, not BytesIO How do I properly pass the image to magic? Thank you -
Why fetch does not include credentials everytime with option {credentials: "include"}?
I have been trying to fetch data from my djangorestframework api verifying through cookies. Before reaching to the main problem, My computer IP on LAN: 192.168.1.50 Running localhost at port 80: 127.0.0.1 Running django at port 8000: 192.168.1.50:8000 - (tried vice versa as well: 127.0.0.1:8000) Now, assuming my django is running on 192.168.1.50:8000, I figured out that if I send fetch request to djangorestframework from 192.168.1.50 the cookies are attached with the request. Django's settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', "corsheaders", 'users', ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", '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', ] CSRF_COOKIE_SAMESITE = None SESSION_COOKIE_SAMESITE = None CSRF_COOKIE_HTTPONLY = True SESSION_COOKIE_HTTPONLY = True CORS_ALLOWED_ORIGINS = [ "http://192.168.1.50", "http://127.0.0.1", ] CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with", ] Fetch method from JS, fetch("http://192.168.1.50:8000/user/auth/", { method: "GET", credentials: "include", headers: { 'Content-Type': 'application/json', }, }).then(r => { console.log(r.json()); }) Sending request from 192.168.1.50, From 192.168.1.50's (from chrome browser), Response Header: Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: http://192.168.1.50 Allow: OPTIONS, GET Content-Length: 5 Content-Type: application/json Cross-Origin-Opener-Policy: same-origin Date: Wed, 15 Dec 2021 #:#:# GMT Referrer-Policy: same-origin Server: WSGIServer/0.2 CPython/3.8.10 Vary: Accept, Cookie, Origin X-Content-Type-Options: nosniff X-Frame-Options: DENY Request Header: … -
How to serialize json to sql?
I have a list of words and I should send requests to an API and get the information about the words. I want to convert the API data which is in JSON format to SQL(my DB is PostgreSQL) format in Django. How can I do that? Do you know any good source to learn to serialize json to sql? I have just started learning Django. It is the API's JSON data: [ { "word": "hello", "phonetics": [ { "text": "/həˈloʊ/", "audio": "https://lex-audio.useremarkable.com/mp3/hello_us_1_rr.mp3" }, { "text": "/hɛˈloʊ/", "audio": "https://lex-audio.useremarkable.com/mp3/hello_us_2_rr.mp3" } ], "meanings": [ { "partOfSpeech": "exclamation", "definitions": [ { "definition": "Used as a greeting or to begin a phone conversation.", "example": "hello there, Katie!" } ] }, { "partOfSpeech": "noun", "definitions": [ { "definition": "An utterance of “hello”; a greeting.", "example": "she was getting polite nods and hellos from people", "synonyms": [ "greeting", "welcome", "salutation", "saluting", "hailing", "address", "hello", "hallo" ] } ] }, { "partOfSpeech": "intransitive verb", "definitions": [ { "definition": "Say or shout “hello”; greet someone.", "example": "I pressed the phone button and helloed" } ] } ] } ] this is my models.py: class Words(models.Model): word = models.CharField(max_length=50) american_phonetic= models.CharField(max_length=50) american_audio= models.URLField(max_length = 200) british_phonetic= models.CharField(max_length=50) british_audio= models.URLField(max_length … -
Django resets user permissions
I am building a site using React for the frontend and Django for the backend. The login page sends a request to this view function when the login button is pressed. @api_view(['POST']) def api_authenticate_login_view(request): body = request.data username = body['username'] password = body['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) content = {"authenticated": True} return Response(content) else: content = {"authenticated": False} return Response(content) When trying to access any other page in the site, a request is first sent to this view function to make sure the user is logged in @api_view(['GET']) def api_is_authenticated_view(request): if request.user.is_authenticated: content = {"authenticated": True} return Response(content) else: content = {"authenticated": False} return Response(content) If it returns false they are redirected to the login page. The issue is that this works great for most of our users, but for a select few, their user permissions in the provided Django admin page are constantly reset. What I mean by that is, in the user section of the Django admin page, you can select a user and see their permissions. On our page this shows a tick box next to the tags Active, Staff status, Superuser, and others(see image link below) Django user … -
Django using Aws S3 bucket to get static files
url.com/:9 GET https://<AWS_STORAGE_BUCKET_NAME>.s3.amazonaws.com/static/user/main.css net::ERR_ABORTED 403 (Forbidden) url.com is the actual site and AWS_STORAGE_BUCKET_NAME is the bucket name When I try to retrieve my S3 file from my base.html I get a 403 forbidden error in the console. <link rel="stylesheet" href="{% static 'user/main.css' %}" type="text/css"> Settings.py # All of this is in my console.aws.amazon to configure aws s3 static files only # IAM Management Console AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') # Amazon S3 Buckets AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'pages/static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) # For some reason I needed static root to collectstatistics # STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage ' -
ValueError at /login invalid salt
I am creating a django app and have run in to a problem with the login portion of it. Everything seems to be working fine but when I login in with the stored information I receive the ValueError with invalid salt. I've looked on here for solutions but nothing seems to be doing the trick. I tried using the encode('utf-8) solution but that doesn't work either. def login(request): if request.method != 'POST': return redirect('/') user = User.objects.filter(email = request.POST.get('email')).first() if user and bcrypt.checkpw(request.POST.get('password').encode(), user.password.encode()): request.session['user_id'] = user.id return redirect('/quotes') else: messages.add_message(request, messages.INFO, 'invalid credentials', extra_tags="login") return redirect('/') return redirect('/quotes') The issue seems to stem around the if user and bcrypt.checkpw() but I don't know what to do different? -
Django overriding filter() without change existing code logic
I have a table in production that is integrated everywhere in the system, now I need to make add a new column in the table with a default value, but don't want to change all the existing logic, what is the best to do that? class People(models.Model): name = models.CharField(max_length=20) gender = models.CharField(max_length=20) class = models.CharField(max_length=20) in the system, we have this kind of queries everywhere People.objects.filter(gender='male') People.objects.filter(gender='female', class="3rd") ... Now we need to add a new field: class People(models.Model): name = models.CharField(max_length=20) gender = models.CharField(max_length=20) class = models.CharField(max_length=20) graduated = models.BooleanField(default=False) Assume that all the existing data should have graduated is False, so all the existing should work if we can add graduated=False, but is there any way we can do so we don't need to change any of the existing code but they will assume graduated=False?