Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Serpy serializer django model JsonField
I am using serpy to serialize my model, so my model has a JSONField containing list of dict. Here is my model: class Section(models.Model): title = models.CharField(max_length=255, null=False) item_count = models.IntegerField(default=0) # The JSON field contents = models.JSONField(blank=True, null=True) I am trying to use serpy.DictSerializer to serialize the contents field but it results in empty dict {} . This is my serializer: class SectionSerializer(serpy.Serializer): title = serpy.StrField() item_count = serpy.IntField() data = serpy.MethodField() def get_data(self, obj): return serpy.DictSerializer(obj.contents, many=True).data As contents is a list of dicts, I have used many=True, But still it is not helping. -
What does this symbol mean "[...]" in docstrings?
I've seen this multiple times now in different python documents. For example: python code The above is from a website that I just saw today and the rest is code written in Django. I see this symbol being regularly used in different documentations. -
Alpine.js x-bind not applying after an HTMX swap
I have an element that is in the initial page load and updates after form post through an HTMX out of bounds swap. On initial load the x-bind formats as expected. After the swap the values from the swapped element display as expected using x-text. The x-bind always fails to apply the formatting that should trigger when staffCount < shiftNeed. When it should apply it quickly flickers immediately after the swap but then goes away. Same flicker is not present when it should not apply. Element on initial page load <tr x-data="{ shiftNeed: {{ day_need }} }"> <td class="fw-bold">Day</td> <td class="fw-bold text-center" x-text="shiftNeed"></td> {% for i, val in day_list|zip:day_staffing %} <td> <div id="dayCount{{ i }}" x-data="{ staffCount: {{ val }} }" x-text="staffCount" x-bind:class="{ 'bg-danger': staffCount < shiftNeed }" ></div> </td> {% endfor %} </tr> Partial template swapped in {% include "schedule/components/schedule_shift_button.html" %} <div id="{{ shift.time_of_day_label|lower }}Count{{ shift.day_num }}" class="text-center rounded" hx-swap-oob="true" x-data="{ staffCount: {{ shift.staff_count }}}" x-text="staffCount" x-init="console.log(staffCount < shiftNeed)" x-bind:class="{ 'bg-danger': staffCount < shiftNeed }" ></div> I added logging statements on the x-init to inspect output, console always displays the expected values of staffCount and shiftNeed and evaluates the criteria used in the x-bind as expected. -
Why when I create an enviroment with anaconda in Visual Studio Code and I try to activate it, shows me an error
I try to activate the env that I already created and everything fine, but when I tried the command "conda activate whynotdata" it shows me this error: PROGRAMACION\Data_base_whynot> conda activate whynotdata usage: conda-script.py [-h] [--no-plugins] [-V] COMMAND ... conda-script.py: error: argument COMMAND: invalid choice: 'activate' (choose from 'clean', 'compare', 'config', 'create', 'info', 'init', 'install', 'list', 'notices', 'package', 'remove', 'uninstall', 'rename', 'run', 'search', 'update', 'upgrade', 'build', 'convert', 'debug', 'develop', 'doctor', 'index', 'inspect', 'metapackage', 'render', 'skeleton', 'verify', 'token', 'pack', 'server', 'env', 'content-trust', 'repo') When I create it with the anaconda prompt everything works fine but in Visual Studio Code I can't complete it, and I want to create my env on the folder that I have on Visual Studio, I am a begginer in the back-end, I am of autodidact learning. Thank you I am trying to create an env on a folder that I create and then install django, I want to use Anaconda to create the project but it didn't work and is rare because on the config of my sistem I added the path to the environments of windows, of the anaconda3 and anaconda3\scripts -
Django cap a DateField value in the database
Sorry I am very new to Django. I have date of birth (DOB) as a field in my model. I use the DOB to calculate the age and get some values from other dataset. class Account(AbstractBaseUser): first_name = models.CharField(max_length=50) dob = models.DateField(blank=True, null=True) The age cannot be higher than 120 years so I raise a ValidationError with the registration and update profile forms whenever they enter a DOB of more than 120 years ago. def clean(self): cleaned_data = super(RegistrationForm, self).clean() dob = self.cleaned_data.get('dob') age = (date.today() - dob).days / 365 if age > 120: raise forms.ValidationError('Sorry but profiles cannot be registered with more than 120 years old due to scientific data unavailability.') elif age < 0: raise forms.ValidationError('Date of birth is in the future. Please enter valid birth date.') However, what if they register as born 119 years ago. In 1 or 2 years, the age would be 121 and my code will fail. Is there a way to always cap the value of the DOB in my database so the DOB is always maximum 120 years old? I checked the documentation for DateField but there is no reference to MinValueValidator as in the case of IntegerField. -
Ingress health check failing on Django GKE Deployemnt
I am deploying a frontend (Nuxt) and a backend (Django) using GKE Autopilot. A CI/CD pipeline has been set up from github to GKE. The frontend gets deployed and easily viewable on xpresstracker.app while the backend spits out server error 501 on backend.xpresstracker.app. Below is the related configurations and error; Error message prodservice.yaml apiVersion: v1 kind: Service metadata: name: prod-xpressbackend-service spec: selector: app: prod-xpressbackend ports: - protocol: TCP port: 8000 targetPort: 8000 type: NodePort prodmanagedcert.yaml apiVersion: networking.gke.io/v1 kind: ManagedCertificate metadata: name: prod-managed-cert spec: domains: - xpresstracker.app - backend.xpresstracker.app prodingress.yaml apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: prod-ingress annotations: kubernetes.io/ingress.global-static-ip-name: xpresstrackerip networking.gke.io/managed-certificates: prod-managed-cert kubernetes.io/ingress.class: "gce" labels: app: prod-xpressbackend spec: rules: - host: xpresstracker.app http: paths: - path: / pathType: Prefix backend: service: name: prod-xpressfrontend-service port: number: 3000 - host: backend.xpresstracker.app http: paths: - path: / pathType: Prefix backend: service: name: prod-xpressbackend-service port: number: 8000 Deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: prod-xpressbackend-deployment labels: app: prod-xpressbackend spec: replicas: 1 selector: matchLabels: app: prod-xpressbackend template: metadata: labels: app: prod-xpressbackend spec: containers: - name: prod-xpressbackend-container image: someimage:production imagePullPolicy: Always resources: requests: memory: "200Mi" cpu: "0.2" limits: memory: "512Mi" cpu: "0.5" ports: - containerPort: 8000 env: - name: SECRET_KEY valueFrom: secretKeyRef: name: proddatabasecredentials key: SECRET_KEY - … -
Custom Django Admin Page/View
Basically I'm trying to create a custom admin web page, like a custom a view. Ideally what I want is something where like once you log in to the admin page, there would be a link somewhere like under the list of models that would redirect you to this admin center. I have a somewhat working version currently, but I would like to have it redirect to a new URL like “ /admin/social/edit/ “ instead and not just render context into the template. I’ve done a ton of googling and I just keep coming across things like “custom admin actions” which is not per se what I’m looking to do. Any help is appreciated. Thank you. -
Trying to delete an item from webpage rendered by django results in all items below it to also be deleted
In my project I have a cart application that displays any items the user decided to add to the cart. Template: {% extends '../main.html' %} {% load static %} {% block title %}Cart Summary{% endblock %} {% block content %} <main class = "pt-5"> <div class = "container"> <h1 class = "h5">Shopping Cart</h1> {% for item in cart %} {% with product=item.product %} <div data-index = "{{product.id}}" class = "row g-3 product-item"> <div class = "col-md-5 col-lg-5 order-mg-first"> <img class = "img-fluid mx-auto d-block" width = "200px" alt = "Responsive image" src = "{{ product.image.url }}" /> </div> <div class = "col-md-7 col-lg-7 ps-md-3 ps-lg-5"> <h1 class="mb-0 h4">{{ product.title }}</h1> <p><span class="lead">{{ product.author }}</span> (Author)</p> <p>{{ product.description|slice:":355" }}...</p> <div class="border"> <div class="col border-bottom"> <div class="row p-3"> <div class="col-6">Hardback</div> <div class="col-6 text-end"><span class="h4 fw-bold">{{ product.price }}€</span></div> </div> </div> <div class="col"> <div class="row p-3"> <div class="col-6"> <label for="select">Qty</label> <select id="select{{product.id}}"> <option selected> {{item.qty}} </option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> <button type="button" id = "update-button" data-index = "{{product.id}}" class="btn btn-secondary btn-sm update-button"> Update </button> <button type="button" id = "delete-button" data-index = "{{product.id}}" class="btn btn-secondary btn-sm delete-button"> Delete </button> </div> </div> </div> </div> </div> {% endwith %} {% endfor %} … -
How can I set group permissions that filter pages according to their owners in Wagtail
I am working on a blog with Wagtail and would like to give users access to create their own content in the Wagtail admin. I would like users to be able to log into the Wagtail admin, but only have access to content that they have created themselves. I have tried to generate permissions by group, however there is no default option to limit content by author, so if I give add, edit and publish permissions, a user could edit content created by other users and could unpublish or even delete that content. I would like to know if there is a way to modify the queryset of pages that appear in the Wagtail admin for a specific user. I don't have much experience with Wagtail. So far I have seen some possible solutions but none have seemed viable or adequate. For example, there are some posts here where they propose to create a Parent page for each user, but then you would have to create a group for each user, which doesn't seem like an efficient way to do it. I appreciate any help or suggestions. Here I share some of the relevant code: class BlogIndexPage(Page): max_count = 1 … -
Django: signal doesn't work well with ForeignKey
models.py from django.db import models class Post(models.Model): text = models.TextField() approved = models.BooleanField(default=False) group = models.ForeignKey('bot_users.BotUserGroup', on_delete=models.SET_NULL, null=True, blank=True) from django.conf import settings from django.db import models import os class PostMedia(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='mediafiles') media = models.FileField(upload_to='post_media/', blank=True) absolute_media_path = models.CharField(max_length=255, blank=True) def save(self, *args, **kwargs): self.absolute_media_path = self.get_absolute_media_path() return super().save(*args, **kwargs) def get_absolute_media_path(self): return os.path.join(settings.BASE_DIR, self.media.path) #Post.objects.last().mediafiles.last().absolute_media_path services.py (functions for aiogram bot and django) async def get_post_path(post_id): url = f'http://localhost:8000/api/get_media_urls/{post_id}/' async with aiohttp.ClientSession() as session: async with session.get(url) as response: if response.status == 200: data_list = await response.json() return data_list else: return None async def register_manager(CHAT_ID: str): fake = Faker() username = fake.user_name() password = fake.password() await bot.send_message(CHAT_ID, f'username: {username}\npassword: {password}\nadmin-panel: http://localhost:8000/admin', reply_markup=set_manager_kb()) # async def send_post(instance): # admin_id = '679553167' # await bot.send_message(admin_id, f'{instance}', reply_markup=set_post_kb()) async def send_post(post): message = post.split('\n') user_id = '679553167' post_id = message[0] media = [] media_paths = await get_post_path(post_id) if media_paths: for photo_path in media_paths: if photo_path.lower().endswith(('.jpg', '.jpeg', '.png')): media_type = types.InputMediaPhoto elif photo_path.lower().endswith(('.mp4', '.avi', '.mkv')): media_type = types.InputMediaVideo else: continue photo_file = open(photo_path, 'rb') input_media = media_type(media=types.InputFile(photo_file)) media.append(input_media) media[0]["caption"] = message[1] await bot.send_media_group(chat_id=user_id, media=media, reply_markup=set_post_kb()) photo_file.close() else: await bot.send_message(user_id, message[1], reply_markup=set_post_kb()) signals.py from django.db.models.signals import post_save from django.dispatch import receiver … -
cant create new model object django rest framework
model.py from django.db import models from django.contrib.auth.models import User class Task(models.Model): title = models.CharField(max_length=30) description = models.TextField() deadline = models.DateTimeField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user = models.ForeignKey('auth.User', on_delete=models.CASCADE) def __str__(self): return self.title serializers.py from django.contrib.auth.models import User from .models import Task from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): tasks = serializers.PrimaryKeyRelatedField( many=True, queryset=Task.objects.all()) class Meta: model = User fields = ['id', 'username', 'email', 'tasks'] class AuthSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password'] class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ['id', 'title', 'description', 'deadline', 'created_at', 'updated_at'] views class CreateTask(generics.CreateAPIView): authentication_classes = [authentication.SessionAuthentication] permission_classes = [permissions.IsAuthenticated] queryset = Task.objects.all() serializer_class = TaskSerializer in the command line it says 'null value in column "userid" of relation "srctask" violates not-null constraint', do i have to access the userid by another way and attach it to the model object? -
Django - AttributeError: 'Index' object has no attribute 'constraint_type'
I am using Django 4.2.2 This is a model that is throwing the subject jessage in an error, when I run makemigrations: class AnonymousInteractionMonitor(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name='%(app_label)s_%(class)s_content_types', related_query_name='%(app_label)s_%(class)s_content_type') object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') interaction_type = models.PositiveSmallIntegerField(choices=Engagement.ENGAGEMENT_TYPES, null=False) visitor_ip = models.GenericIPAddressField(db_index=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('visitor_ip', 'content_type', 'interaction_type') constraints = [ models.UniqueConstraint(fields=['visitor_ip', 'content_type', 'interaction_type'], name="idx_visitor_inf" ) ] The constraint is not defined on an Index, so why am I getting this error message, and how do I fix it? -
error during installation of virtual environment
I face with folliowing error when I want to install virtual env: C:\Users\MICROSOFT\Desktop\django_project>virtualenv venv 'virtualenv' is not recognized as an internal or external command, operable program or batch file. How it could be tackled? -
new collation (English_world.1252) is incompatible with the collation of the template database (English_World.1252)
I'm trying to test with Django, pytest-django and PostgreSQL on Windows 11. But I got the error below: psycopg2.errors.InvalidParameterValue: new collation (English_world.1252) is incompatible with the collation of the template database (English_World.1252) Even though I set English_World.1252 to LC_COLLATE and LC_CTYPE in run_sql() as shown below. *I wrote the code below to connect to PostgreSQL in conftest.py following the doc: # "conftest.py" import pytest from django.db import connections import psycopg2 from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT def run_sql(sql): conn = psycopg2.connect(database='postgres', user='postgres', password='admin') conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = conn.cursor() cur.execute(sql) conn.close() @pytest.fixture(scope='session') def django_db_setup(): from django.conf import settings settings.DATABASES['default']['NAME'] = 'copied_postgres' run_sql('DROP DATABASE IF EXISTS copied_postgres') run_sql(""" CREATE DATABASE copied_postgres LC_COLLATE = 'English_World.1252' # Here LC_CTYPE = 'English_World.1252' # Here TEMPLATE postgres""") yield for connection in connections.all(): connection.close() run_sql('DROP DATABASE copied_postgres') And, this is test_get_username() below in test_ex1.py: # "test_ex1.py" @pytest.mark.django_db def test_get_username(): user = User.objects.create_user("test-user") user.username = "John" assert user.get_username() == "John" So, how can I solve the error? -
Django Integrity error at .... null value in column
New to Django, getting a violates not-null constraint, thats preventing it posting to my DB(elephantSQL), I cant seem to get around this issue even when passing the post.id in urls, in the 'buttons' and the view.... Im not sure what I'm doing wrong hopefully someone can point me in the right direction? I have very little experience with this and im trying to learn I have tried a good few things, tho I cant seem to get it to post. HELP!!!! Views def createReview(request): form = ReviewForm() if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): form.save() return redirect('market_posts/') context = {'form': form} return render(request, 'market/review_form.html', context) Models from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator from cloudinary.models import CloudinaryField STATUS = ((0, "Draft"), (1, "Published")) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="market_posts") updated_on = models.DateTimeField(auto_now=True) content = models.TextField() featured_image = CloudinaryField('image', default='placeholder') excerpt = models.TextField(blank=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) likes = models.ManyToManyField(User, related_name='likes', blank=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def number_of_likes(self): return self.likes.count() class Comment(models.Model): comment = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() … -
using mongodb with motor driver and django
i'm creating an App, using async driver(motor) for mongodb. I have a telegram bot app and django framework app. I want my telegram and web apps use same database. When i try to create User via integrated CreateView class, by default django uses it's standart auth processing and adds user to its default databases(sqlite, postgre etc.) But i'd like to use mongodb and use it asyncronous(as i understood djongo is syncronous driver) the ways I see to solve this: 1) separate users' auth data(to standart database) and other data, that'll be fetched and overwritten frequently(to mongo). 2) use standart view(e.g. TemplateView, FormView) and my own form, write MyOwnUserClass with hashing and all necessary methods. Shortly I want to use instruments of Django with mongodb, how can I reach that? Well don't know if this is needed here, a piece of my current code: forms.py: class RegisterUserForm(UserCreationForm): username = forms.CharField email = forms.EmailField password = forms.PasswordInput password_confirm = forms.PasswordInput telegram = forms.CharField(required=False) views.py: class Register(CreateView): template_name = 'AIsite/register.html' form_class = RegisterUserForm success_url = reverse_lazy('login-user') -
Django admin page looks primitive
for reference: i am learning django from this page:- https://www.w3schools.com/django/django_admin.php im using virtual environment and running this on a local machine: http://127.0.0.1:8000/admin/ Expected output Reality please help. i have tried asking in subreddit and discord but im not yet able to find a fix. any help is appreciated -
WARNINGS: ?: (staticfiles.W004) The directory '/var/www/static/' in the STATICFILES_DIRS setting does not exist
Estoy aprendiendo django y me aparece el error WARNINGS: ?: (staticfiles.W004) The directory '/var/www/static/' in the STATICFILES_DIRS setting does not exist. y no me deja realizar cambios en mis archivos estaticos y no se como solucionarlo intente probando con import os y cambiando STATICFILES_DIRS por STATICFILES_DIRS = \[os.path.join(BASE_DIR, "static")\] pero aun nada -
How to limit client IP of a Django app? (Through django and/or PaaS)
I am making a Django app and I wish to enhance the security as well as limit users by making sure only clients only from one IP (say a shared VPN) can access it. I plan to host the app on a PaaS like Digital Ocean App Platform or Heroku. How can I limit the client IP through: Django, to prevent other users from accessing the app, and The PaaS, so that potential attackers don't have access to the platform in the first place? (Hopefully some PaaS has this optiont) -
Model registration in django in admin.py multi model (choicefield selection)
here is my admin.py class ResumeAdmin(admin.ModelAdmin): def get_fields(self, request, obj=None): fields = ['category'] if obj: if obj.category == 'Summary': fields.extend(['summary_title', 'summary_description', 'summary_address', 'summary_phone', 'summary_email']) elif obj.category == 'Education': fields.extend(['edu_title', 'edu_course', 'edu_start_date', 'edu_end_date', 'edu_gpa']) elif obj.category == 'Experience': fields.extend(['exp_title', 'exp_date', 'exp_where', 'ext_explanation', 'exp_project_link']) elif obj.category == 'Projects': fields.extend(['project_title', 'project_description', 'project_link']) elif obj.category == 'Certifications': fields.extend(['cert_title','cert_date', 'cert_where', 'cert_explanation','cert_project_link']) return fields admin.site.register(Resume, ResumeAdmin) and this is my model.py class Resume(models.Model): CATEGORY = ( ('Summary', 'Summary'), ('Education', 'Education'), ('Experience', 'Experience'), ('Projects', 'Projects'), ('Certifications', 'Certifications'), ) # view different fields according to the category category = models.CharField(max_length=20, choices=CATEGORY, default='Projects') class Summary(models.Model): resume = models.ForeignKey(Resume, on_delete=models.CASCADE) summary_title = models.CharField(max_length=100) summary_description = models.TextField() summary_address = models.CharField(max_length=200) summary_phone = models.CharField(max_length=20) summary_email = models.EmailField() # 2 Education option will have title, course, start_date, end_date, GPA class Education(models.Model): resume = models.ForeignKey(Resume, on_delete=models.CASCADE) edu_title = models.CharField(max_length=100) edu_course = models.CharField(max_length=100) edu_start_date = models.DateField() edu_end_date = models.DateField() edu_gpa = models.FloatField() # 3 experience filed will have same as education filed class Experience(models.Model): resume = models.ForeignKey(Resume, on_delete=models.CASCADE) exp_title = models.CharField(max_length=100) exp_date = models.CharField(max_length=100) # it holds the start and end year of the course exp_where = models.CharField(max_length=200) # college or school name ext_explanation = models.TextField() exp_project_link = models.URLField() # 4 projects filed will have … -
Heroku can't find styles.css
Trying to deploy a Django app to Heroku for the first time. When I view the app using Django, everything shows up correctly, but when I run it on Heroku, pieces of the UI are missing. I'm not too familiar with the frontend - this was a group project and I was working on backend - and my team isn't willing to help with deployment, so I'm unable to diagnose any frontend issues. Looking at the Heroku logs, I get this error "Not Found: /static/styles.css" - but there is a styles.css file under static. Does anyone know where the root problem might lie? Under settings.py I have specified this STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'staticfiles')] All functionalities work as expected, I think it has something to do with the base.html file - but this is just a stab in the dark. An example of what it's meant to look like, compared to what it looks like on Heroku. -
Django path not matching with urlpatterns in urls.py
Guys I am not a web developer, I have been learning django for a couple of hours now for my father's small business website and I am hitting a silly error for hours now. the name of the project is mysite and mysite urls.py looks like this from django.contrib import admin from django.urls import include, path urlpatterns = [ path("", include("index.urls")), path("about/", include("about_page.urls")), path("polls/", include("polls.urls")), path("admin/", admin.site.urls), ] mysite's settings.py also includes the correct AppConfig for the app. about_page included. INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'index.apps.IndexConfig', 'about_page.apps.AboutPageConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] about_page's views.py is attached_below from django.shortcuts import render from django.http import HttpResponse from django.template import loader from django.http import Http404 # Create your views here. # return HttpResponse("website under construction !!!") def about_func(request): template = loader.get_template("about/about_page.html") context = { "about":"about_us", } return HttpResponse(template.render(context, request)) about_page's urls.py: from django.urls import path from . import views urlpatterns = [ path("about/", views.about_func, name="about_page"), ] polls and index apps have exact same pattern, i simply don't know why i cannot display about page. -
deploy project on my local machine with Apache
I built a website with Django, installed Apache and made all the adjustments. In addition, I bought a domain from GoDaddy for the site. I want to deploy the site on my computer. The problem is when I try to access the site via the internet I get to a page from GoDaddy with my domain. The steps I did: Add A record with my local IP DNS on GoDaddy Installing wsgi Updating the settings.py page with the new addresses. Update httpd-vhosts Update httpd.conf Resetting the Apache server open the ports in my firewall *I bought the domain two days ago. httpd.conf: ServerName DomainName LoadFile path LoadModule wsgi_module path WSGIPythonHome path httpd-vhosts: ServerName DomainName <VirtualHost *:80> ServerName DomainName ServerAlias www.DomainName WSGIScriptAlias / "path" ErrorLog "logs/DomainName-error.log" CustomLog "logs/DomainName-access.log" common <Directory "path"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "path" <Directory "path"> Require all granted </Directory> -
Please i want to generate username from user email in django that can be used in the url
I'm encountering an issue with populating the display_username field in my custom Django user model. Which i want to use as the username handle. My Model: class User(AbstractUser): # First and last name do not cover name patterns around the globe name = CharField(_("Name of User"), blank=True, max_length=255) first_name = None # type: ignore last_name = None # type: ignore display_username = CharField(_("Display Username"), blank=True, max_length=255) email = EmailField(_("email address"), unique=True) username = None # type: ignore USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self) -> str: """Get URL for user's detail view. Returns: str: URL for user detail. """ return reverse("users:detail", kwargs={"pk": self.id}) My Manager: class UserManager(DjangoUserManager): """Custom manager for the User model.""" # def _create_user(self, email: str, password: str | None, **extra_fields): # """ # Create and save a user with the given email and password. # """ # if not email: # raise ValueError("The given email must be set") # email = self.normalize_email(email) # user = self.model(email=email, **extra_fields) # user.password = make_password(password) # user.save(using=self._db) # return user # def _create_user(self, email, password=None, **extra_fields): # if not email: # raise ValueError("The given email must be set") # email = self.normalize_email(email) # base_username = email.split('@')[0] # … -
What would be a better solution for storing data in a Django model?
Could you please give me a piece of advice? Context: I have a Django project in which each user stores many different variables linked to his profile. I created a model called Snapshot, that has a foreign key of user. Single user can have multiple Snapshots linked to his User instance, but only the latest one (by its ID, pk) is editable. Any other ones might be used to revert to past setup only. Typical use case: User modifies his setup stored in his latest Snapshot using API endpoints. Each function that an endpoint call has to query the latest Snapshot owned by user that called the function. Then it modifies some of the variables in the Snapshot and saves it. Once everything's done user approves the setup and the Snapshot is being duplicated. Now the new instance becomes the latest. Question: Is it a good idea to query the latest Snapshot this many times in each function? Wouldn't it be a good idea to link the latest Snapshot one-to-one with User, so that it's always available as User.latest_snapshot? This latest_snapshot would be automatically re-linked to User once user approves setup, thus creating a new Snapshot.