Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: Object of type 'Product' is not JSON serializable
I am creating a store which can handle shopping without any registration, but i have some problems. I am storing data about products that user added to basket in django sessions and i am trying to create the similar system which would store a orders which user has done. This is the view which is executed after all payments are done: #I am not pasting the imports, all fine with them basket = Basket(request) orders = Orders(request) ### We are looping through the all items we are storing in basket to create for each one, single order for basketitem in basket: #This order is automatically created for admin, just ignore it, it's working fine order = Order.objects.create(user_id=user_id, product=basketitem['product'], size=basketitem['size'], quantity=basketitem['quantity'], full_name=full_name, address1=address1, address2=address2, postcode=postcode, town=town, country=country, total_paid=baskettotal, order_key=order_key, authenticated=False) #This is the main problem, this is trying to get a product from database "Product" comparing id from database to id that we store in basket in django sessions product = get_object_or_404( Product, id=int(basketitem['productid'])) orders.add(product=product, quantity=basketitem['quantity'], size=basketitem['size'], full_name=full_name, address1=address1, address2=address2, postcode=postcode, town=town, country=country, created=now.strftime("%d/%m/%Y %H:%M:%S")) And after this occurs error "Object of type 'Product' is not JSON serializable" Basket.py class Basket(): def __init__(self, request): self.session = request.session basket = self.session.get('bt') if … -
How do I pass a search query to a Django backend without storing the search results in a database?
My goal is to post a search query to a scraper function in a Django Rest Framework backend and return the results to the frontend without storing the results in a database. Currently, I can pass a search a search from the frontend to the backend, but the search results are stored in the database. Here are my Django Model and Views file that show how it is structured: models.py from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Data(models.Model): created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) data_1 = models.TextField(blank=True) data_2 = models.TextField(blank=True) search = models.CharField(max_length=255, default='') views.py from rest_framework import viewsets from apps.data.models import Data from apps.data.serializers import DataSerializer from apps.search.util import scraper class DataViewSet(viewsets.ModelViewSet): serializer_class = DataSerializer queryset = Data.objects.all() def perform_create(self, serializer): print(scraper(self.request.data['search'])) data_1 = scraper(self.request.data['search']) data_2 = scraper(self.request.data['search']) serializer.save(created_by=self.request.user, data_1 = data_1, data_2 = data_2) def get_queryset(self): return self.queryset.filter(created_by=self.request.user) How would I structure this Django backend application to pass a search query through my scraper without storing the result in the database? -
Serving Static on AWS - Django - Python
I have all of my static images served locally on my Django website project. I need them to be hosted on AWS for my DEBUG = False to work. I have followed many tutorials on how to do this and have had no luck. I have posted my code below for a last-ditch effort hoping that it is just something I have missed. I have my AWS bucket currently as public because that's what I have seen others doing. Any help is greatly appreciated. Thanks! setings.py AWS_ACCESS_KEY_ID = 'hidden for privacy' AWS_SECRET_ACCESS_KEY = 'hidden for privacy' AWS_STORAGE_BUCKET_NAME = 'hidden for privacy' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Caracas' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) #STATIC_ROOT = os.path.join(BASE_DIR, 'static') #MEDIA_URL = '/images/' #MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, '..','www','media') HTML {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link rel="shortcut icon" type="image/x-icon" href="{% static 'tab_icon.ico' %}"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{% static "css/side.css" %}"> <link rel="stylesheet" href="{% static "css/style.css" … -
Django uploads to the database, using the one to many relation
I'm a beginner in Django trying to give a customer his command. Please I need help on a views.py and models.py for my app, which is intended to submit a picture, several documents, and a name for a customer's information. These documents include certificates and some scans! -
Django Admin Panel - How to Create a DateTime String
For Django, I have this in my model: date = models.DateTimeField() the widget for this is AdminSplitDateTime in the Admin Panel. It then displays a graphical widget that shows the date and time, and allows you to pick today or now. What I want to do instead is just display the date time as a string, as such: Date: 08/26/2021 04:46:11 PM I just want to display the date/time as text rather than a fancy widget... I spent time trying to figure this out, but I am stuck. Do you guys have any idea on how to implement this in Django? Thanks! -
Is it possible to create two different submit button in one form in Django?
So I'm working on my Django project and ran into an issue. I have a custom ModelForm, with which I'm trying two different works. I'm trying to create two submit buttons for the form, one for normal submission, and the other for making changes to the input data and then submitting. For Example, let's say I have name field in my form. If the user clicks button A, name is submitted. But if the user clicks button B, I want the name field to be submitted as name@gmail.com. Is it possible to have two buttons working differently in one Django form? Thanks in advance. -
'django_1 | no port[s] to connect to' after running docker-compose up
I am new to docker, and have written a containerized django app, and react app. When I go to run docker-compose up I get a weird, perpetuating error that django has no port(s) to connect to. Running the server from the react and python side both work. Frontend dockerfile: COPY ./react_app/package.json . RUN apk add --no-cache --virtual .gyp \ python \ make \ g++ \ && npm install \ && apk del .gyp COPY ./react_app . ARG API_SERVER ENV REACT_APP_API_SERVER=${API_SERVER} RUN REACT_APP_API_SERVER=${API_SERVER} \ npm run build WORKDIR /usr/src/app RUN npm install -g serve COPY --from=builder /usr/src/app/build ./build Django Python backend Dockerfile WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt FROM python:3.7.9-slim-stretch RUN apt-get update && apt-get install -y --no-install-recommends netcat && \ apt-get autoremove -y && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* COPY --from=builder /usr/src/app/wheels /wheels COPY --from=builder /usr/src/app/requirements.txt . RUN pip install --no-cache /wheels/* WORKDIR /usr/src/app COPY ./entrypoint.sh /usr/src/app/entrypoint.sh COPY ./django_app . RUN chmod +x /usr/src/app/entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] and the nginx dockerfile FROM nginx:1.19.0-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d WORKDIR /usr/src/app Django Python backend Dockerfile WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY … -
Django Blog - I can't add new comment
Problem with a comment system in my Django project. When I add a new comment in 127.0.0.1:8000 or localhost:8000 the page just reloads and nothing happens. In "blog/views.py" in post_detail(request, year, month, day, slug): I guess there is something wrong at if request.method == 'POST': and then move on to else: comment_form = CommentForm() so that I can only see the page just reloads. However, I don't know how to fix it... This is a full code of my Django project. my github repository -
How to load django model rows in a list?
I have a django model that I am basically quering on keypress using ajax to find possible matches cause I am avoiding duplicated rows. Now my question is how can I copy all the rows from a django model and query on it rather than hitting the database everytime the user presses a key because I do not think this is a good idea and please correct me if I am wrong. What are the consequences of hitting a database on keypress? -
Unable to see error messages in registration template. Django
Good afternoon Community, I hope you are all well. I am building my first website and I have the following problem; when I try to create a new user, if the user enters the wrong data the template does not show the error. Any hints? Template: <form action= "" method='post'> {% csrf_token %} {% for field in form %} <p>{{field.label}}{{field}}</p> {% endfor %} <button type="submit" class="btn btn-success">Create User</button> Views.py: def register_page(request): form = UserForm if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('http://127.0.0.1:8000/login_user/') context = {'form' : form} return render(request, 'simple_investing/register.htm', context) Forms.py: class UserForm(UserCreationForm): class Meta: model = User fields = ('username', 'email', 'password1', 'password2') -
Sessions and user id django
I have a form that can be submitted by any user, anonymous included. I want to save the user id (can be randomly generated) into my database that's associated with their input. I want to keep track of which input came from the same/different user. Essentially, if I have a new session, I would generate a new user_id. However, if this is an old session, I would save into the database the old/same user_id. However, I am a total newbie to Django, so I'm not sure how to implement this. So, my database should look something like this where the input values from the same user has the same user_id. |id| user_id | Order | |1 | ---------------------------------- | -------------- | |2 | f205f606c6764a79a77e5495b9d740bc | 10 | |3 | f205f606c6764a79a77e5495b9d740bc | 5 | |4 | f205f606c6764a79a77e5495b9d740bc | 10 | |5 | f205f606c6764a79a77e5495b9d740bc | 3 | |6 | fee472e3b07c4f59834e22751d9d2d60 | 2 | |7 | fee472e3b07c4f59834e22751d9d2d60 | 6 | -
how to make custom creation method [Django models]
class Boat(models.Model): name = models.CharField(max_length=100) quantity = models.DecimalField(max_digits=8, decimal_places=2) fish_type = models.CharField(max_length=50, choices=FISH_TYPE) class Load(models.Model): boat = models.ForeignKey(Boat, on_delete=models.CASCADE) delivery_date = models.DateTimeField(auto_now_add=True) class OrderLoad(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) quantity = models.DecimalField(max_digits=8, decimal_places=2) fish_type = models.CharField(max_length=50, choices=FISH_TYPE) what I want to do is, when orderload instance created, it should reduce the quantity. -
Django Review / Optimization / Recommendations
I have been learning Django over the last couple of weeks and have been working on some projects as practice and to learn real world applications. I have pages (pictured below) that show a list of students, and teachers assigned to those students, on these pages I have a number of forms to do different things such as selecting students, creating new students, editing the student, assigning a teacher etc. I have attached my code below, this all works fine, but I can't help but feel like this is an extremely inefficient way of doing it. Keen to hear people's thoughts and feedback. I am always keen to learn! Students Screen (Ignore the red squares, just covering school names and logos): View.py @login_required(login_url='/login/') def students(request): if request.method == "POST": ## Checks which form is submitted, and actions the correct form if 'new_student' in request.POST: student_queryset = Student.objects.all().filter(creationuser__userschool=request.user.userschool) all_teachers_queryset = Teacher.objects.all().filter(creationuser__userschool=request.user.userschool) teacher_queryset = '' search_term = "" view_state = '' new_teacher_state = '' form = StudentForm(request.POST) if form.is_valid(): save_form = form.save(commit=False) save_form.creationuser = request.user save_form.save() save_form = StudentForm() if 'new_teacher' in request.POST: student_queryset = Student.objects.all().filter(creationuser__userschool=request.user.userschool) all_teachers_queryset = Teacher.objects.all().filter(creationuser__userschool=request.user.userschool) teacher_queryset = '' search_term = "" view_state = '' new_teacher_state = '' form … -
'HitCountDetailView' object has no attribute 'category'
I am trying to add extra context which does filtering to my DetailView. It throws the error that the view object has no attribute category model class Post(models.Model): title = models.CharField(max_length=200) category = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True, blank=True) slug = models.SlugField(max_length=100, unique=True, editable=True) view.py class HitCountDetailView(HitCountDetailView): model = Post template_name = 'detail.html' context_object_name = 'post' slug_field = 'slug' count_hit = True def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['similar_posts'] = Post.objects.filter(category=self.category).exclude(slug=self.slug) return context **urls.py** ```python path('detail/<slug>/', HitCountDetailView.as_view(), name='post-detail') -
Django Tutorial Page Not Found
I have been following along with the Django tutorial for the poll app. I keep getting a 404 error when heading to the site. I have checked quite a few questions for this problem but I wasn't able to find a solution ''' Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^polls/ ^admin/ The empty path didn’t match any of these. ''' my code is as follows mysite\urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] polls\urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index') ] views: from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") -
Django: How to control permissions based on a complex query
I am creating an application using the django rest_framework. I have the following models: Employee (Many to one relationship to Project) Project (Many to one relationship to Manager) Manager The Manager should be able to see all Employees that are not currently assigned to a project, or that are assigned to a project that the Manager is managing. (There can be other managers that assign an employee to their own project, and then other managers can't see them). These are the libraries that I am using: asgiref==3.4.1 Django==3.2.6 django-filter==2.4.0 django-rest-framework==0.1.0 djangorestframework==3.12.4 pytz==2021.1 sqlparse==0.4.1 I'm imagining something like this: class Employee(models.Model): name = models.CharField() assignment = models.ForeignKey('Project', on_delete=models.SET_NULL, null=True, blank=True, related_name='assigned_to_project') class Project(models.Model): name = models.CharField() owner = models.ForeignKey('Manager', on_delete=models.SET_NULL, null=True, blank=True, related_name='managed_by') class Manager(models.Model): name = models.CharField() As far as permissions, I imagine a custom permission on the employee which is something like: def has_permission(self, request, obj=None): if obj: if obj.assignment is not None: """ Start sudo-code - Use the value saved in obj.assignment (for example the PrimaryKey of the project it is assigned to) - Follow that PK to the project table, and look to see if obj.owner is not None. - If it isn't None, take the PK … -
The difference between <str:slug> and <slug:slug> in urls.py of Django application
Why in some cases in urls.py is used str:slug, and in other cases slug:slug? What is the difference? And which option is better to use? And can I use a category slug and then an article slug in one route? -
How to handle form with multiple checkboxes with different values, the same names in django?
I have a problem with handling a form with multiple checkboxes with different values, but the same names using django. HTML: <form name="form1" method="post" id="formToCheck"> {% csrf_token %} <div class="row form-group"> {% for icon in icons_to_show %} <div class="col-md-{{ number }}"> <div class="center"> <i class="large material-icons" style="color: darkslategray">{{ icon }}</i> <p>{{ icon }}</p> <label for={{ icon }}> <input type="checkbox" name="display_type" value="{{ icon }}" id={{ icon }}/> <span>Choose</span> </label> </div> </div> {% endfor %} <button type="submit" class="btn btn-primary blue" style="text-align: center; align-items: center">Submit </button> </div> </form> models.py class MemoryResult(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now=True, null=True) picked_imges_names = models.CharField(max_length=255, null=True) results = models.FloatField(null=True) status = models.CharField(max_length=255, null=True) def __str__(self): return '{}'.format(self.images_names) @receiver(post_save, sender=User) def create_memory_results(sender, instance, created, **kwargs): if created: MemoryResult.objects.create(user=instance) views.py class MemoryImagesView(TemplateView): template_name = 'accounts/memory.html' icon_to_show = [] def dispatch(self, request, *args, **kwargs): previous_images = self.request.user.memoryimage_set.all().last().images_names.strip("[]'").replace("'", "").replace( " ", "").split(",") how_many = 9 - len(previous_images) self.icon_to_show = render_icons(how_many) + previous_images response = super(MemoryImagesView, self).dispatch(request, *args, **kwargs) return response def get_context_data(self, **kwargs): context = super(MemoryImagesView, self).get_context_data(**kwargs) return context def get(self, request): memory = MemoryResult.objects.filter(user=request.user) frontend = { 'title': 'Memory Results', 'number_mem': 'abcdefghi', 'icons_to_show': self.icon_to_show, 'number': 4, 'memory': memory } return render(request, 'accounts/memory.html', frontend) def post(self, request): picked_icons = … -
how to do sorting of item after completing the search
i have search field i want to give user sorting option so user can do sorting luke price low to high to low in the search result but unable to achieve that my view class search_item(View): def get(self, request): search_item = request.GET.get('search') if search_item: items = Item.objects.filter(Q(name__icontains=search_item)|Q(color__icontains=search_item)) sort_by = request.GET.get("sort", "l2h") if sort_by == "l2h": item = items.order_by("price") elif sort_by == "h2l": item = items.order_by("-price") return render(request, 'search_result.html', {'items':item}) it does the search but unable to do sorting what wrong in my code -
Extra context is no passed to /accounts/login in django 3
I want to pass some configurable data to the login template and all other account template. Currently, I am trying it like this: # urls.py path('accounts/', include('django.contrib.auth.urls'), {'extra_context': {'home_title': settings.HOME_TITLE, 'domain': settings.HOSTNAME}}), However, the data is not picked up by the template. And those variable remain empty strings. Is there a better way to do this? For other pages I am passing the data in the views like this: #views.py def home(request): context = {'home_title': conf_settings.HOME_TITLE} return render(request, 'home.html', context) -
404 Not Found, Nginx config
I just started using Django and I try to deploy my project on the digital ocean server using Nginx. I am trying to set up SSL and domain (and they look good through the SSL checker and Google Dig DNS), however I get the 404 error in the browser once I try to access the webpage: 404 Not Found nginx/1.14.0 (Ubuntu) I have been trying different things with Nginx config but it does not seem to help, here is what I have now: http { ... server { listen 443; ssl on; ssl_certificate /etc/ssl/server_merged_key.crt; ssl_certificate_key /etc/ssl/other_key.key; root /home/mysite1/mysite; server_name domain.net www.domain.net ; location / { root /home/mysite1/mysite/; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $http_host; proxy_redirect off; } ... } The Django project is located on the home of the server with no directory (just two folders /mysite1/mysite/). The server starts fine. I do not see any GET request on the server side once I see the 404 error on the page. I do see the 400 error You're accessing the development server over HTTPS, but it only supports HTTP., if I try to access through http://IP-IN-NUMBER:8000. Also, the settings.py looks like this, if this relevant to the issue: … -
capture variables with js without saving it in the database
hello I hope you can help me I try to have the size and color variables with the js without going through the database as I did with the price here is the code snippet that I think is necessary html <table class="table table-bordered"> <tr> <th>Colors</th> <td> {% for color in colors %} <button class="btn btn-lg choose-color" data-color="{{color.color__id}}" style="background-color: {{color.color__color_code}}"></button> {% endfor %} </td> </tr> <tr> <th>Sizes</th> <td> {% for size in sizes %} <button data-price="{{size.price}}" class="btn btn-outline-secondary btn-sm choose-size color{{size.color__id}}">{{size.size__title}}</button> {% endfor %} </td> </tr> <tr> <th>Price</th> <th> <span class="product-price">{{data.productattribute_set.first.price}}</span></th> </tr> </table> <hr/> <div class="input-group my-3" style="width:30%;"> <input type="number" value="1" class="form-control" id="productQty" /> <div class="input-group-append"> <input type="hidden" class="product-id" value="{{data.id}}" /> <button> Add to Cart</button> js $(document).on('click',"#addToCartBtn",function(){ var _vm=$(this); var _qty=$("#productQty").val(); var _productPrice=$(".product-price").text(); // Ajax $.ajax({ url:'/add-to-cart', data:{ 'qty':_qty, 'price':_productPrice, }, -
Change the edit url, dynamically using the Datatable Editor
I'm looking on how to update the ajax configuration dynamically using data from a resource when updating a record. Django REST expects the id at the end of the url and the request method must be type PUT -
django database performane separate tables vs GenericRelation
hello i hope you doing well let us say i have 2 models, say A and B and the third is named order .On side of database performance Which way is better?(when the fileds of order is common) one or two . In other words, what are the advantages and disadvantages of each? implementation one: class A(models.Model): order=GenericRelation('Order') fields class B(models.Model): order=GenericRelation('Order') fields class Order(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') vs----- implementation two: class A(models.Model): fields class B(models.Model): fields class OrderA(models.Model): fields class OrderB(models.Model): same fields of orderA -
Django how can i add multiple databases connection dynamically?
I can add to multiple databases on Django but I want to add with a loop or add a new element to the DATABASES object. How can I add to this object list dynamically ?. Can I read from the txt file or models? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'deneme1', 'USER': 'mamp', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '8889', 'OPTIONS': { 'autocommit':True, } }, 'database2': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'deneme2', 'USER': 'mamp', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '8889', 'OPTIONS': { 'autocommit':True, } }