Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to access request headers in decorator - django 4.0.4
Using class based views. I have a decorator that retrieves headers for verification. However I get this error accessing the request headers in the decorator: Decorator exception 'DetailsView' object has no attribute 'headers' I must emphasize that accessing request headers in the view function works fine. View function: class DetailsView(View): @check_access def get(self, request): res = { 'status': 200, 'response': 'heeaders test.', 'test': 'okay' } return HttpResponse(JsonResponse(res, safe=False), content_type='text/json') Decorator: def check_access(): def decorator(view_function): def wrap(request, *args, **kwargs): try: print("headers", request.headers) return view_function(request, *args, **kwargs) except Exception as e: return HttpResponse('Unauthorized', status=401) return wrap return decorator Kindly assist. Thanks in advance. -
Django rest framework function base view how to get object by string not id
Problem: I trying to path like this --> path('Image/<str>', views.getImage, name='imageCategory'), to get image filter by category --> http://127.0.0.1:8000/Image/TV #-->Model.py from django.db import models class Post(models.Model): Topic = models.CharField(max_length=250, default='') Desc = models.CharField(max_length=750, default='') Link = models.TextField(default='') def __str__(self): return str(self.Topic) class Category(models.Model): categoryName = models.CharField(max_length=50, default='') def __str__(self): return str(self.categoryName) class PostImage(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, null=True, related_name='post_name') category = models.ForeignKey( Category, on_delete=models.CASCADE, null=True, related_name='category_name') images = models.FileField(upload_to='images/') def __str__(self): return str(self.post) #-->Serializer.py from rest_framework.serializers import ModelSerializer from rest_framework import serializers from .models import Post, PostImage class BlogSerializer(ModelSerializer): class Meta: model = Post fields = '__all__' class ImageSerializer(ModelSerializer): topic_link = serializers.CharField(source='post.Link', read_only=True) Category = serializers.CharField(source='category', read_only=True) class Meta: model = PostImage fields = '__all__' #-->view.py from django.shortcuts import render from rest_framework.decorators import api_view from rest_framework.response import Response from .models import Post, PostImage from .Serializer import BlogSerializer, ImageSerializer # Create your views here. @api_view(['GET']) def getNames(request): Blog = Post.objects.all() serializer = BlogSerializer(Blog, many=True) return Response(serializer.data) @api_view(['GET']) def getName(request, pk): Blog = Post.objects.get(id=pk) serializer = BlogSerializer(Blog, many=False) return Response(serializer.data) #my problem part @api_view(['GET']) def getImage(request): image = PostImage.objects.get(Category=request.Category) serializer = ImageSerializer(image, many=True) return Response(serializer.data) #-->urls.py from django.urls import path from . import views urlpatterns = [ path('blogs/', views.getNames, name='blog'), path('blogs/<pk>', … -
How to redirect to new blog post in React/Django
I'm building a blog site with React/Django. Here's my basic NewBlog component: import React, {useState} from 'react'; import { Link } from 'react-router-dom'; function NewBlog(props) { const [title, setTitle] = useState('') const [body, setBody] = useState('') function postBlog() { fetch('http://localhost:8000/api/blogs/', { "headers": { "content-type": "application/json", }, "body": JSON.stringify({ "title": title, "author": 1, "body": body }), "method":"POST", }) } return ( <div> <form onSubmit={postBlog}> <textarea className='title' placeholder='title...' onChange={(ev) => setTitle(ev.target.value)} value={title}></textarea> <textarea className='body' placeholder='' onChange={(ev) => setBody(ev.target.value)} value={body}></textarea> <button>POST</button> </form> <div> <Link to='/blog'>BACK</Link> </div> </div> ); } export default NewBlog; This works to POST a new blog, but after I submit the form, I can't figure out how to redirect to that specific blog, which would just be http://localhost:8000/blogs/BLOG_ID. Instead, the form is just cleared, and I have to go <Link to='/blog'>BACK</Link> to the BlogList to see the new blog rendered. Now, I know with Django you can use their form to post a blog, and, once posted, it redirects to that blog_detail. My issue is I don't know how to do that using React on the front end. Is there some kind of Redirect or Route I can use? Also, I'm not sure how I'd even retrieve that just-posted blog's … -
Django Leaflet: Add form fields for latitude and longitude
I am using the django-leaflet package to display the map in the django admin for a PointField. However, I wanted to put fields so that it would be possible to write the latitude and longitude, as an alternative to selecting the point on the map. How can I add these fields to the form? Note: the Django Map Widgets package has the ability to insert coordinates, but I don't want to use it because it requires a key. -
Django FormView dispatch method is called, even though UserPassesTestMixin's test_func() has returned False
I have a class based form view that implements both LoginRequiredMixin and UserPassesTestMixin class BookingCreateView(LoginRequiredMixin, UserPassesTestMixin, FormView): def dispatch(self, request, *args, **kwargs): ... def test_func(self): return is_customer(self.request.user) When I visit the page while logged in as a user that fails the test_func, instead of getting a 404, as a result of a failed test_func, the code in my view's dispatch method is executing... Shouldn't the test_func() be called before dispatch() ? and if the result of test_func() is False, shouldn't view rendering stop at this point? -
Are "required" HTML fields not enforced on Django Admin intermediate pages?
I have the following abbreviated HTML for an intermediate Django admin page: <!DOCTYPE html> {% extends base_url %} {% block content %} <form action="" method="post"> ... <select name="my_name" id="my_id" required> ... </select> ... <input type="hidden" name="action" value="my_action" /> <input type="submit" name="apply" value="Update" /> </form> {% endblock %} However, my required attribute does not seem to work, and clicking "Update" submits the form even if no selection has been made. Am I missing something special about how Django builds intermediate pages? Happy to provide more code if needed, just removed most of it for brevity's sake. -
How can I filter a modelformset_factory?
I have been coding a personal project in which several user can post educational videos (each video has a language, a foreignkey). I tried to implement a function in which a user add a word to a video (or a various words). But I couldn't to filter a modelformset_factory to show only words that have the same video's language. For instance: Below I have a class which its language is 'inglês', I can see it in de 'aula_lingua'. But my combo box shows words that have another languages, for example the word 'test Norsk_noruegues' which has 'noruegues' as its language. But I would like to filter the words and show only words that have the same laguange of the video. enter image description here Models: class Palavra(models.Model): palavra = models.CharField(max_length=40) lingua = models.ForeignKey( Lingua, null=True, blank=True, on_delete=models.CASCADE) class Aula(models.Model): aula = models.CharField(max_length=250) aula_gravada = models.FileField(upload_to='aula/%Y/%m') lingua = models.ForeignKey( Lingua, blank=True, null=True, on_delete=models.CASCADE) class AulaPalavra(models.Model): aula = models.ForeignKey(Aula, on_delete=models.CASCADE) palavra = models.ForeignKey(Palavra, on_delete=models.DO_NOTHING) Formset: PalavraAulaForms = modelformset_factory( models.AulaPalavra, fields=('palavra',), extra=1, ) View: class TesteAdicionaPalavraAula(TemplateView, DetailView): template_name = 'ensino/teste_add_palavra.html' model = Aula def get(self, *args, **kwargs): formset = PalavraAulaForms( queryset=Palavra.objects.filter( lingua=self.get_object().lingua ) ) return self.render_to_response( { 'add_palavra': formset, 'aula': self.get_object(), }, ) … -
Django: how to delete item in one model AND change many to many relationship in another model that was linked to the first model?
This website allows users to select Rolling Stones concerts they've been to. It will add the Concert and the Song to the model from the API if they select it. And Concert.song has a many to many relationship with the user model. If a user removes a concert from their concert list, the songs still appear. I don't necessarily want the song to be deleted because they could have heard the song from another concert. I also don't think it's the best idea to change the user of the song from the usernmae to --- (because null=True). I think my only choice is to change the usersonglist.html template tags somehow? Models.py class Concert(models.Model): venue = models.CharField(max_length=200, null=True) concertid = models.CharField(max_length = 200, null=False, default='didnotsaveproperly') date = models.DateField(null=True) city = models.CharField(max_length=100, null=True) country = models.CharField(max_length=200, null=True) user = models.ForeignKey(USER_MODEL, related_name="concerts", on_delete=models.CASCADE, null=True) song = models.ManyToManyField("Song", blank=True, null=True) def __str__(self): return str(self.concertid) + " " + str(self.venue) + " " + str(self.date) class Song(models.Model): name = models.CharField(max_length = 100, null=True) user = models.ForeignKey(USER_MODEL, related_name="songs", on_delete=models.CASCADE, null=True) def __str__(self): return self.name URLS.py urlpatterns = [ path("", views.display_concerts, name="choose_concerts"), path('add/<str:concertdict>/', views.log_concert_and_song, name='concert_add'), path('userconcerts/', views.ConcertListView.as_view(), name='user_concert_list'), path('<int:pk>/delete/', views.ConcertDeleteView.as_view(), name='delete_concert'), path('usersonglist/', views.SongListView.as_view(), name='user_song_list'), ] Views.py/SongListView for … -
How to get a field from another model which is linked with OneToOne relationship?
I have my main User model with an 'email' field (and other fields). But I created another model called Profile, where I need to pass user's email to it. models.py for user: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, unique=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UserManager() and for profile: class Profile(models.Model): user = models.OneToOneField('authentication.User', on_delete=models.CASCADE) phone_number = models.IntegerField(blank=True, unique=True) is_subscribed = models.BooleanField(default=False) email = ... Task sounds quite simple, but using user.email doesn't seem to work as well as user__email or a user.get_email property. What should I write instead of ... ? -
How to change ON expression in django-orm select_related()
So i have this models class ApplicationForHelp(BaseModel): user = models.ForeignKey(User, related_name="applications", on_delete=models.CASCADE) tags = models.ManyToManyField(TagsForApplication, related_name="applications") title = models.CharField(max_length=50) description = models.TextField() is_anonymous = models.BooleanField(default=False) place = models.TextField(null=True) And user model so if do ApplicationForHelp.objects.filter().select_related('user') what it does : left join ON application.user_id = user.id what i want : left join ON (application.user_id = user.id and application.is_anonymous=False) -
module 'popenv.core' has no attribute 'project'
Trying to assist my friend set up a new Django/Python project remotely. They've set up a virtual environment on their Windows machine using Linux, and it throws the following error when trying to install Django in the project directory: Creating a virtualenv for this project… Using /usr/bin/python3.8 (3.8.10) to create virtualenv… /usr/bin/python3: No module named pipenv.pew Virtualenv location: Installing django… Looking in indexes: https://pypi.python.org/simple Requirement already satisfied: django in /home/[username]/.local/lib/python3.8/site-packages (4.0.4) Requirement already satisfied: backports.zoneinfo; python_version < "3.9" in /home/[username]/.local/lib/python3.8/site-packages (from django) (0.2.1) Requirement already satisfied: asgiref<4,>=3.4.1 in /home/[username]/.local/lib/python3.8/site-packages (from django) (3.5.2) Requirement already satisfied: sqlparse>=0.2.2 in /home/[username]/.local/lib/python3.8/site-packages (from django) (0.4.2) Adding django to Pipfile's [packages]… Creating a virtualenv for this project… Using /usr/bin/python3 (3.8.10) to create virtualenv… /usr/bin/python3: No module named pipenv.pew Virtualenv location: Pipfile.lock not found, creating… Locking [dev-packages] dependencies… 3/dist-packages/pipenv/resolver.py", line 52, in main project = pipenv.core.project AttributeError: module 'pipenv.core' has no attribute 'project' Does anyone have experience with this error and how to resolve it? -
How to assign a link to a certain item in a list in Django?
a created a table in which it contains names for datasets in a column, and the links to view these datasets in another column. My aim is to retrieve the dataset in which it was clicked to be reviewed. Here is the HTML Code <table> <tr> <th>File Name</th> <th>Link</th> {% for files in names %} <tr> <td> {{ files }} </td> <td> <a href="{% url 'single-dataset' id=files %}">View Dataset</a> </td> </tr> {% endfor %} </tr> </table> Single-dataset is the page that will view each dataset separately Here is the Views.py Code def read_datasets(request, id): file = requests.post.objects.get(id=id) path = r"C:/Users/user/Desktop/Fault Detection App/Uploaded_Datasets/" path1, dirs, files = next(os.walk(path)) file_count = len(files) print(file_count) dataframes_list_html = [] file_names = [] for i in range(file_count): temp_df = pd.read_csv(path+files[i]) print(files[i]) dataframes_list_html.append(temp_df.to_html(index=False)) file_names.append(files[i]) return render(request,'blog/view_datasets.html',{'dataframes':dataframes_list_html, 'names': file_names}) and finally the urls.py path('view_dataset/', views.read_datasets, name = 'view_dataset'), path('test/', views.one_dataset, name='single-dataset'), I want to click on one of the links that says View Dataset and be able to retrieve the right dataset in the single-dataset page. -
Redirect and Login to Django from External Site
I'm building a signup page for my Django application on an external site. Once a user has completed signup, I create a user and they should be redirected to a Django site and logged in. I'm having trouble redirecting an external user to an authenticated page. Does anyone have any idea how to do this or if it's possible? Thanks! -
PUT Request not Updating data-Django
So I am using Postman to get my request. My GET and POST appear to be working fine. It's only when I go to update the data with PUT that its where I am running into the hiccup. Postman actually sends data back as if the object is being updated, but when I go to check via GET it's the same data as before. I have tried adding the hive data to the serializer.save, but it tells me I'm adding too many parameters. Any help will be greatly appreciated here. models class Inspection(models.Model): hive = models.ForeignKey(Hive, on_delete=models.CASCADE) user = models.ForeignKey(User,on_delete=models.CASCADE) eggs = models.IntegerField() larvae = models.IntegerField() sealed_brood = models.IntegerField() covered_bees = models.IntegerField() nectar_honey = models.IntegerField() pollen = models.IntegerField() pest_spotted = models.CharField(max_length=200) pest_action = models.CharField(max_length=200) notes_concerns = models.CharField(max_length=300) `` **serializers** class InspectionSerializer(serializers.ModelSerializer): class Meta: model = Inspection fields = ['id', 'eggs', 'larvae', 'sealed_brood', 'covered_bees', 'nectar_honey', 'nectar_honey', 'pollen', 'pest_spotted', 'pest_action', 'notes_concerns','user_id','hive','hive_id'] depth = 1 hive_id = serializers.IntegerField(write_only=True) VIEWS @api_view(['GET', 'POST','PUT']) @permission_classes([IsAuthenticated]) def inspection_details(request, pk): hive = get_object_or_404(Hive, pk=pk) inspection = Inspection.objects.filter(hive_id = hive.id, user=request.user) if request.method == "GET": serializer = InspectionSerializer(inspection, many=True) return Response(serializer.data, status=status.HTTP_200_OK) elif request.method == 'POST': serializer = InspectionSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save(user=request.user) return Response(serializer.data,status.HTTP_200_OK) elif request.method == 'PUT': serializer … -
Value does not change in admin dashboard and html template, view function shows the correct one
Value does not change in admin dahboard and html template that has a tag of the value, inrthe view function where the change happens,it print the correct value that was changed (order.status) def chef_order(request): chef = request.user.vendor orders = chef.orders.all() if 'btnform1' in request.POST: orderid = request.POST.get("orderid") order = Order.objects.get(pk=int(orderid)) sts = 'confirmed' order.status = "confirmed" print(order.get_status_display()) -
Special character encoding added - PDF Django
I have a function to create a simple PDF. But when working on special characters, it returns something like that. How do I correctly save characters such as śćźż in my pdf file? Views.py (oficial doc) def some_view_aa(request): # Create a file-like buffer to receive PDF data. buffer = io.BytesIO() # Create the PDF object, using the buffer as its "file." p = canvas.Canvas(buffer) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(100, 100, "Hello AZX AĄĄŻĄ world.") # Close the PDF object cleanly, and we're done. p.showPage() p.save() # FileResponse sets the Content-Disposition header so that browsers # present the option to save the file. buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='hello.pdf') -
Why Django sessions is slow while variable working faster?
I have Django view def load(request): store = request.GET.getlist('store', 'None') text = connetction_local(store[:-1]) for _ in tqdm(range(1), desc='session TEXT'): # globals.text = text request.session['text'] = text for _ in tqdm(range(1), desc='session STORE'): # globals.store = store[:-1] request.session['store'] = store[:-1] return redirect('index') in view i am getting some values store and then create variable text with function. Then put theese variables in request.session to laod from another views and never lost added tqdm to check how long time takes each operation. after that just redirect to another view. But there is some problem what i didn't understand. When i put variables in django sessions then after last request.session['store'] = store[:-1] redirect takes some time 5 - 10 sek, but if i open both globals. and remove sessions, then this process takes less time than with sessions anybody can explain what there is going on? -
problems with get_context_data in ListView (django)
I need to show in a template two models: models.py: class Dimension(TimeStampedModel): level = models.ForeignKey('Level', verbose_name=_('Level'), on_delete=models.CASCADE) name = models.CharField(verbose_name=('Name'), max_length=200) active = models.BooleanField(verbose_name=_('Active'), default=True) sort_order = models.PositiveIntegerField(verbose_name=_('sort order'), default=0) class Meta: verbose_name = _('Dimension') verbose_name_plural = _('Dimensions') def __str__(self): return self.name class Subdimension(TimeStampedModel): dimension = models.ForeignKey('Dimension', verbose_name=_('Dimension'), on_delete=models.CASCADE) name = models.CharField(verbose_name=('Name'), max_length=200) active = models.BooleanField(verbose_name=_('Active'), default=True) sort_order = models.PositiveIntegerField(verbose_name=_('sort order'), default=0) objects = managers.SubdimensionManager() class Meta: verbose_name = _('Subdimension') verbose_name_plural = _('Subdimensions') def __str__(self): return self.name and created a ListView of this views.py class DimensionListView(generic.ListView): model = models.Dimension template_name = 'dimension.html' context_object_name = 'dimensions' @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): self.user = self.request.user self.level = self.get_level(pk=kwargs.get('level_pk')) return super(DimensionListView, self).dispatch(request, *args, **kwargs) def get_level(self, pk): level = get_object_or_404(models.Level, pk=pk) return level def get_queryset(self): queryset = super(DimensionListView, self).get_queryset() return queryset.filter(active = True, level = self.level) def get_context_data(self, **kwargs): context = super(DimensionListView, self).get_context_data(**kwargs) context['subdimensions'] = models.Subdimension.objects.filter(active=True, dimension__level=self.level ) return context dimension_list_view = DimensionListView.as_view() I need to created a filter of the same 'dimension' so that in the template show only the subdimensions of that dimension. my template dimension.html: {% include 'base.html'%} {% block content %} <div class="row"> {% for dimension in dimensions %} <div class="col"> <div class="card" style="width: 18rem;"> <a class="">{{dimension.name}}</a> <div … -
Is there a way to set Mixin Django Admin action parameters within the model?
So I have a working Mixin for an action that currently operates on all fields of the queryset. Instead of this, I would like the ability to specify which fields will be used by the action via the code for the Admin page. For context, here is a brief portion of my Mixin: class MyMixin: def my_action(self, request, queryset): model_to_update = apps.get_model( app_label=<my_app>, model_name=queryset.first().__class__.__name__) ... for field in model_to_update._meta.get_fields(): # do cool stuff with all fields ... return render(...) Here is how the mixin is incorporated currently: ... @admin.register(<Model>) class ModelAdmin(MyMixin): ... actions = ["my_action"] ... ... and what I would like to do is something along the lines of: ... @admin.register(<Model>) class ModelAdmin(MyMixin): ... actions = [my_action(fields=['foo', 'bar',]] ... ... where foo and bar are a subset of the fields of ModelAdmin. Thank you in advance for any ideas! Apologies if this has already been asked elsewhere and I'm just phrasing it differently. -
Django custom user not able to log in from web app but works fine in Admin
I have created an App called "myapp" with custom user called "CustomUser" along with a custom user app called "customuser". I am able to successfully login from the admin. But I am not able to login from the app login. Here is the login function: def login(request): if request.method == 'POST': email=request.POST.get('email') password=request.POST.get("password") user = authenticate(request,email=email,password=password) if user is not None: auth_login(request,user) messages.success(request,'You are logged in') else: messages.error(request,"invalid login credentials") return redirect(login) return redirect(request,'myapp/home.html') else: form = AuthenticationForm() return render(request,'customuser/login.html', {'form':form}) Here is the admin from customuser.forms import * from customuser.models import Profiles class UserAdmin(BaseUserAdmin): # The forms to add and change user instances form = UserChangeForm add_form = UserCreationForm filter_horizontal=() list_display = ('email', 'FirstName','LastName', 'last_login','is_active','date_joined','is_admin') list_filter = ('is_admin','is_staff') fieldsets = ( (None, {'description': ( "Enter the new user's name and email address and click save." " The user will be emailed a link allowing them to login to" " the site and set their password." ), 'fields': ('email', )}), ('Password', { 'description': "Optionally, you may set the user's password here.", 'fields': ('password',), 'classes': ('collapse', 'collapse-closed'), }), ('Personal info', {'fields': ('FirstName','LastName')}), ('Permissions', {'fields': ('is_admin','is_staff')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password', 'FirstName','LastName', 'is_admin'), }), ) search_fields … -
How to pass variable data into empty dictionaries
I am trying to push data into empty dictionaries while doing this I add two for loops but I want to return two loops in one variable. d = { "result":[], "out":[] } quest = Question.objects.annotate(choice_count=Count('choice')) ans = Answer.objects.annotate(solution_count=Count('solution')) for i quest: d["quest "].append(i) print(d) for i ans: d["out"].append(i) print(d) return Response({'data':{'staus':d}} -
Django forms.DateInput putting leading zeroes in production because of linux
So I have date inputs in my site where I need the dates to have no leading zeroes in the month or day column which works in my development environment which is a windows machine. 'date_filed': DateInput( format=('%#m/%#d/%Y') But when I push this into my azure production which runs on a linux machine the leading zeroes come back because linux uses format=('%-m/%-d/%Y') instead of format=('%#m/%#d/%Y') Anybody have any suggestions than switching machines? Here is the rest of my form class if that matters class FormClass(ModelForm): class Meta: model = SomeModel fields = "some field names" widgets = { 'date_filed': DateInput( format=('%#m/%#d/%Y'),attrs={ }), -
Django many-to-many raw query
I'm working with a Spotify playlist dataset in Django. I have the following models. class Artist(models.Model): uri = models.CharField(max_length=255) name = models.CharField(max_length=255) class Track(models.Model): uri = models.CharField(max_length=255)= name = models.CharField(max_length=255) artist = models.ManyToManyField(Artist) duration_ms = models.IntegerField() class Playlist(models.Model): pid = models.IntegerField() name = models.CharField(max_length=255) collaborative = models.BooleanField(default=False) tracks = models.ManyToManyField(Track) num_followers = models.IntegerField() Django created the through model for playlist_tracks with the fields: class playlist_tracks(models.Model): id = models.IntegerField() playlist_id = models.IntegerField() track_id = models.IntegerField() I have a section in the track detail template where I would like to make recommendations for other tracks. Loop through each playlist and make an entry that tallies all the other tracks in that playlist. If that track appears in the next playlist, increment the counter, otherwise, add it to the table. Once the loop is complete, order by descending, and limit to 10. This SQL query does what I want in the SQLite viewer, however, I can't work out what the django syntax for writing this query should be. SELECT *, count(track_id) as num_occurences FROM spotify_playlist_tracks WHERE playlist_id in ( SELECT playlist_id FROM spotify_playlist_tracks WHERE track_id = 26(***arbitrary pk) ) GROUP BY track_id ORDER BY num_occurences DESC LIMIT 10 Including it as a model … -
how to make the captcha have a bootstrap class?
I have a problem with the captcha, I'm using the ¨Django Simple Captcha¨ the problem is that it doesn't let me place a bootstrap class so that the input has a better appearance. I tried to: I Put widget_tweaks in that input, but it does not send the data correctly and marks errors html <label class="form-label">Captcha</label> {% render_field form.captcha class="form-control" %} From forms I placed a class inside the widget, but it doesn't work forms.py class RegisterForm(UserCreationForm): captcha=CaptchaField(widget=forms.TextInput(attrs={'class': 'form-control'})) I took the input id and edit it in my style.css but the bootstrap class is not visible either style.css #id_captcha_1{ height: 34px; padding: 6px 12px; font-size: 14px; line-height: 1.42857143; color: #555; background-color: #fff; background-image: none; border: 1px solid #ccc; border-radius: 4px; } Any ideas for that input to have the bootstrap class? -
Django: Response from two models with one view
I have the following models: class Message(models.Model): timestamp = models.DateTimeField(default=None) messageId = models.CharField(max_length=256) userId = models.ForeignKey(User, on_delete=models.CASCADE) chatId = models.ForeignKey(Chat, on_delete=models.CASCADE) class Meta: abstract = True class Text(Message): message = models.TextField() translation = models.TextField(blank=True) def __str__(self): return self.message def image_directory_path(instance, filename): return '{0}/images/{1}'.format(instance.userId, filename) class Image(Message): image = models.ImageField(upload_to=image_directory_path) description = models.CharField(max_length=128, blank=True) Now I want to make a get request to /endpoint/ and response with a combination of text and images ordered by the timestamp. How can I do that?