Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Invalid object name - statements could not be prepared
I have built a custom user model which until introducing database routers was working fine. I have pasted the model below and wondered if anyone had any insight as to why it is generating the following sql error message. django.db.utils.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'Users2_customuser'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") import datetime from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) from django.core.mail import send_mail from django.utils.translation import ugettext_lazy as _ import logging log = logging.getLogger(__name__) class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): if not email: raise ValueError(_(f'Please enter an email address')) email = self.normalize_email(email) user = self.model(email=email, **kwargs) user.set_password(password) user.save() log.info(f'User created with email: {email}') return user def create_superuser(self, email, password=None, **kwargs): kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) if kwargs.get('is_staff') is not True: raise ValueError(f'Superuser must have staff permission') if kwargs.get('is_superuser') is not True: raise ValueError(f'Superuser must have superuser permission') log.info(f'Superuser created with email: {email}') return self.create_user(email, password, **kwargs) class CustomUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField(max_length=150, unique=True) first_name = models.CharField(max_length=150, blank=True) surname = models.CharField(max_length=150, blank=True) address1 = models.CharField(max_length=254, blank=True) address2 = models.CharField(max_length=254, blank=True) area_code = models.CharField(max_length=20, … -
DRF simplejwt do not updating the access token
I'm using simpleJWT with Django restframework and i get this problem when i tried to refresh the access token, i post http request sending the refresh token to the refresh endpoint, it suppose to get new access, but i keep getting the same access token even though the access token has expired ! what's reason that might cause this ? is there anyone can help please ? setting.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=1), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer'), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=1), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } urls.py from django.contrib import admin from django.urls import path, include from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] -
How to make add to cart without reloading the page (js and django)?
Im making this add to cart functionality, and I want to show the new cart total after adding to cart without reloading the page. Right now I have it to reload the page to show the cart changes after having added a product. (SOME OF THE CODE CAN BE IN DANISH, I HOPE ITS FINE) HTML (The add to cart button) <div class="buy-item flex flex-ai-c"> <button data-product="{{product.id}}" data-action="add" class="add-button add-btn update-cart">TILFØJ TIL KURV</button> <div class="flex flex-ai-c flex-jc-c"> <span class="cart-quantity-text">ANTAL</span> <input class="cart-quantity-input" type="number" value="1"> </div> </div> JS function addCookieItem(productId, action) { if(action == 'add'){ if(cart[productId] == undefined){ cart[productId] = {'quantity':parseInt(antal.value)} }else{ cart[productId]['quantity'] += parseInt(antal.value) } } if(action == 'add-from-cart'){ cart[productId]['quantity'] += 1 } if(action == 'remove-from-cart'){ cart[productId]['quantity'] -= 1 if(cart[productId]['quantity'] <= 0){ console.log('Remove Item') delete cart[productId] } } if(action == 'delete'){ delete cart[productId] } console.log('Cart:', cart) document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/" location.reload() } Django def cookieCart(request): try: cart = json.loads(request.COOKIES['cart']) except: cart = {} print('Cart:', cart) items = [] order = {'get_cart_total':0, 'get_cart_items':0} cartItems = order['get_cart_items'] for i in cart: try: cartItems += cart[i]['quantity'] product = Product.objects.get(id=i) total = (product.price * cart[i]['quantity']) order['get_cart_total'] += total order['get_cart_items'] += cart[i]['quantity'] item = { 'product':{ 'id':product.id, 'name':product.name, 'price':product.price, 'imageURL': product.imageURL, 'stripe-price': product.stripe_price_id, … -
Django ManyToMany CheckConstraint IntegerField
I have some models, 1 abstract, and 2 that inherit from the abstract model with a ManyToMany relationship. One model gets its members from the other model. I want to implement a constraint on this model so that its members can't be more than the Sum of the remaining_members on the original groups. I created a Q expression that expresses what I want to achieve, but I know it's not the right way to do it. How can I create the constraint with models that are related by a ManyToMany field? class AbstractGroup(models.Model): members = models.IntegerField() class Meta: abstract=True class OriginalGroup(AbstractGroup): remaining_members = models.IntegerField() new_group_members = ManyToManyField(NewGroup, related_name=new_group, related_query_name=new_group) class NewGroup(AbstractGroup): name = models.CharField() class Meta: constraints = [ models.CheckConstraint( Q(members__lte=original_groups__sum__remaining_members, name='%(app_label)s_%(class)s_available_members' ) ) ] -
How do I recommit database to Heroku after destroying DB in the Heroku dashboard
I've built an app using Django etc. I ran into a whole bunch of problems with database on Heroku after accidentally pushing to production before running heroku run python manage.py makemigrations and heroku run python manage.py migrate. I decided to just completely destroy the database currently on Heroku and want to recommit my app's models to heroku. My hope is to completely start from a clean slate. I just want to make sure I do this correctly so I'm asking for clear instructions about how to recommit my app's database to Heroku after destroying the database in the dashboard. Current error I get when I open my app online is: settings.DATABASES is improperly configured. Please supply the NAME or OPTIONS['service'] value. Thanks! -
Why Django rest framework is not saving data but returns 200 ok code
I have successfully send a post request to deployed(in Heroku) Django rest API from react axios but the data is not saved in my database. I use MongoDB(Djongo) as a databse. Let me show you the code I have used. settings.py """ Django settings for CyberMinds project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import django_heroku # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "rest_framework.authtoken", "corsheaders", "accounts", "threat_catalog_models", 'django_rest_passwordreset', "threat_catalog", # "risk_model", "risk_model", "business_process", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "config.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] WSGI_APPLICATION = "config.wsgi.application" # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { "default": { "ENGINE": "djongo", "NAME": "cyberminds", } … -
Failed to execute command: No such file or directory (Gunicorn) (Django)
First I have created a socket named 'receiver.socket' (nvenv) papli@sender:/datadrive/receiver/GisServer$ cat cat /etc/systemd/system/receiver.socket cat: cat: No such file or directory [Unit] Description=receiver socket [Socket] ListenStream=/run/receiver.sock [Install] WantedBy=sockets.target Then, I created a service file with the same name 'receiver.service' (nvenv) papli@sender:/datadrive/receiver/GisServer$ cat /etc/systemd/system/receiver.service [Unit] Description=gunicorn daemon Requires=receiver.socket After=network.target [Service] User=papli Group=papli RuntimeDirectory=gunicorn WorkingDirectory=/datadrive/receiver/GisServer Environment="PATH=/datadrive/receiver/GisServer/nvenv/bin" ExecStart=/datadrive/receiver/GisServer/nvenv/bin/gunicorn --access-logfile /datadrive/sender/log/gunicorn.log --workers 3 --bind unix:/run/receiver.sock GisServer.wsgi:application [Install] WantedBy=multi-user.target After that sudo systemctl enable receiver sudo systemctl start receiver Error that I am getting (nvenv) papli@sender:/datadrive/receiver/GisServer$ sudo systemctl status receiver ● receiver.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/receiver.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Sat 2022-03-19 07:14:09 UTC; 3min 38s ago Main PID: 6029 (code=exited, status=203/EXEC) Mar 19 07:14:09 sender systemd[1]: Started gunicorn daemon. Mar 19 07:14:09 sender systemd[6029]: receiver.service: Failed to execute command: No such file or directory Mar 19 07:14:09 sender systemd[6029]: receiver.service: Failed at step EXEC spawning /datadrive/receiver/GisServer/nvenv/bin/gunicorn: No Mar 19 07:14:09 sender systemd[1]: receiver.service: Main process exited, code=exited, status=203/EXEC Mar 19 07:14:09 sender systemd[1]: receiver.service: Failed with result 'exit-code'. Troubleshooting Steps I followed Checked sock file is created. (nvenv) papli@sender:/datadrive/receiver/GisServer$ ls /run/receiver.sock /run/receiver.sock Inside nvenv/bin gunicorn file is present and their permissions are adequate (nvenv) papli@sender:/datadrive/receiver/GisServer$ ls -la nvenv/bin/gunicorn … -
How to avoid FileNotFound Error in django model ImageField when file does not exist
I have a Django model which has ImageField img and I have thousands of rows in the db while I also know some of the images in the db do not exist in the directory. But its an existing project and I cant do anything on that for now while the clients produce the missing images later. But the issue is while retrieving a queryset without any reference or specific use of the image files, I get a FileNotFound error. This happens both in Django admin once I paginate to a page that contains one of the records with missing file and also in a ViewSet's queryset I try to create for frontend. And because I have not paginated the ViewSet queryset, I can't even test the endpoint without having the FileNotFound error. How to catch this error or avoid it? -
Getting KeyError: 'answers' when using validated_data.pop('answers') even tho its getting the right data
I'm trying to define create() method in my nested serializers learning from the documentation. When I print the validated_data.pop and it HAS DATA that I requested but its returning keyerror which doesnt make sense since it has data in it. Error: answers_data = validated_data.pop('answers') KeyError: 'answers' serializers from rest_framework import serializers from .models import Question, Answer class AnswerSerializer(serializers.ModelSerializer): """Serialize Answer model""" class Meta: model = Answer fields = ('title', 'body', 'slug', 'author', 'question') lookup_field = 'slug' # https://stackoverflow.com/questions/55031552/how-to-access-child-entire-record-in-parent-model-in-django-rest-framework class QuestionSerializer(serializers.ModelSerializer): """Serialize Question model""" #This answer variable and the fields 'answer' you refer to has to be the SAME but #These can change exp: 'aaa' answer = AnswerSerializer(read_only=False, source='answers', many=True,) print("@@@@@@") print(answer) print("@@@@@@") print(type(answer)) class Meta: model = Question fields = ('title', 'slug', 'author', 'category', 'answer',) lookup_field = 'slug' def create(self, validated_data): print("@@@@@@") print("@@@@@@") print(validated_data.pop('answers')) print("@@@@@@") print("@@@@@@") answers_data = validated_data.pop('answers') question = Question.objects.create(**validated_data) for answer_data in answers_data: Answer.objects.create(question=question, **answer_data) return question views.py from django.shortcuts import render from .models import Question, Answer from django.conf import settings from rest_framework import viewsets from rest_framework.authentication import TokenAuthentication from .serializers import QuestionSerializer #from .permissions import UpdateOwnPrice from rest_framework.permissions import IsAdminUser class QuestionViewSet(viewsets.ModelViewSet): """CRUD """ serializer_class = QuestionSerializer queryset = Question.objects.all() authentication_classes = (TokenAuthentication,) #permission_classes = (UpdateOwnPrice,) … -
DJango - Redirect to another apps / from a button click
I've been trying to redirect my user to another apps root on a button click. So I've two apps, 'portfolio' and 'blogs'. 'blogs' is the main app which loads first. I've been able to navigate to 'portfolio' app from 'blogs', but how can I do it the other way around? My Project urls.py path('admin/', admin.site.urls), path('portfolio/', include('portfolio.urls')), path('', include('blogs.urls')), ] -
data i entered in the admin page not reflecting in my webpage,
The data i entered in the admin page not showing up on the web page. i don't know what is going wrong with my code, please help webpage admin.py from django.contrib import admin from blog.models import Post # Register your models here. class PostAdmin(admin.ModelAdmin): list_display = ('title','slug','status','created_on') list_filter = ('status',) search_fields = ['title','content'] prepopulated_fields = {'slug':('title',)} admin.site.register(Post, PostAdmin) urls.py from . import views from django.urls import path urlpatterns = [ path('blogspot/',views.PostList.as_view(), name="b"), path('<slug:slug>/',views.PostDetail.as_view(), name="post_detail"), ] views.py from django.views import generic from .models import Post # Create your views here. class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'blog/index.html' class PostDetail(generic.DetailView): model = Post template_name = 'blog/post_detail.html' -
Can django queryset date be formatted from 'DD:MM:YYYY HH:MM:SS' TO 'YYYY:MM:DD' using Func,Value,output_field?
My desired output is : { " formated_date:'2021-05-01' ", } Queryset returns : {date : '2021-05-01 12:01:20'} -
Django with Auth0
Currently learning about Auth0 and django. https://github.com/auth0-blog/django-feed-auth0/blob/main/feed/feed/urls.py I saw the URL pattern is like this urlpatterns = [ path('admin/', admin.site.urls), path('', include('feedapp.urls')), path('', include('social_django.urls')), ] From what i learned previously we should have 1 path('', views.xyz) as it will be redundant to have same url pointing to the different views unless we have put other input like int or str. But auth0 have same path with other views. Not really understand why is it okay for it to be like this? Hope you guys can explain to me. Thanks -
How to set up Celery and Heroku Redis
I provisioned a Heroku Redis on my Dashboard and want to use it. Host <x>.compute-1.amazonaws.com User Port <y> Password <x> URI redis://:<x>.compute-1.amazonaws.com:<y> So I ran pip install celery pip install redis And here I need to use it which i used the URI which proceeds to error out. ModuleNotFoundError: No module named 'url' settings.py # CELERY STUFF BROKER_URL = 'url' CELERY_RESULT_BACKEND = 'url' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Africa/Nairobi' celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'portfolio.settings') app = Celery('portfolio') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) init.py from __future__ import absolute_import # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app -
malloc error when migrate in Django using mySQL database
I'm using Django in VSCode and want to connect to the MySQL database, I've created the database in MySQL. When changing the database configuration from mysqlite to MySQL in settings.py, and do the migrate, the error pops up (in the picture below). Basically it says malloc error and asks me to set a breakpoint in malloc_error_break to debug. I have no idea of what's going on here. Anyone knows how to fix this error? The error message disappears once I changed the settings back to sqlite, it only happens when using MySQL. screenshot of error -
Django User Form Update with Groups
I am trying to update a User with django forms. In that form, I include UserGroups also. The problem right now I am facing is that if the user has multiple groups or has no group at all, it is not working. but if the user has a single group then it is working fine. Here is my code. views.py class User(AbstractUser): first_name = models.CharField(blank=False, max_length=25, null=False) last_name = models.CharField(blank=False, max_length=25, null=False) email = models.EmailField(blank=False, null=False, unique=True) password = models.CharField(blank=False, editable=False, max_length=256) company = models.ForeignKey(blank=True, on_delete=models.CASCADE, null=True, related_name="users", related_query_name="user", to='company.Company') is_active = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] username = name = contact = photo = None objects = UserManager() class Meta: ordering = ['id'] def get_absolute_url(self): return reverse('user_detail', kwargs={'pk': self.pk}) def __str__(self) : return self.email forms.py class UserForm(forms.ModelForm): company = forms.ModelChoiceField(queryset=Company.objects.all(), required=True) group = forms.ModelMultipleChoiceField(queryset=Group.objects.all(), required=True) def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['first_name'].widget.attrs = { 'class': 'form-control form-control-sm', 'name': 'first_name', 'id': 'first_name', 'type': 'text'} self.fields['last_name'].widget.attrs = { 'class': 'form-control form-control-sm', 'name': 'last_name', 'id': 'last_name', 'type': 'text'} self.fields['email'].widget.attrs = { 'class': 'form-control form-control-sm', 'name': 'email', 'id': 'email', 'type': 'email', 'aria-describedby': 'emailFeedback' } self.fields['company'].widget.attrs = { 'class': 'form-select form-select-sm', 'name': 'company', 'id': 'comapny', 'type': 'select' } self.fields['group'].widget.attrs = { … -
NoReverseMatch Reverse for 'save-post' with arguments '('',)' not found. 1 pattern(s) tried: ['save/(?P<pk>[0-9]+)$']
I cannot figure out why I keep getting this "NoReverseMatch at /". I am trying to add AJAX to a form to save posts. It seems to be a problem with the URL in the Javascript, but I cannot figure out exactly what it is. Can anyone tell me what is wrong here? Thank you in advance. urls.py path('save/<int:pk>', views.AjaxSave, name='save-post'), views.py def AjaxSave(request, pk): if request.POST.get('action') == 'post': id = int(request.POST.get('postid')) result = post.saves.count() post = get_object_or_404(Post, id=id) if post.saves.filter(id=request.user.id).exists(): post.saves.remove(request.user) post.save() else: post.saves.add(request.user) post.save() return JsonResponse({'result': result, }) popular.html This is the form on the HTML <form action="{% url 'save-post' post.id %}" id="save" method="post"> {% csrf_token %} <button class="savebutton" type="submit" name="post_id" title="Save Post" id="save" value="{{ post.id }}"> <i class="fas fa-bookmark"></i> Save Post </button> </form> Javascript <script> $(document).on('click', '#save', function (e){ e.preventDefault(); $.ajax({ type: 'POST', url: "{% url 'save-post' post.id %}", data: { postid: $('#save').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, success: function (json) { alert('Post saved!') }, error: function () { alert('Error!') } }); }) </script> -
Django ID of foreign key doesn't exist after migrating
I'm new to Django, and I'm trying to create a "game" model with two attributes: A many-to-one field where multiple instances of the game model are associated with an instance of a custom user model. A many-to-many field where instances of the game model are connected with multiple instances of words, and instances of the word model are connected with multiple instances of the game model Game model: class SortingGame(models.Model): user_current_player = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, blank=True) field_words = models.ManyToManyField(Word, related_name="field_sorting_games") Word model: class Word(models.Model): str_word = models.CharField(max_length=50,null=True) int_grade_level = models.IntegerField() arrint_phonemes = ArrayField(models.CharField(max_length=50),null=True) arrstr_graphemes = ArrayField(models.CharField(max_length=50),null=True) int_num_syllables = models.IntegerField() arrstr_syllables = ArrayField(models.CharField(max_length=50),null=True) User model: class CustomUser(AbstractBaseUser): # must have the following fields for django email = models.EmailField(verbose_name="email",max_length = 100,unique=True) username = models.CharField(max_length = 30, unique = True) date_joined = models.DateTimeField(verbose_name = "date_joined",auto_now_add=True) last_login = models.DateTimeField(verbose_name = "last_login",auto_now = True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default = False) is_staff = models.BooleanField(default = False) is_active = models.BooleanField(default = True) first_name = models.CharField(max_length=15, blank=True) last_name = models.CharField(max_length=30, blank=True) spelling_level = models.IntegerField(default=1, unique=False) time_played = models.IntegerField(default=0, unique=False) percent_correct = models.IntegerField(default=0, unique=False) When I run python3 manage.py makemigrations and python3 manage.py migrate, it doesn't complain, but when I go to the admin page of my … -
Passing a pk from one template to another
I am relearning django/python recently and trying to build an app to manage a season ticket draft between friends. I've become stuck while searching for this answer, could be my phrasing, but I'm trying to understand how to pass a value from one template to another. Here is an example of what I am doing. views.py def home_page_view(request): sessions = DraftSession.objects.filter(session_status="ACTIVE") return render(request, "index/index.html", { 'arena_mappings': ARENA_MAPPINGS, 'team_mappings': TEAM_MAPPINGS, 'sessions': sessions, }) index.html {% for session in sessions %} <tr> <td> {{ session.season_year }} </td> <td> {{ team_mappings|get_item:session.home_team }} </td> <td> {{ arena_mappings|get_item:session.home_team }} </td> <td> {{ session.create_date }} </td> <td> {{ session.session_owner }} </td> <td> <button type="button" class="btn btn-primary">Join Now!</button> </td> </tr> {% endfor %} Using the button in the last column I want the user to be able to go to a new page that has awareness of the row that was selected, my assumption is this would be passed in via the pk for the db row. I've setup the view, urls, etc; just lost on how to pass the selection on the the new page. Appreciate any help! -
django 3rd party API Event Loop?
I'm quite new to back-end development so please forgive my ignorance. I need to connect my Django backend to a 3rd party API to fetch live location data from GPS trackers. This needs to be done server side as it triggers other events, so it can't just be run in the browser. What's the best way to go about doing this please? So far I have thought of something like an event loop which calls the API every 60 seconds, but can I run this on a separate thread for example? Is that even the best thing to do? Is it possible to do something like a websocket form my backend to the 3rd party? What's the best way of keeping this data updated? Finally, how does a solution like this scale, what if I had 5,000 vehicle trackers which all needed updating? Any advice would be greatly appreciated. Thank you. -
Can't use assertTemplateUsed with unitest.TestCase
Please help, i'm fairly new to Django and not sure what's the best way to proceed with my unit-tests. So, i have a large django app, and it has dozens of views-methods, and the postgresql schemas get pretty complex. I've read that if I use "from django.test import TestCase" then the test database is flushed after running each unit-test. I wanted to prevent from flushing the db in between unit-tests within the same class, so i started using "from unittest import TestCase". That did the trick and the db is preserved in between unit-tests, but now the statement self.assertTemplateUsed(response, 'samplepage.html') gives me errors AttributeError: 'TestViews' object has no attribute 'assertTemplateUsed'. What can I do? Is there an alternative to 'assertTemplateUsed' that can be used with unittest.TestCase? Many thanks in advance! -
How to extend an IIS request - Django
How can I extend the waiting time for e.g. downloading a file? I use ISS and tried to change the Request Timeout from 90 to 300 in FastCGI Settings, but that didn't help. If the file download request takes longer than 90 seconds, I have a 500 error. The entire site is based on python / Django. -
How to share my list to other user (Django)
Hello guys i'm a begginer in Django and i made a Shopping-list-app from wathing videos on youtube. I can make list in my app and i want to share my list to other user, but i do't know how really do that. I would be happy if someone could help me. model.py I tried to use models.ManyToManyField but i know don't what should i do in View.py to app the list from a user to other user from django.db import models from django.db import models from django.contrib.auth.models import User class Liste(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=30, verbose_name = "Titel") item1 = models.CharField(max_length=30, blank=True, verbose_name = "1") preis1 = models.DecimalField(max_digits=5, decimal_places=2, default = 0, verbose_name = "Preis") item2 = models.CharField(max_length=30, blank=True, verbose_name = "2") preis2 = models.DecimalField(max_digits=5, decimal_places=2, default = 0, verbose_name = "Preis") item3 = models.CharField(max_length=30, blank=True, verbose_name = "3") preis3 = models.DecimalField(max_digits=5, decimal_places=2, default = 0, verbose_name = "Preis") item4 = models.CharField(max_length=30, blank=True, verbose_name = "4") preis4 = models.DecimalField(max_digits=5, decimal_places=2, default = 0, verbose_name = "Preis") item5 = models.CharField(max_length=30, blank=True, verbose_name = "5") preis5 = models.DecimalField(max_digits=5, decimal_places=2, default = 0, verbose_name = "Preis") @property def rate(self): total = (self.preis1) + (self.preis2) + (self.preis3) + (self.preis4) … -
Django get objects that have certain ManyToMany relations
suppose we have two models like this: class User(models.Model): name = models.CharField(max_length=255) date_joined = models.DateField() class Group(models.Model): title = models.CharField(max_length=255) users = models.ManyToManyField(User) we get a queryset of users: user_qs = User.objects.filter(date_joined__range=['2022-01-01', '2022-01-05']) how can I get the list of Group objects that have all users of user_qs in their users? django==3.2 -
Filter foreign key in DetailView Django
I ran into a problem with the queryset query, I need to display certain tags for each article that are related to this article. Each article has tags associated with the article id. model.py class NewsDB(models.Model): title = models.CharField('Название',max_length=300) text = models.TextField('Текст статьи') img = models.ImageField('Фото',upload_to='News',null='Без фото') avtor = models.ForeignKey('Journalist', on_delete=models.PROTECT) date = models.DateField() def __str__(self): return self.title class Meta: verbose_name = 'News' verbose_name_plural = 'News DataBase' class Hashtags(models.Model): News=models.ForeignKey('NewsDB',on_delete=models.PROTECT) Hashtag=models.CharField('Хештег',max_length=150,null='Без темы') def __str__(self): return self.Hashtag view.py class Show_post(DetailView): model = NewsDB template_name = 'navigation/post.html' context_object_name = 'newsDB' def get_context_data(self,**kwargs): hashtags = super(Show_post,self).get_context_data(**kwargs) hashtags['hashtags_list'] = Hashtags.objects.filter(News=self.pk) return hashtags