Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way of passing a model into a template without a class based view
My question is can I use a function view to pass in a model inside my template to be iterated through. This is how my model looks like class Listing(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE) itempicture = models.ImageField(upload_to="images",blank=False) title = models.CharField(max_length=50) about = models.CharField(max_length=500) published_date = models.DateTimeField(blank=True, null=True) how can I write a function based view to pass in my database just like a class based (list view) -
Bypassing DRF throttling
I have a Django application running on an Nginx + Gunicorn server where I use DRF throttling. Whenever I make API requests to my server and change the X-Forwarded-For header value in the client I'm then able to bypass the throttling for unauthenticated users and thereby have unlimited access to the API. This is of course not desired. I think a way to deal with this is to have Nginx append the real IP to the end of the X-Forwarded-For request header before it reaches the server by using proxy params. It just doesn't seem to change the header when I inspect Postman / RapidApi client. I assume that's what causes the error but ultimately I don't know. Nginx conf: location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } The proxy_params file from Nginx includes setting the X-Forwarded-For request header like so: proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; Can somebody tell me what I'm doing wrong and how to fix it so you can't make unlimited API requests? If you need more information or clarification please let me know. -
formset won't validate django admin custom actions interim form page
I don't know how to get the updated fields, from the forms in the formset, into individual messages, because the formset is never valid. in the admin action interim page the user has to be able to see and edit the forms intial values and when they submit the messages should be sent with the form updated or not values to the correct mail. But the formset is never valid. Is it because of how the admin actions functions or what is going on? ¨ forms.py class ReviewRequestTemplate(forms.Form): emailtemplate = forms.CharField(widget=forms.Textarea) employers_email = forms.EmailField() review_link = forms.CharField() subject = forms.CharField() admin.py class EmployerAdmin(TranslationAdmin): list_display = ('name', 'website', 'review_request_sent',) actions = ['request_review',] def request_review(self, request, queryset): RequestTemplateFormset = formset_factory(ReviewRequestTemplate, extra=0) formset = RequestTemplateFormset(initial=[{'emailtemplate': f"Hello {employer.name} Review our servie right NOW! Here is your link:",'employers_email':employer.email, 'review_link':get_current_site(request).domain +reverse('review', kwargs={'uidb64': urlsafe_base64_encode(force_bytes(employer.pk)), 'token':account_activation_token.make_token(employer)}), 'subject':'Please let us better our services'} for employer in queryset]) if request.POST.get('post'): formset = RequestTemplateFormset(request.POST) if formset.is_valid(): print('valid') message = f"email:{form.get('employers_email')}, subject:{form.get('subject')}, message: {form.get('emailtemplate') + form.get('review_link')}" queryset.update(review_request_sent=True) else: print('not valid') all_sent = request.POST.items() return HttpResponse(all_sent) else: context = { 'title': "Are you sure?", 'queryset': queryset, 'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME, 'formset': formset } return TemplateResponse(request, 'admin/requestreview.html', #TemplateResponse context) request_review.short_description = "Send review requests" html {% … -
Not able to run the command: python manage.py runserver, in pycharm
I have tried running the python manage.py runserver in pycharm terminal, earlier it was working fine but now it is not working as expected and gives the following error: Program 'python.exe' failed to run: The file cannot be accessed by the systemAt line:1 char:1 + python manage.py runserver + ~~~~~~~~~~~~~~~~~~~~~~~~~~. At line:1 char:1 + python manage.py runserver + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (:) [], ApplicationFailedException + FullyQualifiedErrorId : NativeCommandFailed -
How to split API to paid and unpaid users?
I have database full of useful information, which I want to develop an API for using Django rest framework. This API will be used by mobile app so user and user authentication. I want the users of this App to pay a subscription fee for the services. What is the best way to go about this using django?? I just need a direction, I thought about dividing user to groups paid and unpaid Paid group have access to all, unpaid only have a portion of every service, using django permissions group. I do have a strong feeling that this not secure or the way to do it. I also thought about Token Authorisation, meaning people who have the token have access others have limited access. Is this good strategy? Please any help is immensely appreciated 🙏. -
I want to perform a search using these two fields by django-watson framework , Please help...thank you
I want to perform a search using these two fields by django-watson framework The first field searches by restaurant name and the second field searches by restaurant locations and the two fields in the same form -
Django request.POST does not contain the name of the button that submitted the form despite having name and value
I have Django form that have 2 different submit button, i need to know which button is clicked. But the button did not include in request.POST This is my form: <form hx-post="{% url 'recomposition:akb-edit' %}" hx-target="#target-{{this_month}}-{{data.pk}}" hx-swap="outerHTML" enctype="multipart/form-data"> ... <div class="form-group modal-footer p-0"> <div class="btn-group d-flex w-100" role="group" aria-label="..."> {% if this_month != 0 %} <button type="submit" value="delete" name="delete" class="btn btn-danger w-100" {%if not is_month %}disabled{% endif %}>Delete changes</button> {% endif %} <button type="button" class="btn btn-secondary w-100" onclick="closeModal()">Close</button> <button type="submit" value="save" name="save" class="btn btn-primary w-100" >Save changes</button> </div> </div> </form> I didnt know whats wrong the last time I encounter this if i forgot to included the name but now i have the name and value but id didnt show up in request.POST -
How to use patterns in the definition of a variable in Django
I am working in Django and I have the following class class Usuario(AbstractBaseUser): username =models.CharField(verbose_name='Nombre de usuario', max_length=45, unique=True) date_join =models.DateTimeField(verbose_name='Fecha de alta', auto_now_add=True) last_login =models.DateTimeField(verbose_name='Última conexión', auto_now=True) es_docente =models.BooleanField(default=False) es_estudiante =models.BooleanField(default=False) es_directivo =models.BooleanField(default=False) es_preceptor =models.BooleanField(default=False) es_tutor =models.BooleanField(default=False) es_superuser =models.BooleanField(default=False) estado =models.BooleanField(default=True) now, I would like to add a function to change the boolean states, if it is possible, by using some kind of pattern. I know that the following code is wrong but I didn't find the correct syntax: def changer(self,var): es_(%var) = not Usuario.es_(%var) where I am marking with %var some kind of usage of the input of the function. For example, I would like to input changer(preceptor) and receive as output that the changing of the boolean field es_preceptor. Thanks in advance! -
I'm making a django webapp and I keep getting pk errors
I keep getting this error even after migrating, making migrations, importing get_object functions, Page not found (404) No storage found matching the query Request Method: GET Request URL: http://127.0.0.1:8000/change-info/1 Raised by: base.views.UpdateInfo Using the URLconf defined in mywallet.urls, Django tried these URL patterns, in this order: admin/ [name='list'] descript/<int:pk>/ [name='descript'] create-bank/ [name='create-bank'] change-info/<int:pk> [name='change-info'] The current path, change-info/1, matched the last one. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. This is my views.py code from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.http import HttpResponse from django.views.generic.edit import CreateView, UpdateView from django.urls import reverse_lazy from .models import Storage # Create your views here. class Listings(ListView): model = Storage context_object_name = 'banks' class Information(DetailView): model = Storage template_name = 'base/storage_detail.html' class NewBank(CreateView): model = Storage fields = '__all__' success_url = reverse_lazy('list') class UpdateInfo(UpdateView): model = Storage fields = '__all__' reverse_lazy('list') my urls.py from django.urls import path from .views import Listings, Information, NewBank, UpdateInfo urlpatterns = [ path('', Listings.as_view(), name= 'list'), path('descript/<int:pk>/', Information.as_view(), name='descript'), path('create-bank/', NewBank.as_view(), name='create-bank'), path('change-info/<int:pk>', UpdateInfo.as_view(), name='change-info') ] my models.py from django.db import models … -
Django Rest Framework implement update_or_create when deserializing object
I want to implement update_or_create when deserializing object. I found @K-Moe answer in this question: Django Rest Framework POST Update if existing or create I tried this solution but I got the ValidationError saying that my object already exists: [{'variant_id': [ErrorDetail(string='sku with this variant id already exists.', code='unique')]}, {'variant_id': [ErrorDetail(string='sku with this variant id already exists.', code='unique')]}] Did I miss something? My model class Sku(models.Model): variant_id = models.CharField(primary_key=True, max_length=10, validators=[MinLengthValidator(10)]) name = models.CharField(max_length=255) shop = models.ForeignKey(Shop, related_name='sku', on_delete=models.CASCADE) barcode = models.CharField(max_length=60, null=True, blank=True) price = models.FloatField(null=True, blank=True) def __str__(self): return self.name class Meta: constraints = [ models.UniqueConstraint(fields=['variant_id', 'shop'], name='unique_shop_sku') ] @classmethod def update_or_create(cls, variant_id, shop_id, **kwargs): with transaction.atomic(): return cls.objects.update_or_create(variant_id=variant_id, shop_id=shop_id, defaults=kwargs) My serializers: class SkuSerializer(serializers.ModelSerializer): shop_id = serializers.CharField(source='shop') class Meta: model = Sku fields = ['name', 'shop_id', 'product_id', 'variant_id', 'barcode', 'price'] def create(self, validated_data): sku = Sku.update_or_create( variant_id=validated_data.pop('variant_id'), shop_id=validated_data.pop('shop'), **validated_data ) return sku -
Django NoReverseMatch at /sitemap.xml error for static views
I followed the instruction on django documentation, but I am getting this error when trying to create the sitemap.xml for my app. (also the similar questions on stackoverflow were not describing my case) The html pages that I would like to add to the sitemap are not based on any models, but they have some forms in their footers. (That's why the urls don't contain "as_view()". I have also added INSTALLED_APPS = [ ... 'django.contrib.sites', 'django.contrib.sitemaps', ''' ] to settings.py file. Here are more details: App --> main main/urls.py from django.urls import path from . import views app_name = 'main' urlpatterns = [ path('', views.HomeView, name='homepage'), path('about/', views.AboutView, name='about'), path('contact/', views.Contact, name='contact'), ] main/sitemap.py from django.contrib.sitemaps import Sitemap from django.urls import reverse class StaticViewSitemap(Sitemap): changefreq = 'daily' priority = 0.9 def items(self): return ['homepage','about','contact'] def location(self, item): return reverse(item) Project --> dcohort dcohort/urls.py from argparse import Namespace from django.contrib import admin from django.urls import path, include from django.contrib.sitemaps.views import sitemap from main.sitemaps import StaticViewSitemap from django.conf import settings from django.conf.urls.static import static sitemaps = { 'staticviews': StaticViewSitemap, } urlpatterns = [ path('', include('main.urls', namespace='main')), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] -
<script> tag gets run twice in HTML file
My HTML file is structured the same as any other HTML file. The <head> tag <body> tag and <script> tag all inside the <html> tag. But my <script> tag gets run twice. For example if I add a console.log("hi") inside my <script> it will log in the console: hi hi This is my index.html file: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}{% endblock %}</title> <!-- Other links in here --> </head> <body> <!-- Some content in here --> </body> <script> console.log("Hi") // The above command gets executed twice </script> </head> I'm using Django so that is why there are {% load static %} and other things like that, could these maybe be affecting the <script> tag? I'm not quite sure what the problem is, could anyone help? -
Django4.1: Login fails on `localhost`, but succeeds on `127.0.0.1`
Before, i was using SQLite as a database backend, eveything was fine, but i have reached a point where an RDBMS (postgres) was required to setup up proper validations, queries, ... Right after dockerizing postgres, i started seeing this problem. Setup: Django [Not Dockerized] (with ALLOWED_HOSTS = ['*']) DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "localhost_db", "USER": "root", "PASSWORD": "root", "HOST": "localhost", # set in docker-compose.yml "PORT": 5432, # default postgres port } } Postgres [Dockerized] Redis [Dockerized] CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6378)], }, }, } docker-compose.yaml version: '3.9' services: redis: restart: always image: redis:alpine expose: - 6378 ports: - '6378:6378' volumes: - 'redisdata:/data' command: [ "redis-server", "--bind", "redis", "--port", "6378" ] db: container_name: pg_container image: postgres:alpine restart: always environment: POSTGRES_USER: root POSTGRES_PASSWORD: root POSTGRES_DB: localhost_db ports: - "5432:5432" pgadmin: container_name: pgadmin4_container image: dpage/pgadmin4 restart: always environment: PGADMIN_DEFAULT_EMAIL: root@localhost.com PGADMIN_DEFAULT_PASSWORD: root ports: - "5050:80" volumes: - postgresdata:/var/lib/postgresql/data/ volumes: redisdata: postgresdata: This is my first time seeing this, anyone has ever faced this issue before ? -
i want to display skill data from model in selected tag in django while editing the existing data
i want the existing skills display like placeholder or values in editing tag This is my html skill selecting tag. when a user want to edit his/her details the skills already added should have in the selected tag like a placeholder or a value. The ' sl ' from another context. <div class="form-group"> <label>Skills</label> <span style="color:#ff0000">*</span> <select id="add_skills" name="skills" placeholder="Select Skills" required multiple> <option value="" id="add_skills" disabled selected></option> {% for i in sl %} <option value="{{i.id}}" name="skills">{{i.skill_name}}</option> {% endfor %} </select> </div> this is my model class corporateTrainers(models.Model): Name = models.CharField( max_length=50) Phone_Number = models.IntegerField() Email = models.EmailField(max_length=54 , unique=True) Skill = models.ManyToManyField(Skill) Rate = models.IntegerField() Description = models.TextField(max_length=255) Resume=models.FileField(upload_to="media",null=True,blank=True) def __str__(self): return self.Name its my editing View def editCorporateTrainers(request): if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') phone = request.POST.get('phone') rate = request.POST.get('rate') description = request.POST.get('description') skill = request.POST.getlist('skills',[]) description= request.POST.get('description') resume = request.FILES['resume'] trainer = request.POST.get('trainer_Id') resumeobj = FileSystemStorage() resume2 = resumeobj.save(resume.name,resume) var = corporateTrainers.objects.filter(id=trainer) var.update(Name=name,Email=email,Phone_Number = phone , Rate = rate, Description = description, Resume = resume2) vars = corporateTrainers.objects.get(id=trainer) if vars.Skill.exists(): vars.Skill.clear() vars.Skill.add(*skill) messages.success(request,"Record Updated") return redirect('listCorporateTrainers') -
how to i add custom permissions in django rest framework
i wanted to ask can we use model level permissions from django in django rest-framework or do we have to create custom permission differently for django rest-framework. permission = Permission.objects.get(codename = 'is_seller') self.request.user.user_permissions.add(permission) the above code to add permission when a form is submitted is not adding the permission and is showing the error that user_permission does not have a object add() -
Django not showing blank validation message on one of my field
I have a problem with my field. I have two field that have same field and widget. But one of the field didn't show blank validation message. Model: class MagangLetter(models.Model): to=models.CharField(max_length=255) reason=models.CharField(max_length=255) start_date=models.DateField() end_date=models.DateField() Form: class MagangLetterForm(forms.ModelForm): class Meta: model=MagangLetter fields=['to','reason','start_date','end_date'] widgets={ 'to':forms.Textarea(attrs={'class':'form-control','rows':'3','placeholder':'''#example'''}), 'reason':forms.Textarea(attrs={'class':'form-control','rows':'3','placeholder':'''#example'''}), 'start_date':forms.DateInput(attrs={'class':'form-control','type':'date'}), 'end_date':forms.DateInput(attrs={'class':'form-control','type':'date'}) } View class CreateLetterMagang(CreateView): model=MagangLetter form_class=MagangLetterForm template_name_suffix="_create_form" def get_context_data(self, **kwargs): context=super().get_context_data(**kwargs) form:MagangLetter=context['form'] file_template=Template(services.letter.get_html_template('magang.docx')) date=datetime.datetime.now() day=settings.MONTHS[date.strftime('%m')] file_context=Context({ 'letter_number' : '........', 'date_submitted' : f'{date:%d} {day} {date:%Y}', 'to': form['to'], 'name': self.request.user.get_full_name(), 'nim': self.request.user.detail.id_number, 'reason':form['reason'], 'start_date': form['start_date'], 'end_date': form['end_date'], 'nip':'.............', 'dosen':'...............', 'sign': '' }) html=file_template.render(file_context) soup = BeautifulSoup(html, 'html.parser') date_submit=soup.find(string=re.compile("Yogyakarta,")) p=soup.find(string=re.compile("#test")) date_submit.parent.parent['style']='width:15rem;' p.parent['class']='p-0' p=soup.find(string=re.compile("#test")) p.parent['class']='p-0' p=soup.find(string=re.compile("#test")) p.parent['class']='p-0' table=(p.next_element.next_element.next_element) table['class'].append('text-center ms-auto') table['style']='width:fit-content' date_forms=soup.find_all(type='date') for date_form in date_forms: date_form['class'].append('w-25') date_form['style']='min-width:fit-content;' context['docx']=soup.prettify() return context Template: {% block body %} <div class="row content d-block overflow-auto"> <div class="card p-3" style="width:40rem;"> <form method='post'> {% csrf_token %} {{docx|safe}} <input type='submit' class='btn btn-primary' value='Buat Surat'></input> </form> </div> </div> {% endblock body %} validation screenshot to field not showing validation message. reason field showing validation message. How do I show this validation on both field? -
403 Forbidden Error in Django Iframe on Safari Browser
I have a Django Iframe that is working fine on Chrome and Mozilla but in Safari I'm getting the above mentioned error. I think the cookies are not detected because when I checked it was empty and no CSRF tokens were found. I am attaching the screenshots. Error Displayed in browsers console log Browser Cookies is empty. This is my settings.py file: """ Django settings for shopify_django_app project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os from shopify_app import * from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Make this unique and store it as an environment variable. # Do not share it with anyone or commit it to version control. SECRET_KEY = config('DJANGO_SECRET') DEBUG = int(config('DEBUG')) # SHOPIFY SETTINGS SHOPIFY_API_KEY = config('SHOPIFY_API_KEY') SHOPIFY_API_SECRET = config('SHOPIFY_API_SECRET') SHOPIFY_APP_NAME = config('SHOPIFY_APP_NAME') SHOPIFY_API_VERSION = 'unstable' SHOPIFY_TEST = config('SHOPIFY_TEST') # For the purpose of Shopify Payments INTERNAL_IPS = ('127.0.0.1',) ALLOWED_HOSTS = config('DJANGO_ALLOWED_HOSTS').split(" ") CSP_FRAME_ANCESTORS = ("'self'", 'https://*.myshopify.com') # default source as self CSP_DEFAULT_SRC = ("'self'", "'unsafe-inline'", "'unsafe-eval'", "https://fonts.gstatic.com") # style from our domain … -
how can I output a list in html django?
I have a chat and I need to display a list of people with whom I had correspondence on an html page, i.e. either I wrote to a person or he wrote to me. I wrote the code in views.py , but I don't know how to display an html page. views.py: def send_chat(request): resp = {} User = get_user_model() if request.method == 'POST': post =request.POST u_from = UserModel.objects.get(id=post['user_from']) u_to = UserModel.objects.get(id=post['user_to']) messages = request.user.received.all() pk_list = messages.values_list('user_from__pk',flat=True).distinct() correspondents = get_user_model().objects.filter(pk__in=pk_list) insert = chatMessages(user_from=u_from,user_to=u_to,message=post['message']) try: insert.save() resp['status'] = 'success' except Exception as ex: resp['status'] = 'failed' resp['mesg'] = ex else: resp['status'] = 'failed' return HttpResponse(json.dumps(resp), content_type="application/json") I was trying to get messages in a variable correspondents, but when I try to output this variable through the chatMessages model, it gives an error that there should be ids in correspondents, although I seem to get them anyway my models.py: class chatMessages(models.Model): user_from = models.ForeignKey(User, on_delete=models.CASCADE,related_name="sent") user_to = models.ForeignKey(User, on_delete=models.CASCADE,related_name="received") message = models.TextField() date_created = models.DateTimeField(default=timezone.now) correspondents = models.ForeignKey(User, on_delete=models.CASCADE,related_name="correspondents", null=True) def __str__(self): return self.message my html code: <div class="container" style="height: 75%;"> <div class="card bg-dark h-100 border-light"> <div class="card-body h-100"> <div class="row h-100"> <div class="col-md-4 border-right h-100"> <div class="list-group bg-dark anyClass" id='user-list'> … -
Django: Field 'object_id' expected a number but got 'fe2b1fd4313c'
I am getting this error while trying to save a model from the admin section using Django admin, this is the error Field 'object_id' expected a number but got 'id_b2cbfe2b1fd4313c'.. I am using django shortuuid package https://pypi.org/project/shortuuid/ to create id field in django, and i choose to use it because the inbuild UUID field keeps giving this error Django UUIDField shows 'badly formed hexadecimal UUID string' error? and the id looks like this id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True). What would be the problem witht the short uuid field. Based on this, i quote: If you filter on the ForeignKey, then Django will filter on the primary key of the target object, and that is normally an AutoField, unless you referred to another (unique) column, or defined another primary key as field. But i dont know what the issue might be now Models.py class Channel(models.Model): id = ShortUUIDField( length=16, max_length=40, prefix="id_", alphabet="abcdefg1234", primary_key=True,) full_name = models.CharField(max_length=200) user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True, related_name="channel") Views.py def channel_profile(request, channel_name): channel = Channel.objects.get(id=channel_name, status="active") context = { "channel": channel, } return render(request, "channel/channel.html", context) -
Cannot send message to specific group in Django Channels
I have a websocket that receives a token as a query string. My custom middleware then decodes this token to find the username passed through this token. The current user connecting to the websocket is then subscribed to a group named after their user_id. Let's assume UserA goes through this process initially and they are subscribed to group '1' UserB then connects to the websocket following the same process. At this point I assume there are two groups; one named '1' and another names '2'. Upon UserA triggering the send & receive method in the frontend, I have a consumer function that sends a message to the group with the user_id it receives ('2'). However, when this code runs, I don't seem to be sending a message to any group. I am not getting any error message (I can see the message I want to send being printed on my terminal). However when I open two browsers; one with UserA and the other with UserB, when I connect to the websocket and trigger send/receive I don't see the message I am sending being console logged on either browsers. Here is the code for the consumer class handling the connect, send … -
How to upload pdf format file in Django
I am doing a Django project and my requirement is to upload a file of PDF format only, no other format of files to be shown while selecting files which has to be upload except pdf format file -
How to check for duplicate file contents
I am checking whether a file uploaded already has duplicates of that file. I am using cosine similarity to do the content check. That works fine, but I thinking this way of running a task with for loops of documents that are already accepted against uploaded files that haven't been accepted(processing) yet is not practical. So what would be a more better way to go out this? documents_processing = Document.objects.filter(status='processing') documents = Document.objects.filter(status='accepted') for processing in documents_processing: for document in documents: # If cosine similary > .9: # Stop and update processing document as status=denied, comment=duplicate cosine_similarity = get_cosine_similary(document, processing) if cosine_similarity > 0.9: processing.status = 'denied' processing.comment = 'duplicate' processing.save() else: processing.status = 'accepted' processing.save() What would be the suggestions here for a more efficient code? -
Django 4.1: how to add 'slug_field' to UpdateView for User model from Profile model
I've created the famous Profile model for Django's User model and it has the following fields: [profile_picture, bio, slug] I've registered the Profile model in User model as StackedInLine I've created a view for editing Profile's fields using the slug in the URLconf Now I'm trying to create an UpdateView for the User model in order to change the fields, But it's missing a slug, I tried setting the slug_field to self.profile.slug but it returns a string and not the field. How can I create an UpdateView for the User model using User.profile.slug as the slug in the URLconf? Am I even taking the right approach? models.py: from django.db import models from django.contrib.auth.models import User from django.urls import reverse from .storage import OverwriteStorage def get_upload_path(instance, filename): extension = filename.split('.')[-1] return f'{instance.user.username}/profile_picture.{extension}' class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(blank=True, null=True) profile_picture = models.ImageField(upload_to=get_upload_path, blank=True, storage=OverwriteStorage) slug = models.SlugField(blank=False, null=False) def get_absolute_url(self): return reverse('profile', kwargs={'slug': self.slug}) admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from .models import Profile class ProfileInline(admin.StackedInline): model = Profile can_delete = False verbose_name_plural = 'employee' class UserAdmin(BaseUserAdmin): inlines = (ProfileInline,) admin.site.unregister(User) admin.site.register(User, UserAdmin) views.py: class UserAccountUpdateView(UpdateView): model = User … -
django custom actions interim formpage doesn't submit
Everytime I submit it quits back to model adminpage without executing anything. I'm trying to let there be an interim page for approval purposes. But it either doesn't notice submit or the submit has already happened on page load in other applications. forms.py class ReviewRequestTemplate(forms.Form): emailtemplate = forms.CharField(widget=forms.Textarea, required=True) employers_email = forms.EmailField(required=True) admin.py class EmployerAdmin(TranslationAdmin): list_display = ('name', 'website', 'review_request_sent',) actions = ['request_review',] def request_review(self, request, queryset): context={} RequestTemplateFormset = formset_factory(ReviewRequestTemplate, extra=0) formset = RequestTemplateFormset(initial=[{'emailtemplate': f'Hello {employer.name} Review our service right NOW!','employers_email':employer.email} for employer in queryset]) if 'submit' in request.POST: print('YEES') formset = RequestTemplateFormset(request.POST) if formset.is_valid(): print("formset is valid") else: print('nooo') context['formset'] = formset context['selected_employers'] = queryset return render(request, 'admin/reviewrequest.html', context) admin/reviewrequest.html {%extends "admin/base_site.html" %} {% block content %} <form action="" method="post" name="requestreviewform"> {% csrf_token %} <input type="checkbox" value="check" name="check"> do you want to send? {%for form in formset%} {{form.as_p}} {%endfor%} <input type="submit" name="request_review" value="Send request/s"> </form> {% endblock %} -
How to exclude certain system checks from running on `manage.py migrate`?
I have created a series of checks using Django's System check framework. Some of the checks are used to confirm that fixtures are set up correctly. For example, I have a check that confirms if all users have at least one group. @register(Tag.database) def check_users_have_group(app_configs, **kwargs): errors = [] users = UserModel.objects.all() for user in users: if not user.groups.exists(): message = f'{user} has no permission groups set.' errors.append( Error( message, obj='account', id=f'check_user_{user.id}_permission_groups' ) ) return errors Django's default is to run checks on migration. If I deploy the app without an existing database, then when I run migrate to set up the database the above check will cause a ProgrammingError because the table is not yet created: django.db.utils.ProgrammingError: relation "accounts_account" does not exist How can I exclude this test from running on python manage.py migrate? I want to run this after the migration is complete.