Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter not appearing in django-import-export
I implemented django-import-export and tried to customer the export form with start_date and end_date filter, but it is not appearing on the export view. here is a snippets of my code. TIA forms.py from django import forms from import_export.forms import ExportForm class CustomExportForm(ExportForm): start_date = forms.DateTimeField(required=False, label="Start Date", help_text="Format: YYYY-MM-DD HH:MM:SS") end_date = forms.DateTimeField(required=False, label="End Date", help_text="Format: YYYY-MM-DD HH:MM:SS") here is my resource.py class SMSMessageResource(resources.ModelResource): sender = fields.Field( column_name='sender', attribute='session', widget=ForeignKeyWidget(Model2, 'sender') ) def __init__(self, **kwargs): super().__init__() self.start_date = kwargs.get("start_date") self.end_date = kwargs.get("end_date") def filter_export(self, queryset, **kwargs): if self.start_date and self.end_date: return queryset.filter(created__range=[self.start_date, self.end_date]) return queryset class Meta: model = Model1 fields = ('id', 'sender', 'created', 'sms', 'synced') export_order = ('id', 'sender', 'created', 'sms', 'synced') and this in my admin.py def get_export_resource_kwargs(self, request, **kwargs): export_form = kwargs.get("export_form") if export_form: kwargs.update( start_date=export_form.cleaned_data.get("start_date"), end_date=export_form.cleaned_data.get("end_date") ) return kwargs What I want to achieve is, apply a date range filter on my export. but the filters don't show on the export view. -
Django NoReverseMatch Error When Using Slug [duplicate]
I'm a newbie working on a Django project, and encountering a NoReverseMatch error when trying to generate a URL using a slug in my template. theres a problem with html file, i think but couldn't solve Error during template rendering In template C:\\Users\\user\\Documents\\coding_files\\python\\website\\main\\templates\\menu.html, error at line 6 NoReverseMatch at /menu/ Reverse for 'post_detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['post/(? P<slug>[-a-zA-Z0-9_]+)\\\'] **views.py** from django.shortcuts import render, get_object_or_404 from .models import Post def post_detail(request, slug): post = get_object_or_404(Post, slug=slug) return render(request, 'menu.html', {'post': post}) **html file** <a href="{% url 'post_detail' slug=post.slug %}"> <div class='dontknow'> <img src="{% static 'img/image1.png' %}" class="logo"> </div> </a> **urls.py** from django.urls import path from . import views urlpatterns = [ path('post/<slug:slug>/', views.post_detail, name='post_detail'), ] the output should be if I click on the image in my HTML file, it should generate a URL with the slug and navigate to the post_detail view. -
Django Q (scheduler) is not working properly in python 3
Django Q (scheduler) is not working properly in python 3. it is alway terminated one time a week but it is working fine on python 2. no error log found in python 3. How to fix that issue ? is any configuration to change or fix? -
is it possible to use django-push-notifications[FCM] for both android/ios? (if both apps configured in firebase)
I want to use django-push-notifications library for push notifications. My mobile app part configured firebase for both android and ios. In library's documentations they separated logic and configuration of gcm and apns devices. Can I use just GCMDevice for both android and ios devices (to save them, send message) as it is already configured in firebase? Or should I configure apns in django also as it is mentioned in documentation from firebase_admin import auth # Initialize the default app (either use `GOOGLE_APPLICATION_CREDENTIALS` environment variable, or pass a firebase_admin.credentials.Certificate instance) default_app = firebase_admin.initialize_app() PUSH_NOTIFICATIONS_SETTINGS = { "APNS_CERTIFICATE": "/path/to/your/certificate.pem", "APNS_TOPIC": "com.example.push_test", "WNS_PACKAGE_SECURITY_ID": "[your package security id, e.g: 'ms-app://e-3-4-6234...']", "WNS_SECRET_KEY": "[your app secret key, e.g.: 'KDiejnLKDUWodsjmewuSZkk']", "WP_PRIVATE_KEY": "/path/to/your/private.pem", "WP_CLAIMS": {'sub': "mailto:development@example.com"} } If so, how to do it properly? -
VSCode Django Debugging: Breakpoints not working with 'debugpy', but work with 'python' type
When trying to debug a Django management command in VSCode, I encountered an issue where breakpoints were not being hit when using the 'debugpy' configuration type. However, when I switched to the 'python' configuration type, the breakpoints started working as expected. Steps to Reproduce Create a new Django project and app Create a simple management command Set up VSCode debug configuration Set breakpoints in the management command Try to debug the management command Django Management Command (myapp/management/commands/hello_world.py): from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Prints Hello, World!' def handle(self, *args, **options): message = "Hello, World!" # Set a breakpoint on this line self.stdout.write(message) VSCode Debug Configuration (.vscode/launch.json): { "version": "0.2.0", "configurations": [ { "name": "Django Command (debugpy)", "type": "debugpy", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "hello_world" ], "django": true, "justMyCode": false }, { "name": "Django Command (python)", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "hello_world" ], "django": true, "justMyCode": false } ] } Expected Behavior The debugger should stop at the breakpoint set in the management command for both configuration types. Actual Behavior With "type": "debugpy", the breakpoint is not hit, and the command runs to completion without stopping. With "type": "python", the breakpoint is hit as expected, … -
Nested models aren't saving to database after being serialized
I'm sending an object like this to my Django backend to update the. { id: 1, firstName: 'Foo', lastName: 'Bar', items: [ { id:1, cost: 150, .... calculatedValue: 0 }, { id: 2, cost: 100, .... calculatedValue: 0 } ] } Here are the Models class Parent(models.Model): firstName = models.models.TextField() lastName = models.TextField() class Item(models.Model): parent = models.ForeignKey(Parent, related_name='items', on_delete=models.CASCADE) cost = models.FloatField(blank=True, default=0, null=True) calculatedValue = models.FloatField(blank=True, default=0, null=True) Here are the serializer class ParentSerializer(serializers.ModelSerializer): items = ItemSerializer(many=True, read_only=True) class Meta: model = Parent fields = ('id', 'firstName', 'lastName') class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('id', 'cost', 'calculatedValue') My intention is perform the operation for the calculatedValue on the server during the post or put calls. The issue I'm running into is the value I'm computing isn't saving to the database. def update(self, request, *args, **kwargs): # I set the values on the request.data object here setValues(request.data) partial = kwargs.pop('partial', False) instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) if getattr(instance, '_prefetched_objects_cache', None): instance._prefetched_objects_cache = {} #save transaction items = request.data['items'] for item in items: itemInstance = Item.objects.get(id=item['id']) itemSerializer = ItemSerializer(itemInstance, data=transaction, partial=False) itemSerializer.is_valid(raise_exception=True) itemSerializer.save() #the correct value prints here print(f'instance after save {itemSerializer.data}') … -
Selenium wire hide redundant logging
I am using SeleniumWire, Django, Celery for parsing I have a lot of redundant logs from selenium-wire. I mean logs: Capturing request: sitename Capturing response: sitename 200 OK I want to hide these logs. How to configure logger/driver to hide selenium-wire logs? I am using regular logger: import logging logger = logging.getLogger(__name__) My Django logging settings: # settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(name)s.%(funcName)s:%(lineno)s- %(message)s' }, }, # django uses some of its own loggers for internal operations. In case you want to disable them just replace the False above with true. # A handler for DEBUG. It is basically writing the DEBUG messages into a file called DJANGO_DEBUG.log 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, }, # A logger for DEBUG which has a handler called 'file'. A logger can have multiple handler 'loggers': { # notice the blank '', Usually you would put built in loggers like django or root here based on your needs '': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, }, }, } -
is it possible to use django-push-notifications for both android/ios without apns? (if I have both apps in firebase)
I want to use django-push-notifications library for push notifications. My mobile app part configured firebase for both android and ios. In library's documentations they separated logic and configuration of gcm and apns devices. Can I use just GCMDevice for both android and ios devices (to save them, send message) as it is already configured in firebase? Or should I configure apns in django also as it is mentioned in documentation from firebase_admin import auth # Initialize the default app (either use `GOOGLE_APPLICATION_CREDENTIALS` environment variable, or pass a firebase_admin.credentials.Certificate instance) default_app = firebase_admin.initialize_app() PUSH_NOTIFICATIONS_SETTINGS = { "APNS_CERTIFICATE": "/path/to/your/certificate.pem", "APNS_TOPIC": "com.example.push_test", "WNS_PACKAGE_SECURITY_ID": "[your package security id, e.g: 'ms-app://e-3-4-6234...']", "WNS_SECRET_KEY": "[your app secret key, e.g.: 'KDiejnLKDUWodsjmewuSZkk']", "WP_PRIVATE_KEY": "/path/to/your/private.pem", "WP_CLAIMS": {'sub': "mailto:development@example.com"} } -
Static not loaded when django project deployed
I'm trying to deply my django site, and I did to my ip address, but when I load page online it doesn't load static files. I tried changing different settings on a server and on django files, but I'm out of ideas. I would appreciate a pair of fresh eyes. for sites-available I did this: sudo nano /etc/nginx/sites-available/django-site Output: server { listen 80; server_name xx.xx.xxx.xx; #my ip address location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/muser/django-site/staticfiles/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } this is settings.py STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] #media MEDIA_URL = 'media/' MEDIA_ROOT = BASE_DIR / 'media' It might be that this is all correct, but it might be that urls aren't set up properly. So please see urls.py urlpatterns = i18n_patterns( path(_('admin/'), admin.site.urls), path('rosetta/', include('rosetta.urls')), path('', include('my_app.urls', namespace='my_app')), ) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) Any ideas what I did wrong? Thanks in advance! -
ReportLab Encoding Issue When Drawing Translated Text in Django
I encountered an issue when using drawString in ReportLab to draw text in the Czech language after translating the text with Django. I've set the font to Arial, which supports the necessary characters, and noticed the following behavior: When I draw a string directly like this: t = "vůči" self.canvas.drawString(10, 10, t) The text is rendered correctly. However, when I try to draw a translated string like this: from django.utils.translation import gettext as _ t = _("towards") self.canvas.drawString(10, 10, t) The text is rendered incorrectly, showing black rectangles instead of the expected characters, indicating that the characters are not being recognized. Does anyone know why this is happening and how to fix it? -
Django - All users added to all groups
i am working to my first django project and i have some problems while creating users. views.py class registerCrispyForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(registerCrispyForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_method = 'POST' self.helper.add_input(Submit('submit', 'Submit')) class Meta: model = models.UserExt fields = ('username', 'password') def register(request): template_name = 'gestionePrenotazioni/login.html' formR = registerCrispyForm(request.POST) context = {'formRegister':formR} if request.method == 'POST': if formR.is_valid(): user = formR.save() user.set_password(request.POST['password']) user.save() return redirect("home") return render(request, template_name, context) models.py class UserExt(AbstractUser): Image = models.ImageField(upload_to='media/users') abbonamento = models.DateField(null=True, blank=True) class Meta: verbose_name_plural = 'Utenti' When i create a new user he is added to all groups and i can't remove him even in administration panel I have tried to use user.groups.clear() or even to add him only one group but i didn't get any results. -
I am making a celery-django connection, but receiving error "consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//:"
I am trying to make a django-celery connection and running a command "celery -A busynaut worker -l info" but i am receiving a following error this is my celery.py # busynaut/celery.py import os from celery import Celery os.environ.setdefault( 'DJANGO_SETTINGS_MODULE', 'busynaut.settings' ) app = Celery('busynaut') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() this is my init.py # busynaut/__init__.py from .celery import app as celery_app __all__ = ('celery_app',) -
Trying to create a generic HTML template that renders a set of questions under topic headings based on context from views.py
I have several areas, i.e. Leadership, operations, etc., each of which has a set of topics and questions associated with it. Leadership, for example, has 3 topics, each with a different set and number of questions. I am trying to create a general questions.html template where the views.py can then fit with the specific area, topics, questions, etc. for that area. I provide the topics, separate question sets for each topic via context when rendering the page for that area. I am trying to avoid hardcoding each page by looping through each topic and using the question set for that topic. I tested the code by hardcoding 1 question set and seeing if the table render properly, and it does except of course the questions are repeated under each topic. However, when I set the outer loop to loop through the topics with each unique questions set using variables, none of the questions appear. The page just renders the topics with no errors. Here is the code snippet that works but reuses the questions: <tbody> {% for m in categories %} <td colspan="7">{{ m }}</td> {% for key, value in questions1.items %} <tr> <td class="question">{{ value }} </td> {% for … -
Django Project Redirecting to /accounts/login/ URL Despite Custom URLs Configuration
I’m working on a Django project and encountering an issue where the login functionality is redirecting to URLs like /accounts/login/ or /accounts/profile/ which I did not configure. I have customized the login and registration views and removed the default Django authentication URLs. However, the server seems to be redirecting to these default paths. Here are the details of the problem: Project Setup: Django version: 5.1 Custom views for login, registration, and logout are implemented. The urls.py in my app does not include the default Django authentication URLs. urls.py in the app (firstapp/urls.py): python from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("", views.index, name="index"), path("index/", views.index, name="index"), path("error/", views.custom_404, name="error"), path("login/", views.login, name="login"), path("register/", views.register, name="register"), path("profile/", views.profile, name="profile"), path("logout/", views.logout, name="logout"), # Remove or comment out the line below # path("accounts/", include("django.contrib.auth.urls")), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # Remove or comment out handler404 if not using custom 404 view # handler404 = views.custom_404 Views File (views.py): python from django.shortcuts import render, redirect from django.contrib.auth import login as auth_login, logout as auth_logout from django.contrib.auth import update_session_auth_hash from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User, auth from .models … -
fcm-django gives error fcm_django.FCMDevice.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out
I'm using fcm-django to send push notifications. I have configured it as it is in documentation. While python manage.py migrate I got an error: SystemCheckError: System check identified some issues: ERRORS: fcm_django.FCMDevice.user: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. I have custom user model. I checked fcm_django models and migrations there is no relation with auth.User. In github issues I have found exact the same issue, but it doesn't have a lot information. Only information from owner was https://github.com/xtrinch/fcm-django/issues/207#issuecomment-1091457284 . But I didn't get it How can I fix this? -
how can i have image of user who sign up before
i have three table #post that user create class Post(models.Model): title = models.CharField(max_length=255) content = models.TextField(help_text='type something') author = models.ForeignKey(User,on_delete=models.SET_NULL,null=True) #.... #comment has related to uniqe post class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE) name = models.CharField(max_length=255) #.... #userprofile get image for each user has sign up befor class UserProfile(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) avatr = models.ImageField() comment = models.ForeignKey(Comment,on_delete=models.CASCADE) i try to have user profile image when show comments for any user can we call image when users comment has picture post=get_object_or_404(Post,pk=pid,status=1) #...... comment = Comment.objects.filter(post=post.id,) #like this i want to have my comment details {% for comment in comment %} {{comment.name}} {{comment.userprofile.image.url}} -
Django: cannot display variations of items on the template
I'm working on adding product variations to my website. However, I'm encountering a problem where the drop-down menu is showing product names instead of sizes. My application already filters products by categories, but I need to ensure that the product sizes are displayed correctly on the product detail page. models.py from django.db import models from category.models import Category from django.urls import reverse class Product (models.Model): product_name = models.CharField(max_length=100,unique=True) slug = models.SlugField(max_length=100,unique=True) description = models.CharField(max_length=1000,unique=True) price = models.IntegerField() images = models.ImageField(upload_to='photos/products') stock = models.IntegerField() is_avilable = models.BooleanField(default=True) category = models.ForeignKey(Category,on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return self.product_name def get_url(self): return reverse('product_detail',args=[self.category.slug, self.slug]) class VariationManager(models.Manager): def colors(self): return super(VariationManager, self).filter(variation_category='color', is_active=True) def sizes(self): return super(VariationManager, self).filter(variation_category='size', is_active=True) variation_category_choice = ( ('color', 'color'), ('size', 'size'), ) class Variation(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) variation_category = models.CharField(max_length=20, choices= variation_category_choice) variation_value = models.CharField(max_length=100) is_active = models.BooleanField(default=True) created_date =models.DateTimeField(auto_now=True) objects = VariationManager() def __str__(self): return self.variation_value product-details.html {% extends "base.html" %} {% load static %} {%block content%} <section class="section-content padding-y bg"> <div class="container"> <!-- ============================ COMPONENT 1 ================================= --> <div class="card"> <div class="row no-gutters"> <aside class="col-md-6"> <article class="gallery-wrap"> <div class="img-big-wrap"> <a href="#"><img src="{{ single_product.images.url }}"></a> </div> <!-- img-big-wrap.// --> </article> <!-- gallery-wrap .end// --> … -
Django rest framework Google OAuth best packages
I am currently building a webapp with backend in django and frontend in react (Later, I want to add mobile app for it too. I want to add login via Google as only option, so it would be easier for users to register/login. What packages do you think will work the best? What will be the easiest to implement? -
django migration failed : the field value was declared with a lazy reference
I am trying to enforce my User's email should be unique. In my app called accounts I have the below models.py where I created a CustomUser. Then the Employeee model below there is a 1:1 relationship to CustomUser. from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): email = models.EmailField(unique=True) groups = models.ManyToManyField( 'auth.Group', related_name='customuser_set', # Unique related_name to avoid conflict blank=True, help_text='The groups this user belongs to.', verbose_name='groups', ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='customuser_set', # Unique related_name to avoid conflict blank=True, help_text='Specific permissions for this user.', verbose_name='user permissions', ) def __str__(self): return self.username # Create your models here. class Employee(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) number_work_hour_per_week = models.FloatField( help_text="Number of working hour per week" ) work_hour_limit = models.BooleanField( default=False, help_text="If true number_work_hour_per_week applies in the time registration", ) flexible_time_registration = models.BooleanField( default=True, help_text="Allow the user to register working hour flexible without preregistered time", ) def __str__(self): return self.user.username In my settings.py I have overwrite the default User to be accounts.CustomUser AUTH_USER_MODEL = 'accounts.CustomUser' When I do python manage.py migrate I get the below error stack dimsum-dk-py3.10jianwu@localhost:~/webapp/HD_website/website$ poetry run python manage.py migrate accounts zero Operations to perform: Unapply all migrations: accounts Traceback (most recent call last): … -
Send variable to Django crispy forms
I have a Django Crispy form defined in views.py: @login_required def PostCreate(request): if request.method == 'POST': form = PostFileForm(request.POST or None, request.FILES or None) files = request.FILES.getlist('file') if form.is_valid(): post = form.save(commit=False) post.author = request.user form.instance.author = request.user etc. and post_form.html: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <button class="btn btn-outline-info" id="audit" onclick="audit()">Basic</button> <form method="POST" id="PostForm" data-sektor-url="{% url 'ajax_load_sektors' %}" data-department-url="{% url 'ajax_load_departments' %}" data-person-url="{% url 'ajax_load_persons' %}" novalidate enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4" style="color:red;">Order</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" id="submit" type="submit">Submit</button> </div> </form> in my models.py I have defined all models I need for the full form. Depending on the 4 buttons which user can click to call the form, that form should have some fields hidden/shown or autofilled. I hide them using Javascript, for example: <script type="text/javascript"> function on_load(){ document.getElementById('hidden_on_open').style.display = 'none'; My problem is, I don't know which button is pressed. Is there a way to 'pass a static variable' or something to the HTML, since if I pass it to views.py it's already rendered? So that I can use Javascript to hide/show and autofill certain fields depending on that variable. Just … -
Django ORM efficient way for annotating True on first occurrences of field
I have a situation where we have some logic that sorts a patient_journey queryset (table) by some heuristics. A patient_journey has a FK to a patient. I now need an efficient way of setting True for the first occurrence of a patient_journey for a given patient, false otherwise. The first heuristinc is patient_id so the queryset will already by grouped by patient. The algorithm is v straight forward & should be fast, yet I'm stuck at trying to get something <1s. I've tried using distinct and checking for existence, however that's adding 1-2s. I've tried using a subquery with [:1] & test on id, but that's even worse around 3-5s extra. def annotate_primary( *, qs: 'PatientJourneyQuerySet' # noqa ) -> 'PatientJourneyQuerySet': # noqa """ Constraints: -------------- Exactly One non-global primary journey per patient Annotations: ------------ is_primary_:Bool, is the primary_journey for a patient """ from patient_journey.models import PatientJourney qs = get_sorted_for_primary_journey_qs(qs=qs) # cost until now is around 0.17s # using distinct on patient_id & checking if id is in there adds around 1.5-2s # looking for something faster, i.e. this shoiuld be a straight forward scan. qs = qs.annotate( # True for first occurrence of a `patient_id` false otherwise primary= ) … -
"detail": "Authentication credentials were not provided." postman django
Trying to do authorization on tokens When I make a POST request through postman it gives an error "detail": "Authentication credentials were not provided." REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_PARSER_CLASSES':[ 'rest_framework.parsers.JSONParser', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', #'rest_framework.authentication.SessionAuthentication', #'rest_framework_simplejwt.authentication.JWTAuthentication', ] manager.py from django.contrib.auth.models import BaseUserManager from django.core.exceptions import ValidationError from django.core.validators import validate_email from django.utils.translation import gettext_lazy as _ class UserManager(BaseUserManager): def email_validator(self, email): try: validate_email(email) except ValidationError: raise ValueError(_("please ener a valid email")) def create_user(self, email, username, password, **extra_fields): if email: email=self.normalize_email(email) self.email_validator(email) else: raise ValueError(_("an email adress is required")) if not username: raise ValueError(_("an username is required")) user=self.model(email=email, username=username, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("is_verified", True) if extra_fields.get("is_staff") is not True: raise ValueError(_("is staff must be true for admin user")) if extra_fields.get("is_superuser") is not True: raise ValueError(_("is superuser must be true for admin user")) user = self.create_user( email, username, password, **extra_fields ) user.save(using=self._db) return user views.py from django.shortcuts import render from rest_framework.generics import GenericAPIView from .serializers import UserSerializer from rest_framework.response import Response from rest_framework import status from .utils import send_code_to_user class RegisterUserView(GenericAPIView): serializer_class=UserSerializer def post(self, request): user_data=request.data serializer=self.serializer_class(data=user_data) if serializer.is_valid(raise_exception=True): serializer.save() user=serializer.data send_code_to_user(user['email']) return Response({ 'data':user, 'message':f'hi{user.username}' }, … -
Azure Appservice for Django fails with Azure Devops Pipeline
I have an appservice running on Azure in a Linux environment. I try to associate it with a Azure Devops Pipeline so I can have CI/CD for the repositories & branches on Github. I want the builds to occur on Azure Pipeline & Azure infrastructure, not Github Actions. I have tried all other suggestions including following environment variables on App Service : SCM_DO_BUILD_DURING_DEPLOYMENT=true WEBSITE_NODE_DEFAULT_VERSION=~18 WEBSITE_RUN_FROM_PACKAGE=true Here is the logs that I receive from the Kudu / Azure Devops Pipeline / AppService logs : /home/LogFiles/2024_08_14_ln1xsdlwk0000K3_docker.log (https://project-app-development.scm.azurewebsites.net/api/vfs/LogFiles/2024_08_14_ln1xsdlwk0000K3_docker.log) 2024-08-14T23:51:45.168Z INFO - Status: Image is up to date for 10.1.0.6:13209/appsvc/python:3.10_20240619.2.tuxprod 2024-08-14T23:51:45.179Z INFO - Pull Image successful, Time taken: 0 Seconds 2024-08-14T23:51:45.223Z INFO - Starting container for site 2024-08-14T23:51:45.223Z INFO - docker run -d --expose=8000 --name project-app-development_0_f2e0544d -e WEBSITE_USE_DIAGNOSTIC_SERVER=false -e WEBSITE_SITE_NAME=project-app-development -e WEBSITE_AUTH_ENABLED=False -e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_HOSTNAME=project-app-development.azurewebsites.net -e WEBSITE_INSTANCE_ID=3f627dbbecdaed255d87aa9c3e8f1448758df1cdff41f5e14b114384ea9b244a appsvc/python:3.10_20240619.2.tuxprod gunicorn -b :$PORT project.wsgi 2024-08-14T23:51:45.223Z INFO - Logging is not enabled for this container. Please use https://aka.ms/linux-diagnostics to enable logging to see container logs here. 2024-08-14T23:51:45.893Z INFO - Initiating warmup request to container project-app-development_0_f2e0544d for site project-app-development 2024-08-14T23:51:49.043Z ERROR - Container project-app-development_0_f2e0544d for site project-app-development has exited, failing site start 2024-08-14T23:51:49.057Z ERROR - Container project-app-development_0_f2e0544d didn't respond to HTTP pings on port: 8000, failing site … -
How do I use prefetch_related for Generic Relationship in Django?
I've multiple models. Model1, Model2, Model3, ... Each model requires multiple let's say feature/images. Can be implemented by making different Image models ( i.e. Morel1Image ) then link with foreign key. Or, Make a Generic Image Model and use it wherever it needs. The problem is, I'm having similar queries ( debug ). And prefect_related isn't working ( Django might not have the feature ). Now how do I solve the problem ( efficiently ) ? I'm expecting no similar or duplicate quary. -
Using formset in django formtool
am creating a 8 steps form wizard. 2 of the models are Qualification and SSCE and i used formset to create multiple forms inputs Formset factory QualificationsFormSet = modelformset_factory(Qualifications, form=QualificationsForm, extra=5) SscesFormSet = modelformset_factory(Ssces, form=SSCESubjectForm, extra=5) the View class StudentWizard(LoginRequiredMixin, SessionWizardView): form_list = FORMS # template_name = 'admission/form_wizard.html' file_storage = FileSystemStorage(location='/tmp/') def get_form(self, step=None, data=None, files=None): if step is None: step = self.steps.current form = super().get_form(step, data, files) form.request = self.request if step == '3': form = QualificationsFormSet(data, queryset=Qualifications.objects.none()) elif step == '4': form = SscesFormSet(data, queryset=Ssces.objects.none()) return form def get_form_instance(self, step): print(f"Current step: {step}") if step == '4': # SSCE step qualifications = self.get_cleaned_data_for_step('3') print(f"Qualifications data: {qualifications}") if qualifications: certificates = [qual['certificate_obtained'] for qual in qualifications] print(f"Certificates: {certificates}") if not any(cert in ['WASC', 'SSCE', 'NECO', 'GCE'] for cert in certificates): print("Skipping SSCE step") return None # Skip the Ssces formset return super().get_form_instance(step) def get_context_data(self, form, **kwargs): context = super().get_context_data(form=form, **kwargs) if self.steps.current in ["3", "4"]: context['formset'] = form context['formset_with_widgets'] = [ [(field, field.field.widget.__class__.__name__) for field in form] for form in context['formset'].forms ] else: context['fields_with_widgets'] = [ (field, field.field.widget.__class__.__name__) for field in form ] return context the problem is that the other forms works well upto the Qualification where after …