Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get a list of all the Product Attributes associated with the Products displayed on a Product Category Page?
On the Product Category pages a set of Products are displayed using a HTML template with context from the view.py. In the sidebar of the HTML page, I want to display all the Product Attributes associated with the available Products on the page (here's an example). In other words, I want to access the Product Attributes in the template file of the Product Categories. The Product Attributes have the Product Categories as foreign keys, as seen in the code below. # views.py # class ProductCategoryListView(ListView): template_name = "products/product_categories.html" # Default fetch template location: <blog>/<modelname>_list.html #queryset = Product.objects.filter(categories_id = ) # e.g. id=1 def get_queryset(self): self.category = get_object_or_404(ProductCategory, slug=self.kwargs["slug"]) #id=self.kwargs["id"] return Product.objects.filter(categories=self.category) # categories_id=self.category.id #return Product.objects.filter(categories__contains = self.category.get_descendants(include_self=True)) def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Context of Product Category context['full_name'] = self.category.full_name context['ancestors'] = self.category.get_ancestors context['category'] = self.category context['descendant_count'] = self.category.get_descendant_count context['descendants'] = self.category.get_descendants(include_self=False) context['siblings'] = self.category.get_siblings(include_self=False) context['filter'] = ProductFilter(self.request.GET, queryset=self.get_queryset()) attributes = [] for product in Product.objects.filter(categories=self.category): attributes.append(...) context['attributes'] = attributes # Get attributes of the category return context # models.py # class ProductAttributes(models.Model): """ The Product Attributes Table contains product attributes or features for the product category. """ product_category … -
REST api for system admin
i am trying to understand what is special in REST api. I am from a infra admin background and for me a HTTP server handling GET, PUT and POST looks like a REST end point. is this magic lies in the word "framework". which define some standards for communication over HTTP. other than that it just like a webserver. example: GET /users is REST GET /users?id=user1 is not REST why the 2nd one is not REST? django vs django rest framework DRF? if i read a django code -- in urls.py urlpatterns = [ path('/users', views.get_user), ] -- in views.py def users(request): if request.method == "GET": return JsonResponse({'users':'all_users'}) if request.method == "POST": ## add user return JsonResponse({'success':'OK'}) is this /users endpoint is not REST? what will be the difference with DRF can anyone please explain this in a layman term people other than development background can understand? -
Issue Creating Django Models
I'm trying to create some new tables, through Django Models, but, everytime I try to Migrate the changes, appears the following error. It says it is a syntax error, though I can't detected. What I'm doing wrong? Operations to perform: Apply all migrations: RegistrarProyecto, admin, auth, contenttypes, sessions, vuelos Running migrations: Applying RegistrarProyecto.0008_auto_20210621_1223...Traceback (most recent call last): File "C:\Users\pansh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\pansh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: near ")": syntax error models.py from django.db import models from django.db.models.fields import CharField from django.db.models.fields import IntegerField # Create your models here. class Proyecto(models.Model): NombreProyecto = models.CharField(max_length = 64) ResponsableProyecto = models.CharField(max_length= 64) DescripcionProyecto = models.CharField(max_length = 64) def __str__(self): return f"{self.NombreProyecto}" views.py from django.http.response import HttpResponse from django.shortcuts import render from django.shortcuts import redirect from .models import Proyecto # Create your views here. def index (request): return render (request, "RegistrarProyecto/index.html", { "Proyecto": Proyecto.objects.all() }) def registro(request): if request.method == 'POST': NombreProyecto = request.POST.get('NombreProyecto') ResponsableProyecto = request.POST.get('ResponsableProyecto') DescripcionProyecto = request.POST.get('DescripcionProyecto') Proyecto.objects.create(NombreProyecto=NombreProyecto,ResponsableProyecto=ResponsableProyecto,DescripcionProyecto=DescripcionProyecto) return redirect("/RegistrarProyecto") return render(request, 'RegistrarProyecto/Registro.html') def financiamiento(request): return render(request,"RegistrarProyecto/financiamiento.html") -
Field '_id' expected a number but got 'top' in Django Rest Framework
I already seen this type of questions here but I am not able to reproduce the solution. I'm trying to get Top BlogPosts from my model in relation with their rating. #models.py class BlogPost(models.Model): _id = models.AutoField(primary_key=True, editable=False) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=100, null=True, blank=True) image = models.ImageField(null=True, blank=True, default='/placeholder.png' ) description = models.TextField(null=True, blank=True, help_text="Description Here ") rating = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) numReviews = models.IntegerField(null=True, blank=True, default=0) createdAt = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.createdAt) class BlogPostReview(models.Model): blogpost = models.ForeignKey(BlogPost, on_delete=models.SET_NULL, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True, blank=True) rating = models.IntegerField(null=True, blank=True, default=0) comment = models.TextField(null=True, blank=True) createdAt = models.DateTimeField(auto_now_add=True) _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return str(self.rating) Serializer #serializers.py class BlogPostReviewSerializer(serializers.ModelSerializer): class Meta: model = BlogPostReview fields = '__all__' class BlogPostSerializer(serializers.ModelSerializer): reviews = BlogPostReviewSerializer( many=True, read_only=True) class Meta: model = BlogPost fields = '__all__' def get_reviews(self, obj): reviews = obj.blogpostreview_set.all() serializer = BlogPostReviewSerializer(reviews, many=True) return serializer.data Now comes to Views ... Problematic one @api_view(['GET']) def getTopBlogPosts(request): blogposts = BlogPost.objects.filter(rating__gte=4).order_by('-rating')[0:10] serializer = BlogPostSerializer(blogposts, many=True) return Response(serializer.data) URLs #urls.py path('top/', views.getTopBlogPosts, name='top-blogposts'), When I try to load top posts this error comes ValueError: invalid literal for int() with base 10: 'top' ValueError: … -
How to generate a choices tuple for django models field to use in a form
Trying to create a choice field based on another model I want my choices to be mapped like username: first_name + last_name I tried doing something like this(Note, I am adding on user_choices and choices=user_choices. The model already existed before me making these changes.) Here's what my models.py looks like: from django.contrib.auth.models import User owner_choices = [ tuple(User.objects.values_list('username', 'first_name' + 'last_name')) ] class ErrorEvent(models.Model): """Error Event Submissions""" event_id = models.BigAutoField(primary_key=True) owner = models.IntegerField(verbose_name="Owner", blank=True, choices=owner_choices) and here's my forms.py from django import forms from .models import ErrorEvent class ErrorEventForm(forms.ModelForm): class Meta: model = ErrorEvent # fields = exclude = ['event_id'] widgets = { 'owner': forms.Select(), } Currently the owner_choices doesn't work, I get an error that says: ERRORS: app.ErrorEvent.owner: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. Any recommendations on what else I can try, or how would I go about fixing my problem? Thank you in advance! -
How to store the default value for a Django form in the database?
I have a page with bookmarks and I want to implement several types of sorting for them. The user chooses the type of sorting and it's stored in the database. He/she sees the chosen type of sorting as the default value for the select-menu. I wrote this: class BookmarksSortingForm(forms.Form): SORTING_CHOICES = [(1, "новым"), (2, "имени"), (3, "звёздам -"), (4, "звёздам +")] bm_sorting = forms.ChoiceField(SORTING_CHOICES) # https://stackoverflow.com/questions/6325681/passing-a-user-request-to-forms # In your view: form = MyForm(..., request=request) def __init__(self, *args, **kwargs): self.request = kwargs.pop("request", None) super().__init__(*args, **kwargs) self.fields['bm_sorting'].initial = BookmarksSortingForm.SORTING_CHOICES[self.get_current_sorting() - 1][1] def get_current_sorting(self): user = User.objects.get(username=self.request.user) return user.profile.bookmarks_sorting # small integer, default = 1 But I get "TypeError: init() takes 1 positional argument but 2 were given" at the line with bm_sorting. How could I fix this? Django version is 3.2.4. -
Django URL not rendering templates
Instead of directing me to the page django is simply returning the following error: “C:\Users\RodrigoPinto\Desktop\Insider\users\register” does not exist This is my url; from django.urls import path from users import employee_views from users import views as auth_views from django.contrib.auth.views import LoginView, LogoutView app_name = 'users' urlpatterns = [ path('login/', LoginView.as_view(template_name='users/login.html')), path('logout/', LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('register/', auth_views.Register.as_view, name='register'), path('profile/', auth_views.Profile.as_view, name='profile'), path('listView/', employee_views.AccountsListView.as_view, name='listView'), path('update/<pk>/', employee_views.AccountsUpdate.as_view, name='updateView'), path('password_update/<pk>/', employee_views.update_password, name='password_update'), path('delete/<pk>/', employee_views.AccountsDelete.as_view, name='deleteView'), ] and on the main app i have this inside the URL; from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from users import urls as user_urls app_name = "inside" urlpatterns = [ path('admin/', admin.site.urls), path('', include('inside.urls')), path('users/', include(user_urls)), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I've been over this code for the last two hours and I cant understand what I'm doing wrong. Maybe someone can see something that I'm missing. Also my template directory in settings is configured like this; template_dir = [ os.path.join(BASE_DIR, 'users', 'templates'), os.path.join(BASE_DIR, 'forums', 'templates'), ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': template_dir, 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Django app engine can not connect to db No such file or directory Is the server running locally and accepting connections on Unix domain socket
I have a Django app that I built, I am trying to upload the app into the app engine, but for some reason, I am getting the error could not connect to server: No such file or directory. Is the server running locally and accepting connections on Unix domain socket I already upload another Django app to GCP using the app engine, but this time is different; my guess is something about PostgreSQL. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'main', 'USER': os.getenv('USERNAME'), 'PASSWORD': os.getenv('PASSWORD'), 'HOST': os.getenv("HOST"), 'PORT': '5432' } } I tried removing the port, change it, etc.. locally. The app is running and can connect to the proxy; when I deploy the app, it can not connect. And I made sure I close the local connection before I deploy the app just in case. My old app is running with the same configuration except for engine 'django.db.backends.postgresql_psycopg2' The reason I change the engine here was that django postgresql -
NOT NULL constraint failed: users_profile.user_id django
I am trying to update the profile of a particular user and I have to update 2 different models and forms.. The User model and custom Profile model.. I also have 2 different forms, the UserUpdateForm and ProfileUpdateForm I am using class based views models.py: from django.db import models from django.contrib.auth.models import User from PIL import Image from django.urls import reverse User._meta.get_field('email')._unique = True class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='images/no_picture.jpg', upload_to = 'profile_pics') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.user.username} Profile' def save(self,*args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.avatar.path) if img.height > 300 or img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.avatar.path) def get_absolute_url(self): return reverse('profile', kwargs={'username': self.user}) views.py: class ProfileUpdateView(UpdateView): model = User template_name = "users/profile_update.html" success_message = "Your profile was updated successfully" slug_url_kwarg = 'username' slug_field = 'username' context_object_name = 'profile' fields = ['username', 'email'] second_form_class = ProfileUpdateForm def get_success_url(self): user = User.objects.get(username=self.request.user) return reverse_lazy("profile", kwargs={self.slug_url_kwarg:user}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["form2"] = ProfileUpdateForm(self.request.POST, self.request.FILES, instance = self.request.user.profile) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form2 = self.second_form_class(request.POST, request.FILES) if form2.is_valid(): form2.save() What is this error that I am getting and how to solve it? I have to … -
function .load() doesn't return data after submit form django
I've got a problem with the function .load() without refresh doesn't return data after submit form django.. I'm new in JS and Django. my view : def accueil(request): if request.method == 'POST': form_plot_one_way = plot_onewayForm(request.POST) if request.POST.get('Plot_one_way_analysis'): if form_plot_one_way.is_valid(): request.session['Key_plot_oneway_coverage'] = form_plot_one_way['Key_plot_oneway_coverage'].value() request.session['Key_plot_oneway_nb_interval']=form_plot_one_way['Key_plot_oneway_nb_interval'].value() listbox_values = [key for key in fig_dict.keys()] print("listbox values : " ) print(listbox_values) my html : <form action="{% url 'accueil' %}" id='form-Plot_one_way_analysis' method="POST" enctype="multipart/form-data" class="norefresh_load"> {% csrf_token %} <button type="submit" name="Plot_one_way_analysis" class="btn btn-primary" id="Plot_one_way_analysis" value="Plot_one_way_analysis" onClick="ModalWindows(this.id)">Plot One-way analysis </button> with the following size : {{ form_plot_one_way.Key_plot_oneway_coverage }} Maximal number of modalities for one variable : {{ form_plot_one_way.Key_plot_oneway_nb_interval }} </form> {{ listbox_values }} // i can't display it <div id="myModal-Plot_one_way_analysis" class="modal"> <!-- Modal content --> <div class="modal-content"> <div class="modal-header"> <span class="close">&times;</span> <h2>One way analysis</h2> </div> <div class="modal-body"> <p>Features</p> {{ listbox_values }} // also here i can't display it </div> <div class="modal-footer"> <h3>Export</h3> </div> </div> </div> my js : $('.norefresh_load').submit(function(e){ e.preventDefault(); // avoid to execute the actual submit of the form. console.log(e); let button_i = null; for(let i = 0; i < e.target.length; i++) { if(e.target[i].type == "submit") { button_i = i; break; } } if(button_i != null) { var button = $(e.target[button_i]); console.log(button.parents('form')); var id = $(this)[0].id; console.log(id); … -
How to check for `--keepdb` flag in Django
I've created an AppConfig that uses the post_migrate signal to run some extra SQL every time I do a migration. In my tests sometimes I use --keepdb to speed up running the tests but it's still triggering the post_migrate signal. How can I check to see if the --keepdb flag was used so I can skip running my extra SQL commands? I've looked in the Django documentation and the source code and I can't seem to find any way to do that. -
Static json file in Django project loads fine with python manage.py runserver but not with apache
I have a django rest framework project with a folder called data inside root directory. Inside data folder there is a json file used to store and read some internal app data, so this file is not sent to apps users. So, this file can be accessed from app when is run with python manage.py runserver, but when I use apache server a File not found error is thrown. What can I do about it? Thanks in advance. This is the project structure django_project └── venv ├── data ├── file.json └── django_project ├── init.py ├── settings.py ├── urls.py └── wsgi.py ├── manage.py And this is the apache config file for static files Alias /static /home/mach/django_project/data <Directory /home/mach/django_project/data> Require all granted </Directory> -
Django Request Session Value changes when accessed from another dev server port
I'm currently hosting two development servers on two different ports for the same Django App. I thought that by running the app on two different ports it would isolate the variables and make the two servers run independently. However, when I change a request.session variable on one of the ports, it also changes the value on the other port. Why does this happen? -
Get content elements and download images in BS4 and Django
Hola tengo el siguiente codigo en una pagina web de noticias y estoy trabajando en un proyecto de Django y Bs4 que pueda extraer información <article> <div class="top"> <div **class="cat"**> <a href="/futbol/">**Elimitarorias**</a> </div> <a href="https://radonss.us/archivo/2021-06-20" class="time"> <time class="x-ago" data-x="**2021-06-20T21:55:35-05:00**"> 20/06/21 </time> </a> </div> <div class="inner"> <figure class="holder"> <a href="https://www.gogole.com.pe" class="cover x-lazy loaded"> <span class="video"></span> <img src="**https://radonss.us/medium/2021/06/20/441644_1110204.jpg**" alt="**descripcion iagen** " pinger-seen="true"></a> </figure> <div class="cont"> <h2><a href="https://radonss.us/1343200">titulo</a></h2> <p><a href="**https://radonss.us/1342858**">**<strong>Titulo</strong>**</a>**&nbsp;descripcion de titulo.**</p> </div> </div> </article> Intento extraer article .top .cat a href article .top .cat a. article .top .time data-x. article .inner figure a img src. article .inner .cont h2 article .inner .cont p (only content p) article .inner .cont p strong (only content strong) Y estoy estancado en este codigo de prueba, pude extraer el h2 seleccionando la clase .cont pero quisiera algo mas refinado, ¿Como hago para seleccionar lo que requiero?, asi mismo quisiera obtener la ruta de la imagen o descargarla, ¿Pueden ayudarme? por favor import requests from bs4 import BeautifulSoup ht_r = requests.get("https://radonss.us/archivo/2021-06-20/") ht_soup = BeautifulSoup(ht_r.content, 'html5lib') ht_headings = ht_soup.findAll("div", {"class": "cont"},) ht_headings = ht_headings[:2] ht_h2 = [] ht_a = [] ht_img = [] for hth in ht_headings: article = Article(title=hth.h2.text, description=hth.p.text, image=hth.img.href) article.save() -
Django: What is the reverse equivalent of cascade?
I have found this post with the exact same title: Django - What is the reverse equivalent of cascade? It is exactly what I need, however the post is 10 years old. Is this still the best way to go about it, or is there a new way? -
Get Distinct object with sorted from lowest value to highest value in django
I want to sort the filter value from lowest to highest in Django. Here I'm getting this output: Now in this filter list, I want to show data to be filtered in ascending order and the blank data and none data to be not shown in o/p. something like this: cores [] 2 [] 4 [] 6 [] 8 . . . I try to code some this way. views.py filter_cores = Processor.objects.distinct().values('cores') How it will be filtered data in ascending order and I tried filter_cores = Processor.objects.distinct().values('cores').order_by('cores') but it scrambled data and nothing else. -
Cannot import '<app_name>'. Check that '<Config>' is correct
Given is my folder structure. In 'urls.py' of project- urlpatterns = [ path('admin/', admin.site.urls), path('', include('apps.job_main.urls')), ] In settings.py- INSTALLED_APPS = [ 'django.contrib.admin', . . 'apps.job_main' ] Complete error pastebin link Is my import correct or any suggestions would be helpful? Django Version=3.2.4 -
How to annotate the same value multiple times in django?
How to perform nested annotation on the same field. Example: Say you have two querysets that are a result of annotation, where foo is the annotation field qs1 = [ {user:1, foo:30}, {user:2, foo:10} ] qs2 = [ {user:1, foo:7}, {user:2, foo:5} ] after the combination of the querysets, I need to annotate a field called sum. combined = qs1 | qs2 result = combined.annotate(Sum('foo')) # The result of annotation will be print(result) [{user: 1, foo__sum: 37}, {user:2, foo__sum: 15}] But when attempting to do so, I get an error: FieldError: Cannot compute Sum('foo'): 'foo' is an aggregate -
How To Use Query Inside Django Model?
I Have 2 Different Django Model User_detials and Monthly_payment and now I want to make the Status= Active, Expire, Soon Expire, or Deactivated, in User details i am trying this but not work ho to make using 2 different model different fields using username and received date is any solution ?? here is my model class Client_Detials(models.Model, object): First_name = models.CharField(max_length=100) Last_name = models.CharField(max_length=100) Address = models.CharField(max_length=100) Contact_1 = models.CharField(max_length=100) Contact_2 = models.CharField(max_length=100) Email = models.EmailField() Username = models.CharField(max_length=20) Password = models.CharField(max_length=20) cont_type = ( ('Fiber', 'Fiber'), ('wireless', 'wireless'), ) Connection_Type = models.CharField(choices=cont_type, max_length=12, default='Fiber') Internet_Plan = models.ForeignKey(Nas_Package, on_delete=models.CASCADE) Payment_Cycle = models.CharField(max_length=100, blank=True) User_Img = models.ImageField(upload_to='Client', default='user.jpg', blank=True) Created_by = models.OneToOneField(User, on_delete=models.CASCADE) Created_Date = models.DateTimeField(auto_now=True) def status(self): recharge = recharge_monthly.username if recharge == self.Username: date_to_re = recharge_monthly.received_date myd = datetime.datetime.now().date() - date_to_re print(myd) if myd.days < 20: return "Active" elif myd.days < 25: return "Expire Soon" elif myd.days <= 30: return "Expire" else: return "Expire From {} day".format(30 - myd.days) class recharge_monthly(models.Model): username = models.ForeignKey(Client_Detials, on_delete=models.CASCADE) Total_amount = models.FloatField() Received_amount = models.FloatField(default=0.0) received_date = models.DateField(auto_now_add=True) is_vat_add = models.BooleanField() is_tsc_add = models.BooleanField() tsc_amount = models.FloatField() vat_amount = models.FloatField() -
Django Prefetch Related use effectively in Template
I have two models Quiz and Sitting Models.py class Quiz(models.Model): title = models.CharField(verbose_name=_("Title"),max_length=300, blank=False) description = models.TextField(verbose_name=_("Description"),blank=True, help_text=_("a description of the quiz")) url = models.SlugField(max_length=60, blank=False,help_text=_("a user friendly url"), verbose_name=_("user friendly url"),default=uuid.uuid4) class Sitting(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_("User"), on_delete=models.CASCADE) quiz = models.ForeignKey(Quiz, verbose_name=_("Quiz"), on_delete=models.CASCADE) views.py from django.db.models import Prefetch def getTestFest(request): if request.method == "GET" and request.is_ajax(): examtype = request.GET.get('examtype') print(examtype) if examtype=='M': exams = Quiz.objects.filter(Q(draft=False) ).prefetch_related(Prefetch('sitting_set',queryset=Sitting.objects.filter(user=request.user))).all() else: exams = Quiz.objects.filter(Q(draft=False)).prefetch_related(Prefetch('sitting_set',queryset=Sitting.objects.filter(user=request.user))).all() context={ "exams": exams, } #exams.filter(sitting.user==request.user) print(exams) return render(request, 'testfest/exams.html',context) My Template: {% for exam in exams %} <div > {% for sitting in exam.sitting_set.all%} {% if sitting %} Exam Completed {% else %} {% endif %} {% endfor %} <div class="pass__footer"> <div class="pass-cta" ><a type="button" class="btn buynow btn-block btn--pass btn-primary exams" id="b_{{exam.id}}" style="text-decoration: none; font-size: 15px !important;" href="/quiz/{{exam.url}}" >Start Exam</a> </div> </div> </div> {% endfor %} I would like to display the link "Start Exam" only if the there is no entry in Sitting for that quiz and user. The template successfully displays "Exam Taken" however, I am not able to figure out the else part. Any suggesstions. -
I am using LoginRequiredMixin in Django. If I type the url in search bar it shows the page without being logged in
I am using LoginRequiredMixin in a django class view AdCreateView which is binded to the url /create. When I type the whole url it goes to the page even if I'm logged out but if I click on the create button from anywhere else on the site it redirects to the login page. I would like for it to redirect to the login page in both cases. My urls.py path('', AdListView.as_view(), name='list'), path('create/', AdCreateView.as_view(), name='create'), views.py class AdCreateView(LoginRequiredMixin, View): template_name = 'ads/ad_form.html' success_url = reverse_lazy('ads:list') def get(self, request, pk=None): form = CreateForm() ctx = {'form': form} return render(request, self.template_name, ctx) def post(self, request, pk=None): form = CreateForm(request.POST, request.FILES or None) if not form.is_valid(): ctx = {'form': form} return render(request, self.template_name, ctx) # Add owner to the model before saving pic = form.save(commit=False) pic.owner = self.request.user pic.save() form.save_m2m() return redirect(self.success_url) -
Access form 'fields' in django View class
I am trying to access the 'fields' attribute in my Class based View Here's an example of what my forms.py looks like: from django import forms from .models import ErrorEvent class ErrorEventForm(forms.ModelForm): class Meta: model = HumanErrorEvent # fields = exclude = ['event_id', 'user_modified', 'date_modified'] widgets = { 'owner': forms.TextInput(), } Then here's my views: class ErrorCreateView(CreateView): template_name = "forms/form.html" form_class = ErrorEventForm model = ErrorEvent def get_context_data(self, **kwargs): if not self.request.user.groups.filter(name='leaders').exists(): self.form_class.fields['owner'].widget = forms.HiddenInput() context = super(ErrorCreateView, self).get_context_data(**kwargs) return context The error I am getting is: AttributeError: type object 'ErrorEventForm' has no attribute 'fields' Due to this line: self.form_class.fields['owner'].widget = forms.HiddenInput() Is it not possible to access the 'fields' attribute in the views? If not, is there a way to hide the 'owner' form field based on the group the user is in? Thank you for all your help in advance! -
Django 3 - How to populate HTML Select from Database?
I need to build a Python/Django web app, where the category/subcategory data could run between 100 and 200 rows and will be changing with time. On DJango 3.2.4, I am trying to figure out how can i achieve this? I only have the following link from the DJanago ref: https://docs.djangoproject.com/en/3.2/ref/models/fields/ but it only mentions the topic "Database Representation", without giving any detailed explanation or a concrete example. Perhaps I am missing something here, but would be grateful, if I could be directed to a right resource. -
django model value not geting updated cbv
I am trying to update a profile and I am using Class based views views.py: class ProfileUpdateView(UpdateView): model = User template_name = "users/profile_update.html" success_message = "Your profile was updated successfully" slug_url_kwarg = 'username' slug_field = 'username' context_object_name = 'profile' fields = ['username', 'email'] def get_success_url(self): return reverse_lazy("profile", kwargs={self.slug_url_kwarg:self.kwargs['username']}) If I don't update anything and click on the update button, it redirects me to my profile page.. But if I update, it does not redirect me but rather, it stays is the same page. What am I missing here? profile_update.html: {% extends 'log/base.html' %} {% block content %} {%load crispy_forms_tags %} <div class='container mt-4'> {% if profile.username == user.username %} <form method='POST' autocomplete="off" enctype="multipart/form-data" > {% csrf_token %} <fieldset class='form-group'> <legend class='border-bottom mb-4'>Update Profile</legend> {{ form | crispy }} </fieldset> <div class='form-group'> <button class='btn btn-outline-info' type='submit'>Update</button> </div> </form> {% endif %} </div> {% endblock content %} profile.html : {% extends 'log/base.html' %} {% block content %} {%load crispy_forms_tags %} <title>Error logger - Profile {{ profile.username }}</title> <div id='profile' class="content-section card p-4"> <div class="media"> <img class="rounded-circle account-img" src="{{ profile.profile.avatar.url }}"> <div class="media-body"> <h2 class="account-heading">{{profile.username}} </h2> <p >{{profile.email}}</p> <p>Created on: {{ profile.profile.created }}</p> {% if profile.username == user.username %} <p>Last updated on : … -
use rest_framework_simplejwt with Django 1.11.x and Python 3.6.2
I have an app that is using Django 1.9.2 and python 2.7. Now I wanted to use the simple JWT solution on a REST API and started to upgrade the app to Django 1.11.29 and Python 3.6.2. I cannot upgrade to Django 2.x at a reasonable cost ;-) When I use the url for access token, I am getting correctly my pair of access token and a refresh token back. But when I use refresh token url -X POST \ -H "Content-Type: application/json" \ -d '{"refresh":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImNvbGRfc3R1ZmYiOiLimIMiLCJleHAiOjIzNDU2NywianRpIjoiZGUxMmY0ZTY3MDY4NDI3ODg5ZjE1YWMyNzcwZGEwNTEifQ.aEoAYkSJjoWH1boshQAaTkf8G3yn0kapko6HFRt7Rh4"}' \ http://localhost:8000/api/token/refresh/ I should get back my access token like "access": "eyJ0eXAiOiJ.........." } But I get a response like { "username": [ "this field is required" ], "password": [ "this field is required" ] } I mocked up another super-limited Django app running under Django 2.2.2 and things behave like required. Can anyone help me on this?