Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
hwo to fetch upper data and then delete in one action in Django?
I just want to fetch the upper data only and then delete it in one action. I tried this code: `def Data(request): data = Plan.objects.get(id = 1) data.delete() context = {'data':data} return render(request,'data.html',context)` But didn't work. see Database column -
Django with sockets io for Texas hold'm poker game
is it possible to create a poker game with django back end and socket io (front end using vanilla javascript) if no what is the best alternative -
Using custom fonts in TinyMCE API for editor in django admin
I am trying to use TinyMCE API in Django admin for blog post editing. It is working flawlessly. However, now I want to add custom fonts to my editor. As per tinymce documentation for adding custom fonts i have followed all steps but still cannot figure out what is wrong. Step-1: Add fonts as per menu option admin/base.html: font_formats:"Andale Mono=andale mono,times; ........ ; Montserrat = Montserrat , sans-serif",` Step-2: Import fonts in tinymce admin/base.html: {% extends "admin/base.html" %} {% load static %} {% block footer %} tinymce.init({ .... content_css: "{% static "TinyMCE/style.css" %}", content_style:"@importurl('https://fonts.googleapis.com/css2family=Montserrat:ital,wght@0,400;0,600;1,400&display=swap');", .... {% endblock %} TinyMCE/style.css @import url('https://fonts.googleapis.com/css2family=Montserrat:ital,wght@0,400;0,600;1,400&display=swap'); snapshot: the custom font is added in the dropdown menu 'Monstserrat' Step3: Import the font on the page admin/base.html {% block extrahead %} <style> @import url('https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,400;0,600;1,400&display=swap'); * {font-family : 'Montserrat', sans-serif;} </style> {% endblock %} snapshot: the custom font changes in dropdown from fallback font to 'Monstserrat' Step4: Import the font on any published pages I am using tailwind in my project and my default font is Monstserrat which is perfectly working over the site style.css @import url('https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,400;0,600;1,400&display=swap'); body{ font-family: Montserrat, sans-serif; } Problem: Although i see the custom font 'Montserrat' in the dropdown on tincymce editor but when … -
Reach django user from javascript template
I'm following Corey Shafer's django guide and I have run into some problems he doesn't cover. I'm trying to make profiles that are visible to everyone but only editable by the user itself. In my views.py I have a boolean "editable", and this part is working. However, I can't get that boolean to my js file... Code below. const button = document.getElementById("button"); button.addEventListener("click", () => { const form = document.getElementById("form"); var bool = {{ user.profile.editable }}; if(form.style.display == "none" && bool){ form.style.display = "block"; }else{ form.style.display = "none"; } }); When I inspect it in the browser it gives me a syntaxError because I'm using '{'. And here is the code from my views.py: @login_required def profile(request, username): user = User.objects.get(username=username) Profile.objects.get_or_create(user=request.user) editable = False if request.method == "POST": user_form = UserUpdateForm(request.POST, instance=request.user) profile_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, f"Profile successfully updated!") return redirect("profile") else: user_form = UserUpdateForm(instance=request.user) profile_form = ProfileUpdateForm(instance=request.user.profile) context = { "user_form": user_form, "profile_form": profile_form } if request.user == user: editable = True return render(request, "users/profile.html", context) Any help would be much appreciated. Thanks in advance! -
Django & AJAX file upload
When using POST request with AJAX in Django 4.0.1 I can't reach the file from the backend using request.FILES. The form used is pretty simple so I can't spot any typos etc. HTML: <form id="snipForm" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" id="multiFiles" name="files[]" multiple="multiple"/> <button id="upload">Upload</button> </form> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> JavaScript: (sorry for quite a long code sample but I can't shrink it more) $(document).ready(function (e) { $('#upload').on('click', function (event) { //Prevent page from reloading event.preventDefault() var form_data = new FormData(); // check if there is any file selected var ins = document.getElementById('multiFiles').files.length; if(ins == 0) { $('#msg').html('<span style="color:red">Select at least one file</span>'); return; } // add all files for (var x = 0; x < ins; x++) { form_data.append("files[]", document.getElementById('multiFiles').files[x]); } // obtain CSFR token csrf_token = $('input[name="csrfmiddlewaretoken"]').val(); // set the headers headers = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest', 'X-CSRFToken': csrf_token}; $.ajax({ type: 'POST', url: '/docs/', // point to server-side URL dataType: "json", ContentType: "application/x-www-form-urlencoded", cache: false, processData: false, headers: headers, data: form_data, success: function (response) { // display success response console.log("successssssssssssss") }, error: function (response) { console.log("NOPEEEEEE") } }); }); }); views.py: from django.views.decorators.csrf import ensure_csrf_cookie @ensure_csrf_cookie def generate(request): is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' if request.method == 'POST' and is_ajax: files … -
Search with Django (for Tags)
I'm doing a 3-part search. (1st username 2.caption 3.tag) only the 3rdtag search doesn't work. (The error I get when I add the tag -Related Field got invalid lookup: icontains) I also tried using the Tag model, but it didn't work, can you help? enter code here myviews.py @login_required(login_url="login") def UserSearch(request): query = request.GET.get("q") context = {} specailAd= Ad.objects.order_by('-dateAd') ads = list(Ad.objects.all()) oneAd = random.choice(ads) post_items = Post.objects.all().order_by('-posted') if query: post_items = post_items.filter(caption__icontains = query) if query: post_items = post_items.filter(tags__icontains = query) if query: users = User.objects.filter(Q(username__icontains=query)) #Pagination paginator = Paginator(users, 6) page_number = request.GET.get('page') users_paginator = paginator.get_page(page_number) context = { 'users': users_paginator, 'post_items':post_items, 'specailAd':specailAd, 'oneAd':oneAd, } template = loader.get_template('direct/search_user.html') mymodels.py class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) content = models.ManyToManyField(PostFileContent, related_name='contents') caption = models.TextField(max_length=1500, verbose_name='Caption') posted = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(Tag, related_name='tags') user = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField( User, related_name='like', default=None, blank=True) like_count = models.BigIntegerField(default='0') def get_absolute_url(self): return reverse('postdetails', args=[str(self.id)]) def __str__(self): return str(self.id) class Tag(models.Model): title = models.CharField(max_length=75, verbose_name='Tag') slug = models.SlugField(null=False, unique=True) class Meta: verbose_name='Tag' verbose_name_plural = 'Tags' def get_absolute_url(self): return reverse('tags', args=[self.slug]) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) return super().save(*args, **kwargs) -
why i am getting no reverse match error after adding the url in home.html file?
I am getting the error after adding the URL in the home.html file. I migrated before running the program. I used commands to migrate. i.e., python manage.py migrate. 2. python manage.py makemigrations app_name. Django version I am using is 4.0.6. Thank you Settings.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIR=os.path.join(BASE_DIR,"templates") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-d4@4fwcpkk$6a8ylqjmyhp-9%22t^aizetygwkxzw9s_wu5$&2' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'g6app', ] 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', ] ROOT_URLCONF = 'g6.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR,], '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', ], }, }, ] urls.py from django.contrib import admin from django.urls import path from g6app.views import V1,V2 urlpatterns = [ path('admin/', admin.site.urls), path("",V1.as_view(),name="v11"), path("index/<int:pk>",V2.as_view(),name="index_detail1"), ] admin.py from django.contrib import admin from . models import T1 # Register your models here. admin.site.register(T1) models.py from django.db import models from django.urls … -
Sending email verfications works locally but doesnt work on heroku in my django app
i am using an email verfication using links once the user register an email is sent to the user to activate their account this works fine in my local app when i run it but after i deployed the app to heroku even tho i set the config vars to be the same as my enviroment vars i still get this error (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError t19-20020a05622a181300b0031e9b5ead3asm2297749qtc.76 - gsmtp', 'samdjangoemail@gmail.com') this error indicates that for some reason heroku cant access the gmail even tho i set an app password for it and this is my settings for heroku DEFAULT_FROM_EMAIL = os.environ.get('EMAIL_FROM_USER') EMAIL_FROM_USER = os.environ.get('EMAIL_FROM_USER') EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = os.environ.get('EMAIL_FROM_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') EMAIL_USE_SSL = True EMAIL_PORT = 465 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = '/static/' # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' CRISPY_TEMPLATE_PACK = 'bootstrap5' # heruko settings cwd = os.getcwd() if cwd == '/app' or cwd[:4] =='/tmp': import dj_database_url DATABASES = { 'default' : dj_database_url.config(default='postgres://localhost') } # honor the 'X-Forward-Proto' header for request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARD_PROTO', 'https') DEBUG = False #static asset configuration BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = 'staticfiles' STATICFILES_DIR = (os.path.join(BASE_DIR, 'static')) … -
I have uploaded a django project on ngnix server. I want the api requests to go to subdomain.example.com but it's going to 0.0.0.0:8083 instead
Nginx setup: server { listen [::]:8005 ssl; # managed by Certbot listen 8005 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/qatekinternal.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/qatekinternal.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot server_name subdoamin.example.com; location /static { alias /home/example/jrms_server/static; } location /media { alias /home/example/jrms_server/media; add_header Access-Control-Allow-Origin *; } location / { proxy_pass http://0.0.0.0:8083; proxy_http_version 1.1; } } Gunicorn config file: command = '/home/example/jrms_prod_env/bin/gunicon' pythonpath = '/home/qatekadmin/jrms_server' bind = ['0.0.0.0:8083'] workers = 9 Limit_request_line = 8190 Project settings.py file: https://gist.github.com/salmanc2/e0a00d27945a2a93863c0822ab0a91b1 Project api.js file: https://gist.github.com/salmanc2/dabd163b091478bd3567518224e8e1a8 I have used the address "https://subdomain.example.com:8005"; for my APIs but after uploading to server they are calling at 0.0.0.0:8083 instead. -
BeautifulSoup4 Scraping doesn't work when I try to deploy
In my Django system I use django-bs4 for scraping. It works well on my local host but when I deploy it on Pythonanywhere.com it beautifulsoup doesn't working. On Pythonanywhere it returns None when I try to scrape some HTML. It works on local but why it doesn't work on Pythonanywhere? -
module not found when using include in django
I'm trying to use include in my app following the tutorial here - https://www.w3schools.com/django/django_views.php it seems that when I run the server using this configuration- urlpatterns = [path('members/', include('mimi.urls')), path('admin/', admin.site.urls),] I get ModuleNotFoundError: No module named 'mimi'. I've attached a screenshot of my Pycharm project folder as it is now. I don't understand what I'm doing wrong. It seems to fail to recognize anything outside the web_questions folder, but I can't find a way to give it the absolute path. I'm running the server using this command line - py web_questions/manage.py runserver Help! Karin. -
How can I replace part of url in redirecting?
I have some problems in redirecting urls in my Django app. This is my urls.py: urlpatterns = [ path('Stu_SignUp/step1/', views.new_student, name='new_student'), path('Stu_SignUp/step2/', views.comPnew_student, name='comPnew_student')] Now I want to change part of url from /step1/ to /step2/. These are my views.py app: def new_student(request): if request.method == "POST": Person.objects.create(p_fName=request.POST['fName'], p_lName=request.POST['lName'], p_SSN=request.POST['SSN'], p_birthDate=request.POST['birthdate'], p_phoneNum=request.POST['phoneNum']) return redirect('Stu_SignUp/step2/') else: return render(request, 'signUp_student.html', context={'person': Person}) def comPnew_student(request): if request.method == "POST": if request.method['password'] == request.method['conf_Pass']: update_person = Person.objects.get(Person_ID=Person.objects.last().id) update_person.p_Email = request.POST['email'] update_person.p_Password = request.POST['password'] return redirect('Stu_SignUp/step2/') else: return render(request, 'signUp_student2.html', context={'person': Person}) Html Template is signUp_student.html and signUp_student2.html: Page Number 1: <form action="{% url 'new_student' %}" method="post"> {% csrf_token %} <label for="firstName">First Name<br> <input type="text" name="fName"> </label><br> <label for="lastName">Last Name<br> <input type="text" name="lName"> </label><br> <label for="firstName">SSN Code<br> <input type="text" name="SSN"> </label><br> <label for="birthdate">Birthdate <br> <input type="date" name='birthdate'> </label><br> <label for="phoneNumber">Phone Number<br> <input type="text" name='phoneNum'> </label> <br><br> <button type="submit">Sign up</button> </form> Page Number 2: <form action="{% url 'comPnew_student' %}" method="post"> {% csrf_token %} <label for="Email">Email<br> <input type="text" name="email"> </label><br> <label for="password">Password<br> <input type="text" name="password"> </label><br> <label for="confPassword">Confirm Password<br> <input type="text" name="conf_Pass"> </label><br> <br><br> <button type="submit">Sign up</button> </form> I'll appreciate your help. -
when I try to search I get this error : Related Field got invalid lookup: tag
views.py def home(request): WAllPAPER_PER_PAGE = 15 WALL = Wallpaper.objects.all() from django.core.paginator import EmptyPage, Paginator from django.db.models import Q qd = request.GET.copy() qd.pop('page', None) querystring = qd.urlencode() #link formatting for ordering ordering =request.GET.get('ordering', "") #link formatting for sorting search = request.GET.get('search', "") if search: wallpapers = Wallpaper.objects.filter(Q(name__icontains=search) | Q(category__category_name__icontains=search) | Q(tags__tag__icontains=search)).distinct().order_by('-pk') WALL = None else: wallpapers = Wallpaper.objects.all().order_by('-pk') if ordering: wallpapers = wallpapers.order_by(ordering) page = request.GET.get('page', 1) wallpaper_paginator = Paginator(wallpapers, WAllPAPER_PER_PAGE) try: wallpapers = wallpaper_paginator.page(page) except EmptyPage: wallpapers = wallpaper_paginator.page(wallpaper_paginator.num_pages) except: wallpapers = wallpaper_paginator.page(WAllPAPER_PER_PAGE) context = {'querystring': querystring, "wallpapers": wallpapers, 'page_obj': wallpapers, 'is_paginated': True, 'paginator': wallpaper_paginator, 'WALL': WALL} return render(request, "Wallpaper/Home.html", context) models.py class Tags(models.Model): tag = models.CharField(max_length=100) def __str__(self): return self.tag class Category(models.Model): category_name = models.CharField(max_length=100) def __str__(self): return self.category_name class Wallpaper(models.Model): name = models.CharField(max_length=100, null=True) size = models.CharField(max_length=50, null=True) pub_date = models.DateField('date published', null=True) resolution = models.CharField(max_length=100, null=True) category = models.ManyToManyField(Category) tags = TaggableManager() Device_Choices = [ ('PC', 'pc'), ('mobile', 'mobile') ] Devices = models.CharField(max_length=20,choices=Device_Choices, default= 'PC') image = models.ImageField(upload_to='Wallpaper/Images/', default="") def __str__(self): return self.name error File "C:\Users\Atharva thaware\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\q uery.py", line 1339, in build_filter raise FieldError('Related Field got invalid lookup: {}'.format(lookups[0])) django.core.exceptions.FieldError: Related Field got invalid lookup: tag -
Why django RowNumber() does not start ordering from 1
I'm trying to use RowNumber to get sequential ordering of queryset objects (1,2,3...) qs = self.filter_queryset(self.get_queryset()) qs = qs.annotate( row_number=Window( expression=RowNumber() ) ) but when I iterate over qs and print objects, ordering starts from 4 for q in qs: print(q.row_number) result is: 4,1,2,5,6,3,10... I have no idea why this happens and how can I fix it. any help? thank you -
How to make (if & else) for internal values in django orm?
I am making models for my store project and I wanted to know why the code I wrote is wrong? And how can I write correctly? I want only the time when a product is sold from me to be recorded in the database. class Product(models.Model): product_type = models.ForeignKey(ProductType, on_delete=models.PROTECT, related_name='products_types') upc = models.BigIntegerField(unique=True) title = models.CharField(max_length=32) description = models.TextField(blank=True) category = models.ForeignKey(Category, on_delete=models.PROTECT, related_name='products') brand = models.ForeignKey(Brand, on_delete=models.PROTECT, related_name='products') soled = models.BooleanField(default=False) if soled == True: soled_time = models.DateTimeField(auto_now_add=True) created_time = models.DateTimeField(auto_now_add=True) modified_time = models.DateTimeField(auto_now=True) def __str__(self): return self.title I hope that my problem will solve the question of many friends <3 -
'ManyRelatedManager' object has no attribute 'save'
I've got the same problem as this post. I tried the solution from cshelly, but my adoption fails on the last line given (the save). The difference is my code uses model based views and forms and has a polymorphic model. It's throwing an exception on the last line, where a save of the append to the manytomany field. I use whatever django gives as the through table. I can see the value being added. If I comment out the offending line, the match object has everything from the form (including the objects selected on the form from the other (in this case, the student) manytomany field. All help is much appreciated. Here's the view: if form.is_valid(): instance = form.save(commit=False) current_user = self.request.user instance.lvm_affiliate = current_user.affiliate instance.save() if pt == 'tutor': person = Tutor.objects.get(id=pk) print("before ", vars(instance)) print("student ", instance.student.all()) print("tutor ", instance.tutor.all()) instance.tutor.add(person.id) print("after ", vars(instance)) print("student ", instance.student.all()) print("tutor ", instance.tutor.all()) instance.save() instance.tutor.save() here's the output: before {'_state': <django.db.models.base.ModelState object at 0x000001E84D5CEAA0>, 'id': 46, 'lvm_affiliate_id': 34, 'match_status_id': 3, 'date_started': datetime.date(2022, 7, 23), 'date_dissolved': None, 'comments': ''} student <PolymorphicQuerySet []> tutor <PolymorphicQuerySet []> after {'_state': <django.db.models.base.ModelState object at 0x000001E84D5CEAA0>, 'id': 46, 'lvm_affiliate_id': 34, 'match_status_id': 3, 'date_started': datetime.date(2022, 7, 23), … -
how to update feed in django using feedparser?
i am lookig for a way to update rss feeds using feedparser. i tried: in models.py class Feed(models.Model): title = models.CharField(max_length=200, unique=True) url = models.URLField(unique=True) is_active = models.BooleanField(default=True) def __str__(self): return self.title def load_articles(self): new_list = feedparser.parse(self.url) for entry in new_list.entries: try: Article.objects.create(entry) except IntegrityError: pass class Article(models.Model): feed = models.ForeignKey('Feed', on_delete=models.CASCADE) title = models.CharField(max_length=200) url = models.URLField() description = models.TextField() publication_date = models.DateTimeField() and i created managment command from django.core.management.base import BaseCommand, CommandError from news.models import Feed, Article art = Article() class Command(BaseCommand): help = 'updates feeds' def handle(self, *args, **kwargs): Feed.load_articles(art) self.stdout.write("feeds updated") command doesn't return any error and prints feeds updated but i don't see any effect. -
Why can't I save my form data into a model db?
When I try to save the info inputted into the form, I get the ValueError: Cannot assign "<class 'auctions.models.User'>": "Listing.user" must be a "User" instance. I think that this may be because the model field Listing.user is a foreign key between the Listing model and the User model. Even when I change Listing.user = User to Listing.user = User() (includes brackets), it returns the ValueError: save() prohibited to prevent data loss due to unsaved related object 'user'. So how do I add who the current user is to the model field Listing.user? models.py: class User(AbstractUser): pass class Listing(models.Model): ... user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) views.py: def save_new(request): if request.method == 'POST': form = NewListing(request.POST) if form.is_valid(): obj = Listing() ... obj.user = User # this returned the first ValueError # obj.user = User() - this returned the second ValueError obj.save() return HttpResponseRedirect('/') -
Django Multiple Forms from related Models
I am pretty new to Django and have come stuck on how to approach an issue I have with collecting Data via multiple forms. I have the following models, the first being where I store data of an asset: class Model_AssetData(models.Model): UU_Project_Number = models.ForeignKey(Model_Project, null=True, on_delete=models.CASCADE) Site_Code = models.CharField(blank=True, null=True,max_length=5) Facility = models.ForeignKey(Model_Facility, null=True, on_delete=models.CASCADE) Facility_Number = models.IntegerField(blank= False, null= True,) Process = models.ForeignKey(Model_Process, null=True, on_delete=models.CASCADE) Process_Number = models.IntegerField(blank= False, null= True) Arrangement = models.ForeignKey(Model_Arrangement, null=True, on_delete=models.CASCADE ) Arrangement_Number = models.IntegerField(blank= False, null= True) Asset_Group = models.ForeignKey(Model_AssetLocation, null=True, on_delete=models.CASCADE ) Asset_Group_Number = models.IntegerField(blank= False, null= True) Asset_Number = models.CharField(blank=False, null=False,max_length=50) Equipment_Group_Identifiier = models.ForeignKey(Model_EGI, null = True, on_delete=models.CASCADE) Engineering_Design_Identifier = models.ForeignKey(Model_EDI, null = True, on_delete=models.CASCADE) ITR = models.ForeignKey(Model_ITR, null = True, on_delete=models.SET_NULL) def __str__(self): return self.Asset_Number def save(self, *args, **kwargs): # Only generate key on creating if it was not provided if not self.id: # Use f-string to concatenate the asset code into the Database self.Asset_Number = f'{self.UU_Project_Number}-{self.Site_Code}-{self.Facility} {self.Facility_Number}-{self.Process}{self.Process_Number}-{self.Arrangement} {self.Arrangement_Number}-{self.Asset_Group}{self.Asset_Group_Number}' super().save(*args, **kwargs) Then I am trying to collect basically some answers to questions to ensure certain things have been checked when the asset was installed: This model is a reference to what questions need to be asked for a particular asset: … -
Django Sessions, SESSION_EXPIRE_AT_BROWSER_CLOSE does not change session expire date
I have set SESSION_EXPIRE_AT_BROWSER_CLOSE = True in my settings.py and it works fine. The problem is that when the user closes the browser, he is logged out just fine but in the session instance related to that user the expire_date field does not change. I have a piece of code for listing all active sessions. from django.contrib.sessions.models import Session from django.utils import timezone sessions = Session.objects.filter(expire_date__gte=timezone.now()) uid_list = [] for session in sessions: data = session.get_decoded() uid_list.append(data.get('_auth_user_id', None)) print("#", uid_list[-1]) The output of the code contains the user id of the logged out user. The Session Base Class is: class AbstractBaseSession(models.Model): session_key = models.CharField(_('session key'), max_length=40, primary_key=True) session_data = models.TextField(_('session data')) expire_date = models.DateTimeField(_('expire date'), db_index=True) objects = BaseSessionManager() class Meta: abstract = True verbose_name = _('session') verbose_name_plural = _('sessions') def __str__(self): return self.session_key @classmethod def get_session_store_class(cls): raise NotImplementedError def get_decoded(self): session_store_class = self.get_session_store_class() return session_store_class().decode(self.session_data) The question is that how do I know if a user has closed the browser and logged out. -
While migrating default database model assigned for another database is being migrated
I was working on two database for my Django project. I followed online Django documentation and made work two sqlite database at the same time for different purposes but I ended up having one issue which is while migrating default database the model Game that I created for 'games.db' is also being migrated to 'default.sqlite'. I have added my code below. Kindly help me fix this issue as I have tried multiple things but nothing worked out. Project/settings.py ------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'games': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'games.db'), }, } DATABASE_ROUTERS = ( 'Games.dbrouters.GamesDBRouter', ) Games/models.py --------------- from django.db import models from django.urls import reverse STATUS = ( (1, "Publish"), (0, "Draft") ) class Game(models.Model): title = models.CharField(max_length=2000, unique=True) slug = models.SlugField(max_length=2000, unique=True) image = models.CharField(max_length=2000, unique=True) overlay = models.CharField(max_length=2000, blank=True) updated_on = models.DateTimeField(auto_now=True) story_p = models.TextField(blank=True) story_span = models.TextField(blank=True) about_p = models.TextField(blank=True) about_span = models.TextField(blank=True) screenshot_1 = models.CharField(max_length=2000, blank=True) screenshot_2 = models.CharField(max_length=2000, blank=True) screenshot_3 = models.CharField(max_length=2000, blank=True) screenshot_4 = models.CharField(max_length=2000, blank=True) gameplay = models.CharField(max_length=2000, blank=True) download_android = models.CharField(max_length=2000, blank=True) download_ios = models.CharField(max_length=2000, blank=True) download_windows = models.CharField(max_length=2000, blank=True) download_linux = models.CharField(max_length=2000, blank=True) download_mac = models.CharField(max_length=2000, blank=True) torrent_android = models.CharField(max_length=2000, blank=True) torrent_ios … -
How to serialise Generic Relation in DrangoRestFramework
I have these serialisers to work with Generic Foreign Key in DRF. class GenericContactsSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=False) class Meta: model = GenericContacts fields = ( 'id', 'email', 'phone', 'ext', 'contact_name', 'fax', 'producer_email', 'producer_phone', 'producer_phone_ext', 'producer_contact_name', ) class CompanyCreateOrUpdateSerializer(serializers.ModelSerializer): company_contacts = GenericContactsSerializer(many=True) class Meta: model = Company fields = ( "id", "company_contacts", "company_name", ) def _manage_company_contacts(self, instance, contacts): contact_instances = [] c_type = ContentType.objects.get(model='company') for contact in contacts: contact_instances.append(GenericContacts(**contact, object_id=instance.id, content_type=c_type)) GenericContacts.objects.bulk_create(contact_instances) instance.refresh_from_db() def create(self, validated_data): company_contacts = validated_data.pop('company_contacts', []) instance = super().create(validated_data) self._manage_company_contacts(instance, company_contacts) return instance def update(self, instance, validated_data): company_contacts = validated_data.pop('company_contacts', []) instance = super().update(instance, validated_data) instance.company_contacts.all().delete() self._manage_company_contacts(instance, company_contacts) return instance My JSON to frontend is looks like: { "id": 1, "company_contacts": [ { "id": 14, "email": "lol@mail.com", "phone": "999-000-1231", "ext": "321", "contact_name": "Tom", "fax": null, "producer_email": "", "producer_phone": "", "producer_phone_ext": null, "producer_contact_name": null }, { "id": 13, "email": "iliass@mail.com", "phone": "111-122-2121", "ext": "123", "contact_name": "John", "fax": "", "producer_email": "ins@mail.com", "producer_phone": "241-245-1245", "producer_phone_ext": "333", "producer_contact_name": "Max" } ], "company_name": "Company" } And incoming request JSON is looks like: { "company_contacts": [ { "id": 13, "email": "iliass@mail.com", "phone": "111-122-2121", "ext": "123", "contact_name": "John", "fax": "", "producer_email": "ins@mail.com", "producer_phone": "241-245-1245", "producer_phone_ext": "333", "producer_contact_name": "Max" }, { "email": "somemail@mail.com", "phone": "333-333-3333", … -
¿Cómo comparar cada uno de los elementos de una lista con ellos mismos?
Tengo una lista en Python lista = [1,2,3,4,5,6,7,8,9] Quiero recorrer la anterior lista , pero en cada iteración comparar esa iteración con todos los demás elementos de la misma lista (incluyendo al valor de la iteración actual) para realizar una consulta a la base de datos y verificar si existe un valor , de lo contrario regresaría cero (0) suponiendo que estamos iterando en la lista: para la primera iteración que es el 1 ahí se debe iterar de nuevo todos los elementos de la misma lista para realizar unas comparaciones y la consulta mencionada anteriormente , y así seguido con la iteración 2, 3, 4 etc. Lo ideal es que esas comparaciones no llenen la memoria RAM o se ponga lento el programa, ya que estoy trabajando con Django 4. por eso no he intentado realizar bucles for Agradezco cualquier aporte que me ayude a solucionar este problema. Muchas gracias -
social-auth-app-django problem with DjangoStrategy
After installing social-auth-core social-auth-app-django on Django 4.0.6 and including to the INSTALLED_APPS and made everything on documents I got this error 'DjangoStrategy' object has no attribute 'get_backend' This error happens when I click on login link on this URL http://localhost/login/google-oauth2/ In settings.py I have this backends AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) -
change Django default URL
first sorry for my bad English When I run my server, I want to Django redirect me to http://127.0.0.1:8000/home instead of http://127.0.0.1:8000. what should I do?