Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Two divs in same row when click on one expand both tailwind css Django alpine js
image before opening div image after clicking on div CODE SNIPPET <div x-init x-data="{expanded: false}" :class="expanded ? 'h-full' : 'h-12'" class="w-full md:w-48/100 flex flex-col"> <div @click="expanded = !expanded" class="flex items-center px-10 py-4 border-b bg-white rounded-lg cursor-pointer"> <div class="font-bold font-lato text-xsm bg-white">{{ value.question }}</div> <div class="ml-auto p-2"> <svg width="8" height="6" viewBox="0 0 8 6" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M7.77083 0.937549C7.68535 0.850049 7.57545 0.812549 7.46555 0.812549C7.35565 0.812549 7.23354 0.862549 7.16027 0.937549L4.03424 4.11255L0.932622 0.937549C0.847145 0.850049 0.725034 0.800049 0.615134 0.800049C0.505234 0.800049 0.383123 0.850049 0.309857 0.925049C0.138902 1.10005 0.138902 1.38755 0.309857 1.56255L3.71675 5.06255C3.8877 5.23755 4.16856 5.23755 4.33951 5.06255L7.75862 1.57505C7.94178 1.40005 7.94178 1.11255 7.77083 0.937549Z" fill="#080F33"> </path> </svg> </div> </div> <div x-show="expanded" class="px-10 py-4 text-left font-lato bg-gray-50 text-gray-500 flex-1"> {{ value.answer|richtext }} </div> -
Using CSS Grid on a Django Template
I have a div container in my HTML which displays a list of 10 parsed headlines from The Toronto Star. I want to be able to display them in a repeating grid that looks like this: Here's the example image ( I can't add images since I dont have 10 reputation yet ) Here's the django template that I have : <div id="container"> <div class="containers"> {% for n, i in toronto %} <center><img src="{{i}}"></center> <h3>{{n}}</h3> {% endfor %} </div> Would highly appreciate any help :) -
Django: Include a template containing a script tag into another script tag
I want include a html file containing a script tag like this: <script>$('#page-content').html('{% include "title.html" %}');</script> title.html: <script>document.title = "Hello World!"</script> result: <script>$('#page-content').html('<script>document.title = "Hello World!"</script>');</script> Sadly, this will render incorrectly in the browser and I'm not quite sure how to solve it best -
Django error: Relation "<name>" already exists
I am attempting to run migrations on an existing model where i am adding a history field/table via the django-simple-history. I initially ran made and ran the migrations and then ran python manage.py populate_history --auto to generate the initial change for the pre-existing model. This created a new table in the DB and now when i try and re-run migrations, i get the error that relation <name> already exists. Do i have to delete/drop the table for the db? -
what does "weight" in "SearchVector" django?
Can you explain to me what role "weight" play in the SearchVector? for example in this code: vector = SearchVector('body_text', weight='A') + SearchVector('blog__tagline', weight='B') -
django json.loads() of string of list
I'm trying to save a list of ids as a string and then turn it back to a list and use it's values for filtering a queryset. So first I do something like this - my_items_ids = list(Item.objects.filter(....).values_list('id', flat=True)) which returns list of UUIDS - [UUID('ef8905a7-cdd3-40b8-9af8-46cae395a527'), UUID('0904bcc4-7859-4c38-a2f9-94a4a2b93f0a')] Then I json.dumps it so I get - "[UUID('ef8905a7-cdd3-40b8-9af8-46cae395a527'), UUID('0904bcc4-7859-4c38-a2f9-94a4a2b93f0a')]" Later on I want to use those IDs for filtering again. something like - my_items = Item.objects.filter(id__in=my_items_ids) Since it's a string I'm trying json.loads(my_items_ids) first and I get json.decoder.JSONDecodeError: Expecting value: line 1 column 2 (char 1) I also tried to turn the UUIDs in the list to strings before the json.dumps() but I got the same results.