Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show DB data in my HTML page in Django website?
I checked my DB table and the data I entered is on my db, but I see nothing on my HTML page in my Django website. this is my View: from django.shortcuts import render from django.http import HttpResponse, JsonResponse from .models import Article # Create your views here. def home(request): context = { "articles": Article.objects.filter(status="publish").order_by("-publish") } return render(request, 'website/home.html', context) This is my model: from django.db import models from django.utils import timezone # Create your models here. class Article(models.Model): STATUS_CHOICES = ( ('Draft', 'Draft'), ('Published', 'Published') ) title = models.CharField(max_length=300) slug = models.SlugField(max_length=100, unique=True) description = models.TextField() thumbnail = models.ImageField(upload_to="images") publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES) def __str__(self): return self.title this is my HTML page: <div style="text-align: center;"> {% for article in articles %} <img src="{{ article.thumbnail.url}}" alt="{{ article.title }}"> <h1><a href="{{ article.slug }}"> {{ article.title }}</a></h1> <small>{{ article.publish }}</small> <p>{{ article.description }}</p> {% endfor %} -
Login page is verifying all users as good Django
I'm trying to build a login page in Django. But whenever I try to authenticate the user it doesn't work. The user passes each time even if the user doesn't exist. Any help I would really appreciate it! def login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) form = CreateUserForm() return render(request, "leadfinderapp/login.html", context={"form":form}) -
Django cart Timer
i am developing a commerce website with limited quantities so I need to have the option (like most travel, concerts, cinema etc. websites) to reserve the item for let's say 10 minutes. Basic idea is that when you add item to the cart available quantity decreases and Timer starts. If checkout proceeds, cool, nothing hapens. If cart is abandonned or timer goes to zero, item becomes again available (qty increases). I started with JS timer. When added to the cart i decrese the qty and if it reaches zero i increment the qty. It works fine if the customer stays on the page. But if he closes his page/computer i lose the timer info and qty is never incremented back in the DB. Second idea was to store timer in the backend, but again how do i run timer on the server. For info, i have cart stored in django.request.session.cart Can someine give me some guidance? Thanks Mali -
DoesNotExists query in python Django when I build eccomerce website
I am making a website for myself. When I tried making cart it was crushing but everything else works perfectly. Please help, i wasted 3 days already trying to solve it. Ask for any files you need, I will post. [here is error: Traceback (most recent call last): File "C:\Users\Kali\PycharmProjects\djangoProject\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Kali\PycharmProjects\djangoProject\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Kali\PycharmProjects\djangoProject\venv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Kali\PycharmProjects\djangoProject\venv\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Kali\PycharmProjects\djangoProject\shop\mainapp\views.py", line 47, in get customer = Customer.objects.get(user=request.user) File "C:\Users\Kali\PycharmProjects\djangoProject\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Kali\PycharmProjects\djangoProject\venv\lib\site-packages\django\db\models\query.py", line 429, in get raise self.model.DoesNotExist( mainapp.models.Customer.DoesNotExist: Customer matching query does not exist. 1 is my error [1]: https://i.stack.imgur.com/A6j9n.png I will also attach my homepage and all directories -
Mark a user as logged in using Django-two-factor-auth
I am using the Django-two-factor-auth library for my sites login. Everything is working fine, however when I try to login and redirect a new user to their profile page after sign up using login(request, user) I keep getting redirected to the login page. The login works fine when the user re-enters their new login credentials however I want to redirect the user straight to their profile page after signup instead. I am aware Django-two-factor-auth overides Django's built in authentication (Django.contrib.auth), however I am unsure why the login() function is not marking the user as authenticated. views.py from django.contrib.auth import login def signup(request): ... user = signup_form.save() login(request, user) return redirect('/profile') -
Django Models Exercise
Im new using django models, so I started doing some practice exercises that a friend did to me. But I got stuck 😅, this is the problem that I wanted to solve. Requirement: A Game company requires a solution which allow them store next information in the best way possible: server: Field which correspond to server's name and is representated as a slug name(ie: korea as kr, europe as eu, etc) game_id: Unique field which correspond to a game identifier and is representated as a integer (ie: 8234, 7324, etc) game_data: Field which contains all information of the determinated game_id stored in JSON format. Relationships: Server has many game_Id. Game_id has only a single game_data. To Consider: Game_id is an unique field, but into differents servers. By the momment, this is my code. models.py class Game(BaseModel): server = models.ForeignKey(Server, on_delete=models.CASCADE) game_id = models.CharField("gameId", max_length=25) game_data = JSONField(blank=True, False=True) class Server(BaseModel): name = models.SlugField("server", unique=True, max_length=25) I could said It works "well", but I've still having troubles about repeated game_ids on determinated servers, because my code it always will save all data without consider anything about server field. I tried to set unique = True on game_id field, but that validation … -
Auto foreign key in django models
It is possible to do this in Django. I have models and I want every new user to register in Model User and automatically in models Customer in foreign key register class Customer(models.Model): here auto user = models.ForeignKey(User, on_delete=models.CASCADE) phone = models.CharField(max_length=11,null=True) likecus=models.ManyToManyField(smartphone ,verbose_name="b",null=True) def __str__(self): return "User: {}, phone: {}".format(self.user, self.phone) -
My serializer that returns a 0 for Null value is not working
I'm trying to create a serializer that returns the value 0 instead of Null when API data is requested. class MyIntegerField(serializers.IntegerField): def to_representation(self, value): if value is None: return 0 return super(MyIntegerField, self).to_representation(value) class ListSerializer(serializers.ModelSerializer): post_count = MyIntegerField(initial=0) class Meta: model = Post fields = (..., 'post_count', ...) model.py: post_count = models.IntegerField(blank=True, null=True) If a user has no posts, then I would like to return the value 0, instead of Null. What is the issue with my current serializer? I think the field that's inputted is still pulling from my model field, and not the new serializer function. Currently I'm still receiving a Null when user requests data. -
Django API test not working for post request.with payload
I am writing some test for an API that I am working on. I am quit new to Django Rest-framework. This is the code for my 'create' test. The strange thing is that my test is failing (BAD request 400) but my published reat-api is working, at least via the django api-web-browser. I can't find the mistake. Can anyone see what I am doing wrong? The Vacancy_url is correct, I checked that by printing in in code. The get request don't have any problems. So I can conclude that my client is working. Then I thought it must the payload That I am sending. Here I show my test script and my model and view. TESTSCRIPT: from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import Vacancy from vacancy.serializers import VacancySerializer VACANCY_URL = reverse('vacancy:vacancy-list') class PrivateVacanciesApiTests(TestCase): """ Test the Private vacancy API""" def setUp(self): self.client = APIClient() self.user = get_user_model().objects.create_user( email='test@uxstudio.nl', password='testpass') self.client.force_authenticate(self.user) def test_create_vacancy_successful(self): """Test create a new vacancy""" payload = { "title": "titel", "description": "wat tekst om te testen", "is_active": True, } self.client.post(VACANCY_URL, payload) exists = Vacancy.objects.filter( company_id=self.user, title=payload['title'] ).exists() self.assertTrue(exists) MODEL class Vacancy(models.Model): """Vacancy … -
passing dictionary to view ,with multiple key:value pairs
def status_(request,id): stages=['Vendor Quotation','Estimate Generation','Purchase Requsition','Purchase Order','Provision To Invoice','Reimbursement Invoice','Request Receipt#(PTI+RI+PO)','Receipt# Received(Updated PTI)','Request Sales Tax Invoice','Uploaded to Jazz Portal'] ctx={'invoice':Invoices.objects.get(pk=id),'stages':stages} return render(request,"Invoices/status.html",ctx) Hi I am trying to pass multiple objects of data for displaying to the template for displaying , I am creating a ctx dictionary with multiple 2 key value pairs ,second Key-value pair is array ,when i access this array in by using {% for idx in range(0,len(ctx.get("stages")) %} I get following parsing error **Could not parse the remainder: '(0,len(ctx.get("stages"))' from 'range(0,len(ctx.get("stages"))'** -
stderr + python: can't open file 'app.py': [Errno 2] No such file or directory using spawn in electron js
stderr + python: can't open file 'app.py': [Errno 2] No such file or directory using spawn in electron js please someone helps me -
Django Rest Views: How to access a class variable in another class?
Here's how my authentication works: I get an email and check if that email exists in the database, if it doesn't, I generate a random 8-digit number and then email it to the entered email address and inform the user to confirm his/her email address by entering the emailed code. Here's the View: class CheckEmailView(APIView): permission_classes = [AllowAny] def post(self, request, *args, **kwargs): serializer = CheckEmailSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = Account.objects.filter(email=serializer.data['email']) if user.exists(): return Response({'is_member': True}) else: confirm_code = randint(10000000, 99999999) context_data = {'code': confirm_code} email_template = get_template('email.html').render(context_data) email = EmailMessage( 'Confirm Email', email_template, settings.EMAIL_HOST_USER, [serializer.data['email']], ) email.content_subtype = 'html' email.send(fail_silently=False) return Response({'is_member': False}) I'm using another View to check if the user enters the correct confirmation code, so now I have to send the value of confirm_code variable to the new class. which Looks like this at the moment: class ConfirmEmailView(APIView): permission_classes = [AllowAny] def post(self, request, *args, **kwargs): user_input_code = request.data print(confirm_code) return Response(True) But I have no idea how to pass the value from CheckEmailView to ConfirmEmailView class. I'm new to Django so despite the solution, any tips on how to make my code any better or any faster or more logical solution to manage this whole process … -
Django - item created by logged user ViewSet
What I want: A logged user creates an item which is stored in the database with that user ForeignKey. I have 2 codes: both should do the same thing (create item linked to current user), but one of them works and the other one doesn't. GET requests work, I'm focusing on POST requests. First code (POST working): class UserPortfolio(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=False, null=False) slug = models.CharField(max_length=200, blank=False, null=False) class UserPortfolioSerializer(serializers.ModelSerializer): class Meta: model = UserPortfolio exclude = ('id', 'user') class UserPortfolioViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserPortfolioSerializer queryset = UserPortfolio.objects.all() permission_classes = [IsAuthenticated] def get_queryset(self): return UserPortfolio.objects.filter(user=self.request.user).order_by('last_updated') def perform_create(self, serializer): serializer.save(user=self.request.user) Second code (POST not working): class ExchangeConnection(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) portfolios = models.ManyToManyField(UserPortfolio, blank=True) exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE) last_updated = models.DateTimeField(auto_now=True) class Meta: db_table = 'exchange_connection' verbose_name_plural = "Exchange Connection" def __str__(self): return self.user.username class ExchangeConnectionSerializer(FlexFieldsModelSerializer): class Meta: model = ExchangeConnection fields = '__all__' expandable_fields = {'exchange': ExchangeSerializer, 'portfolios': (UserPortfolioSerializer, {'many': True})} class UserExchangeConnectionsViewSet(viewsets.ModelViewSet): serializer_class = serializers.ExchangeConnectionSerializer queryset = ExchangeConnection.objects.all() permission_classes = [IsAuthenticated] def get_queryset(self): return ExchangeConnection.objects.filter(user=self.request.user).order_by('last_updated') @action( detail=True, methods=['post'], url_path='create-exchange-connection', ) def post(self, serializer): serializer = serializers.ExchangeConnectionPostSerializer(user=self.request.user) if serializer.is_valid(): serializer.save() return Response({'status': 'Exchange created.'}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The error I get when I POST … -
Trouble Importing module in Django
I am working inside of a Django project and I'm trying to import a class from the models.py file. Screen shot of file scaffold shows the google_locator.py file I am trying to import Truck instance from models. I have tried .models, ..models, ../models, ./models, truck.models, and several more combinations. I either get an "invalid syntax" error or "ImportError: attempted relative import with no known parent package" -
return JsonResponse is printing it's values after Click
I am using Django Version- 3.8.1. AND i built a like, dislike system for BlogPost. BUT when i click on Like button it just print {"action": "like_only"} views.py def post_like_dislike(request, post_id): post = get_object_or_404(Post, pk=post_id) # Like if request.GET.get('submit') == 'like': if request.user in post.dislikes.all(): post.dislikes.remove(request.user) post.likes.add(request.user) return JsonResponse() elif request.user in post.likes.all(): post.likes.remove(request.user) return redirect('mains:posts') else: post.likes.add(request.user) return JsonResponse({'action': 'like_only'}) # Dislike elif request.GET.get('submit') == 'dislike': if request.user in post.likes.all(): post.likes.remove(request.user) post.dislikes.add(request.user) return JsonResponse({'action': 'unlike_and_dislike'}) elif request.user in post.dislikes.all(): post.dislikes.remove(request.user) return JsonResponse({'action': 'undislike'}) else: post.dislikes.add(request.user) return JsonResponse({'action': 'dislike_only'}) else: messages.error(request, 'Something went wrong') return redirect('mains:posts') detail.html <form method="GET" class="likeForm d-inline" action="{% url 'mains:post_like_dislike' data.id %}" data-pk="{{ data.id }}"> <button type="submit" class="btn"><i class="far fa-thumbs-up"></i> <span id="id_likes{{data.id}}"> {% if user in data.likes.all %} {{data.likes.count}}</p> {% else %} {{data.likes.count}}</p> {% endif %} </span><form><button name='submit' type='submit' value="like"> Like </button></form> </button> </form> ERROR When i click on Like button it finely add like but it prints the return Jsonresponse value ( {"action": "like_only"} ). What have i tried Once i tried to redirecting the page into it BUT then failed. Check HereCheck Here Thank You in Advance -
Django: Generate Insert Statements By Passing a Django Object
Is there a way to generate raw MYSQL insert statements for a object and it's related objects. Any package that does this out of box? -
Django AbstractBaseUser MultipleChoiceField
I have created a custom user model with AbstractBaseUser like this: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) preference = models.CharField(max_length=400) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'preference'] objects = CustomUserManager() def __str__(self): return self.email For the preference field i don't want a char field, but to create a MultipleChoiceField and when a user sign up to choose what he/she wants from the choices. Is there a simple way to do this? I have a similar form which i used for different purpose: class CategoryForm(forms.Form): def __init__(self, *args, **kwargs): categories = kwargs.pop("Category") super(CategoryForm, self).__init__(*args, **kwargs) self.fields["Category"] = forms.MultipleChoiceField(choices=categories, label='Click this to select categories') -
Using AJAX to run django function from JS
I have a html button. when i press it i want to run a JS function that will call a django function. The website loads but when i press the button nothing happens. can anyone see where I am going wrong? HTML: <input type='button' value='run function' onclick='runScript()'> URLs.py: path('printing_function/', views.printing_function, name='printing_function') views.py: def printing_function(request): print("hello") return HttpResponse() Main.js: function runScript() { $.ajax({ url: 'print_function/', success: function(data) { } }); } -
Django error in test only: django.contrib.auth.models.User.customers.RelatedObjectDoesNotExist: User has no customers
I write test in Django. But for a reason I can't explain, some code that use to work in data migration does not work in tests. I have two models related with a oneToOne relationship: User and Customers. I create Users first and Customers 'based' on Users created just before. Here I use RandomUser API but even if I create User and Customers 'normally' it failed In my tests.py: class CafeTestCase(TestCase): def setUp(self): users1 = RandomUser.generate_users(5) for user in users1: u = User.objects.create( username = user.get_username()+str(random.randrange(100000)), ... date_joined = timezone.now() ) Customers.objects.create( user = u, ... created_at = timezone.now() ) -
How to make migrate Django with Docker
I have docker db and web containers. After command docker-compose up -d --build I have errors with not exists relations in DB. I really don't have tables in DB. I execute following command: $ docker-compose exec web python manage.py migrate And I have following output: Operations to perform: Apply all migrations: admin, auth, autos, bot, contenttypes, sessions, sites Running migrations: Applying contenttypes.0001_initial... OK ... If I execute this command second time, then I get No migrations to apply., but I still don't have tables in DB. Part of my docker-compose.yaml: version: '3.3' x-base: &base restart: unless-stopped build: . working_dir: /code/autotracker env_file: - .env services: web: <<: *base command: gunicorn autotracker.wsgi -b :8001 volumes: - "/static:/static" ports: - "8001:8001" depends_on: - db db: image: postgres restart: unless-stopped volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - .env.db ports: - 5432 volumes: postgres_data: -
Django: ModelForm save() method for multiple objects for a span of dates
I need to make a form to save multiple instances of a Model for a span of dates provided by a user. I have created a ModelForm with a change - exclude date (a model attribute) and added 2 fields: date_from and date_to (for a starting and ending date). I would like the form to save as many records as needed based on the dates span. The code below doesn't work. models.py class Tour(models.Model): company = models.ForeignKey('Company', on_delete=models.PROTECT) employee = models.ForeignKey('Employee', on_delete=models.PROTECT) date = models.DateField() forms.py class TourForm(forms.ModelForm): DATE_INPUT_FORMATS = ['%d-%m-%Y'] date_from = forms.DateField(widget=AdminDateWidget) date_to = forms.DateField(widget=AdminDateWidget) class Meta: model = Tour fields = ['company', 'employee', 'date_from', 'date_to'] def save(self, *args, **kwargs): start_date = self.cleaned_data['date_from'] end_date = self.cleaned_data['date_to'] delta = datetime.timedelta(days=1) count = end_date - start_date while start_date <= end_date: data = { 'company': self.cleaned_data['company'], 'employee': self.cleaned_data['employee'], 'date': start_date, } single_tour = SingleTourForm(data) single_tour.save() start_date += delta class SingleTourForm(forms.ModelForm): DATE_INPUT_FORMATS = ['%d-%m-%Y'] class Meta: model = Tour fields = '__all__' The custom save() method above doesn't work. I get an error 'NoneType' object has no attribute 'save' What should I do to make it work? I am tryign to make it work using Django Admin Panel. -
Django: fetch multiple models
This is my first project with Django, I want to recreate my static HTML/CSS/js site to a dynamic site with an admin panel. However, I have a hard time understanding the views/urls.On my index, I have main news, events, mini news - 3 categories. I can render mainnews, however, I'm not sure what to use as 'return' for the other 2(all 3 are on the belongs to index page) Currently, I have 'index' but doesn't show the events/news. pages>view.py from django.shortcuts import render, redirect, get_object_or_404 from mainnews.models import Mainnews from events.models import Event from mininews.models import Mini # Create your views here. def home_view(request): main_news = Mainnews.objects.order_by('-publish_date').filter(is_published = True)[:1] context = { 'main_news' : main_news } return render(request, 'index.html', context) def event_view(request): events = Event.objects.order_by('-publish_date').filter(is_published = True)[:3] context = { 'events' : events } return render(request, 'index.html', context) def mini_view(request): mini_news = Mini.objects.order_by('-publish_date').filter(is_published = True)[:4] context = { 'mini_news' : mini_news } return render(request, 'index.html', context) main>urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from pages.views import home_view, event_view, mini_view urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name = 'home'), path('', event_view, name = 'home'), path('', mini_view, name = 'home'), … -
Django - How to filter database using HTML select tag?
I am trying to create an E-Commerce Website. So, I am trying to add filters like Price: Low - to High and vice versa. I know how to filter the price but I don't know how to apply the filter on select value getting changed. Here is HTML Code <div class="d-flex flex-row-reverse" style="margin-right: 20px; margin-bottom: 20px;"> <label> <select class="bg-dark" name="price" id="priceFilter"> <option value="normal">Sort by Price</option> <option value="low">Low-to-High</option> <option value="high">High-to-Low</option> </select> </label> </div> Django Code def index(request): fil = request.GET('price') if fil == "low": products = Product.objects.all().order_by('productDiscountedPrice') elif fil == "high": products = Product.objects.all().order_by('-productDiscountedPrice') else: products = Product.objects.all() context = { 'products': products } return render(request, "Amazon/index.html", context) So, How to sort products when select tag value gets changed? -
How to implement element ordering accross two different models in Django?
I've got these Car and Bike models I can't modify. They may need to be linked to a Ferry model which I can modify. I want to implement ordering of these elements of two different models in the database and I want to avoid using Generic Foreign Keys. So far this is what I've come up with: class Car(models.Model): pass class Bike(models.Model): pass class Ferry(models.Model): pass class Lot(models.Model): position = SmallInteger() car = models.ForeignKey(to=Car, null=True, related_name="ferries") bike = models.ForeignKey(to=Bike, null=True, related_name="ferries") ferry = models.ForeignKey(to=Ferry, null=False, related_name="load") Now my goal is to be able to access directly all the elements of a particular ferry –be they cars or bikes– ordered by position, and all the ferries (in the context of ferry travel bookings there may be several) of a particular car or bike: some_ferry.load.all().order_by("position") some_car.ferries.all() How do I create these relations, including a sort of combination of (car + bike)? -
Django models - Model relations misunderstandings
I want to create a table that only adds some information about another table. Here is what I have: I have 2 tables Exchange and ExchangeConnection: class Exchange(models.Model): slug = models.CharField(max_length=200, primary_key=True, blank=False, null=False) name = models.CharField(max_length=200, blank=False, null=False) class ExchangeConnection(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) exchange = models.OneToOneField(Exchange, on_delete=models.CASCADE) There are multiple exchanges which are defined by me and won't be modified throughout the app usage. It's only useful stored data to make my app works. I see it more like a type of ExchangeConnection. Then, I have ExchangeConnection. This table will be modified throughout the app usages because it represents information that belongs to a user, and it will be able to create some: When the user create an ExchangeConnection, he select which only one Exchange he is using. In my code you can see I'm using OneToOneField which isn't good because It implies an Exchange can be "linked" only once for every ExchangeConnection. I don't want to use ForeignKeyField in Exchange because I don't want ExchangeConnections to be part of an Exchange. I certainly misunderstood the logic of relations so I may bot be clear...