Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Do I have to buy dynos too for my staging application on Heroku?
I'm using Heroku as a platform for my Django application, currently on a free dyno. I have created a copy of my application in order to seperate staging and production applications. Now before the application launch, I'm willing to upgrade to Standart2X dyno tier on Heroku for my production app, to use multiple process for background tasks. The things is my app really depends on background tasks (slow and high number of API calls), so I want be able to test multiple process's working in staging enviroment before pushing to production. What I don't understand is, do I have to upgrade my dynos both in staging and production enviroment? Maybe I can use hobby tier dynos in staging (which allows defining multiple process types in Procfile too) as they are cheaper than standart dynos, but this feels wrong as application sources will be different for staging and production. Maybe I'm missing something here or I don't understand these concepts enoughly. I'm kinda new to staging-production concept, so I appreaciate all kind of helpfull links and suggestions. -
How to update database automatically at a given time python
I've written a python script that takes a CSV from Github, makes it data frame with pandas, then do some preprocessing, and finally exports a SQL table for a database that is being used by Django models. Then a new CSV file is uploaded every day, and then I need the new CSV, so I manually run the script again for read CSV data frame and preprocessing delete the previous table create a new table with the same name for the Django model Is there a way to automate this? Is there a better practice than the one I'm doing? Thanks. -
Intermediary model not showing up in admin console?
I'm still relatively new to programming, Django, and creating apps so please bear with me. I'm working on a dietary app and I'm having a hard time visualizing and understanding why my specific use case of a ManyToManyField for one of my models is not showing up in the admin console. I tried reading the Django docs for the ManyToManyField relationship but I am still having troubles understanding it, so hopefully someone can explain this to me like I am a happy golden retriever. I have three models: class Product(models.Model): product_name = models.CharField(verbose_name='Product name', max_length=100) product_description = models.TextField(verbose_name='Product description', max_length=500) product_id = models.UUIDField(default=uuid.uuid4(), unique=True) def __str__(self): return self.product_name #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# class Recipe(models.Model): recipe_name = models.CharField(verbose_name='Recipe name', max_length=100) ingredients = models.ManyToManyField(Product, related_name='Ingredients', through='IngredientQuantity', through_fields=('recipe','ingredient')) class Meta: ordering = ['recipe_name'] def __str__(self): return self.recipe_name #-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------# class IngredientQuantity(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredient = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.DecimalField(verbose_name='Quantity', decimal_places=2, max_digits=99, null=False) What I was trying to do with this was create an Intermediary with IngredientQuantity which will give me the quantity along with a selected Product that I can then associate with Recipe. However I am not seeing the ingredients input for Recipe when I attempt to create a new entry for Recipe … -
Best way to send a mail in Django Model when a user's password has been changed?
I am new to python and django this year and am just struggling to figure out how to send a simple mail via send_mail to a user after their password has been updated? I have managed this via Signals with pre_save, however I don't want to make the user wait until the mail has been sent (which I can't work around as far as I know). With post_save, the previous state cannot be queried. What would be the best way here if I gave the following user model? class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(verbose_name="email address", max_length=255, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] # Tells Django that the UserManager class defined above should manage # objects of this type objects = UserManager() def __str__(self): return self.email class Meta: db_table = "login" I had set this up with a pre_save signal, but this is not a solution for me because of the delay: @receiver(pre_save, sender=User) def on_change(sender, instance: User, **kwargs): if instance.id is None: pass else: previous = User.objects.get(id=instance.id) if previous.password != instance.password: send_mail( "Your password has changed", "......", "info@examplpe.com", [previous.email], fail_silently=False, ) Thanks in advance -
I want to change name of submenu and header in django admin
Django automatically picks the name of the model and adds s for plural, i would like to fix the code below, class PolicyAdmin(admin.ModelAdmin): class Meta: verbose_name = 'Policy' verbose_name_plural = 'Policies' list_display = ( 'policy_type', 'plate_number', 'user', 'policy_amount', 'last_renewal_date', 'next_renewal_date', 'policy_expiry', 'surrender_value', 'active', 'created_at', 'updated_at' ) name = 'Policies' ordering = ('policy_expiry', 'policy_expiry') -
I'm getting a NoReverseMatch error when I go into the DetailView
Everytime I create a post in my website I always get a NoReverseMatch error when it redirects to the detail view of the app. I can't find the answer in the internet. I need urgent help with this problem. Thank you in advance! Views.py: from django.shortcuts import render from django.views import generic from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from . import forms from . import models # Create your views here. class AnnouncementListView(generic.ListView,LoginRequiredMixin): model = models.Announcement class AnnouncementDetailView(generic.DetailView, LoginRequiredMixin): model = models.Announcement class AnnouncementUpdateView(generic.UpdateView, LoginRequiredMixin): model = models.Announcement form_class = forms.AnnouncementForm class AnnouncementCreateView(generic.CreateView, LoginRequiredMixin): model = models.Announcement form_class = forms.AnnouncementForm class AnnouncementDeleteView(generic.DeleteView, LoginRequiredMixin): model = models.Announcement success_url = reverse_lazy('announcement:single') def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user_id=self.request.user.id) def delete(self, *args, **kwargs): messages.success(self.request, "Post Deleted") return super().delete(*args, **kwargs) Urls.py: from django.urls import path from . import views app_name = 'announcement' urlpatterns = [ path('create/', views.AnnouncementCreateView.as_view(), name='create'), path('', views.AnnouncementListView.as_view(), name='list'), path('posts/<int:pk>/', views.AnnouncementDetailView.as_view(), name='single'), path('delete/<int:pk>/', views.AnnouncementDeleteView.as_view(), name='destroy'), ] announcement_detail.html: {% extends 'base.html' %} {% block content %} <div class="container"> <h1>{{announcement.title}}</h1> <p>{{announcement.text}}</p> <span>{{announcement.date}}</span> <a href="{% url 'announcement:destroy' %} "><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-eraser-fill" viewBox="0 0 16 16"> <path d="M8.086 2.207a2 2 0 0 1 2.828 0l3.879 3.879a2 2 0 0 1 … -
No module named 'django.core.context_processors' django template
i tried to make a template tag to get the logged in user request.user , i tried this in the settings.py 'context_processors': [ 'django.core.context_processors.request', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], and this is my template tag from django import template register = template.Library() @register.simple_tag def is_member(context): request = context['request'].user if request.user in request.user.model_name.admins.all: return True else: return False i have to make sure if the logged in user is one of members in admins (M2M) field but i get this error No module named 'django.core.context_processors' and while i try to remove this line 'django.core.context_processors.request' in the settings.py file i get this error 'is_member' did not receive value(s) for the argument(s): 'context' any recommendation i will appreciate thanks , art -
DJANGO - i execute_from_command_line(sys.argv)
Good afternoon, night or day, people! I'm trying to run this free project: https://github.com/mateoBa/trend These were my steps: clone; virtualenv env cd env / Scripts activate CD.. pip install -r requirements.txt bower install bower.json and finally: python manage.py migrate And, in the end, gave this error: (env) PS C: \ Users \ account \ Desktop \ PARANHOS \ trend> python manage.py migrate Traceback (most recent call last): File "C: \ Users \ account \ Desktop \ PARANHOS \ trend \ manage.py", line 22, in <module> execute_from_command_line (sys.argv) File "C: \ Users \ account \ Desktop \ PARANHOS \ trend \ env \ lib \ site-packages \ django \ core \ management \ __ init__.py", line 363, in execute_from_command_line utility.execute () File "C: \ Users \ account \ Desktop \ PARANHOS \ trend \ env \ lib \ site-packages \ django \ core \ management \ __ init__.py", line 337, in execute django.setup () File "C: \ Users \ account \ Desktop \ PARANHOS \ trend \ env \ lib \ site-packages \ django \ __ init__.py", line 27, in setup apps.populate (settings.INSTALLED_APPS) File "C: \ Users \ account \ Desktop \ PARANHOS \ trend \ env \ lib \ site-packages … -
How to make strings from my database show up in my localisation .po file in Django?
in one of my python projects, I'm looping through a list of countries which is stored in my SQLite database: {% if europe %} {% for country in europe %} <figcaption>{{ country.Name_fr }}</figcaption> {% endfor %} {% endif %} I am using localization so I have a locale folder with .po files with which I handle the different translations. However I would like to have the database strings (from {{ country.name_fr }}) show up in these .po files. This means I would have to include a translate tag but if I try it, it shows an error. This: <figcaption>{% translate {{ country.Name_fr }} %}</figcaption> leads to this: TemplateSyntaxError at / Could not parse the remainder: '{{' from '{{' Any help would be appreciated -
Set or change the DEFAULT_LANGUAGE in Django
I want the default language of my site to be Persian, not English! and DEFAULT_LANGUAGE is not working for me ! A part of my settings.py file : LANGUAGES = ( ('fa','Persian'), ('en','English'), ) DEFAULT_LANGUAGE = 1 LANGUAGE_CODE = 'fa' TIME_ZONE = 'Asia/Tehran' USE_I18N = True USE_L10N = True USE_TZ = True I also read these and they did not help: Set or change the default language dynamically according to the user - Django Django how to set the default language in the i18n_patterns? Django: Can't change default language Django: default language i18n Please help me. thanks! -
Django: How to make non-serializable object available within a session
My danjgo/python project consists of db-backed models and non-db-backed models. The non-db-backed models get data from the db-backed models and do some heavy computational stuff and they have a state. At the moment for every request the non-db-backed models get newly instantiated and I have to re-calculate everything. This makes everything very slow... How can I save the non-db-backed models to a django session or something similar? Its not feasable to serialize these objects (and it would also be very time consuming to serialize them or deserialize them). Therefore I cannot use the request.session dictionary. It also makes no sense to make these models db-backed, because their state depends on other API-Calls, current date, time and user input. I do not want them to be saved "forever". I want to use them just in the session to save computing time. I use the django.contrib.auth.models. Best would be, that I could add somehow these "expensive" models to my current user. I had a look into the django cache. But the cache is "static". If I set an object into the cache at the beginning of the function and change it afterwards, these changes are not reflected in the cache. Maybe I … -
bulk_upsert update based on existing value
I need to bulk_upsert some data set. But one field should be calculated based on the existing value that is already present. For simplicity, I have used the field IN_updated_at to update with the same value that already exists in the DB. i.e F('IN_updated_at') from django.db.models import F for i in some_list: sync_list.append( { 'id':'some_id', 'last_synced_time': Now(), 'IN_updated_at': F('IN_updated_at') } ) MyModel.objects.bulk_update([MyModel(**kv) for kv in sync_list], ['last_synced_time', 'IN_updated_at']) But I get the following error: TypeError: expected string or bytes-like object I also did the same with a JSON field and I get the following error: TypeError: Object of type 'F' is not JSON serializable How can I get this work? -
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. Django 3.1.4
I'm trying to learn about Django and REST framework and starting customize my model but went I use makemigration it show this error can someone lease help me out. This is my models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.forms import ModelForm, forms, TextInput class AccountManager(BaseUserManager, PermissionsMixin): def create_user(self, username, email, password = None): if username is None: raise TypeError('Username cannot be empty') if email is None: raise TypeError('Email cannot be empty') user = self.model(username = username,email = self.normalize_email(email)) user.set_password(password) user.save() return user def create_super_user(self, username, email, password = None): if password is None: raise TypeError('Password cannot be empty') user = self.create_user(username,email,password) user.is_super_user = True user.is_admin = True user.save() return user class Account(AbstractBaseUser): username = models.CharField('settings.AUTH_USER_MODEL', max_length=300, unique=True) email = models.EmailField(max_length=300, unique=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False)# only for superuser created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = AccountManager() def __str__(self): return self.email And this this the error raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. Thanks! -
Showing errors with LoginView in Django
I have a problem with displaying errors on the template for login page. I am using the Login built in view and I made a custom form which inherits from AuthenticationForm and I tried to override the clean() method but if the username or password is not correct is not displaying any ValidationErorr message. Any help? I created a custom view because I need to inherit from a custom mixin for some restrictions. my view: class UserLoginView(IsAuthenticatedMixin, LoginView): template_name = 'home/auth/login.html' authentication_form = UserLoginForm my form: class UserLoginForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput()) password = forms.CharField(widget=forms.PasswordInput()) def clean(self): cleaned_data = super().clean() username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username is not None and password: login = authenticate(self.request, username=username, password=password) if login is None: raise ValidationError('The username or password are incorrect') return self.cleaned_data url: path('auth/login/', UserLoginView.as_view(), name='login'), my template: {% extends 'home/auth/base.html' %} {% load widget_tweaks %} {% block content %} <!-- Outer Row --> <div class="row justify-content-center"> <div class="col-xl-10 col-lg-12 col-md-9"> <div class="card o-hidden border-0 shadow-lg my-5"> <div class="card-body p-0"> <div class="row"> <div class="col-lg-6 d-none d-lg-block bg-login-image"></div> <div class="col-lg-6"> <div class="p-5"> <div class="text-center"> <h1 class="h4 text-gray-900 mb-4">Welcome Back!</h1> </div> <form class="user" method="POST"> {% csrf_token %} <div class="form-group"> {% for error in form.non_field.errors … -
Trying to pass a foreign key of my model into URL for dynamic routing
I have 3 models, a custom user model (using AbstractUser - User/Brand models) and a Message model: class User(AbstractUser): is_brand = models.BooleanField(default=False) is_influencer = models.BooleanField(default=False) class Brand(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name="brand_info") email = models.EmailField() brand_name = models.CharField(max_length=100, blank=True) class Message(models.Model): recipient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='recipient') sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') message_content = models.TextField() send_time = models.DateTimeField(auto_now_add=True) I have a view where I want to load up all the messages associated with a particular Brand, and this page will also have the attribute (from Brand model) as a dynamic URL parameter. Here's my current code for views.py: def conversation_view(request, username): messages = Message.objects.filter(Q(message__sender=username) | Q(message__recipient=username)).order_by('send_time') return render(request, "conversation.html", { 'messages': messages }) And here's my urls.py: urlpatterns = [ path('conversation/<username>/', views.conversation_view, name='conversation_view') ] When I try and load up a page with the appropriate conversation/ URL, I get the following error message: invalid literal for int() with base 10: 'username' I'm not sure why Django is expecting an int() here? Is it because I'm using sender/recipient from Message model in my view, which are both foreign keys? -
How to save a foreignkey field while saving a HTML form in Django?
I want to save a html form data into django model but it has a foreign key field from another model. How can I save a form which has FK field?? My models: class Dish(models.Model): title =models.CharField(max_length=200) description =models.TextField(blank=True) price =models.IntegerField() photo_main= models.ImageField(upload_to="photos/%Y%m%d/") photo_1= models.ImageField(upload_to="photos/%Y%m%d/", blank= True) photo_2= models.ImageField(upload_to="photos/%Y%m%d/", blank= True) def __str__(self): return self.title class Order(models.Model): dishorder= models.ForeignKey(Dish,null=True,on_delete=models.CASCADE) name = models.CharField(max_length=200,blank=True) email = models.CharField(max_length=100,blank=True) phone = models.CharField(max_length=100,blank=True) quantity =models.IntegerField(blank=True) def __str__(self): return self.name My views: def order(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] quantity = request.POST['quantity'] order= Order( name=name, email=email, phone=phone, quantity=quantity) order.save() messages.success(request, "Your order has been submitted.") return render(request,"dishes/order.html") My urls: urlpatterns = [ path("dish",views.dish,name="dish"), path("dish/<pk>",views.dishsingle,name="dishsingle"), path("order",views.order,name="order"), ] My template dishes/order.html <form method="POST"> {% csrf_token %} <div> <label for="name">Name:</label> <input type="text" name="name" class="form-control" required> </div> <div> <label for="email">Email:</label> <input type="email" name="email" class="form-control" required> </div> <div> <label for="phone">Phone:</label> <input type="number" name="phone" class="form-control" required> </div> <div> <label for="quantity">Quantity:</label> <input type="number" name="quantity" class="form-control" required> </div> <hr> <input type="submit" value="MAKE AN ORDER"> </form> While submitting this html form, I would like the foreignkey field dishorder to be saved on the backend as well. When I check the admin page, order is saved but without … -
adding dropdown list for django
I am learning Django right now and I try to add a dropdown list to the website. The website right now will show a list of games. The dropdown list has different platforms and I want the list change after the user selects one platform. What should I do? At form.py: class platformSelectForm(forms.Form): platformsList = ( ('all', 'Please Select'), ('NS', 'Nintendo Switch'), ('PS4', 'PlayStation4'), ('PS5', 'PlayStation5'), ('XBO', 'Xbox One'), ('XS', 'Xbox Series S/X'), ); platforms_Select = forms.ChoiceField(widget = forms.Select, choices = platformsList, required = False); At view.py: class showGameLists(TemplateView): template_name = "showList/home.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs); platformSelect = platformSelectForm(self.request.POST or None); context['platformSelect'] = platformSelect; games = getGames(nowDay.year, nowDay.month, platforms); context['games'] = games; context['year'] = nowDay.year; context['month'] = calendar.month_name[nowDay.month]; context['prevMonth'] = prevMonth(nowDay); context['nextMonth'] = nextMonth(nowDay); return context At urls.py: from django.urls import path; from .views import showGameLists; urlpatterns = [ path('', showGameLists.as_view(), name='home') ] At home.html: <form method = 'POST' action = '/'> {% csrf_token %} {{ platformSelect.as_p }} <input type='submit' value='Submit' /> </form> {% for game in games %} <div> <span><h2>{{game.0}}</h2> <p>Release Date: {{ game.1 }}, Metacritic: {{ game.3 }}</p> <p>Platform: {% for platform in game.2 %}{{ platform }}/{% endfor %}</p> {% if game.4 %} <img src={{game.4}} width="367" … -
Django Rest Framework - ManyToMany List of IDs disappearing
I have recently upgraded my Django to 3.1.5 and my DRF to 3.12.2, and something in my application has stopped working. I have the following structure in my models and serializers (simplified): Models: class A(models.Model): name = models.CharField(max_length=50) class B(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) class C(models.Model): b = models.ForeignKey(B, on_delete=models.CASCADE) class D(models.Model): c = models.ForeignKey(C, on_delete=models.CASCADE) name = models.CharField(max_length=50) items = models.ManyToManyField(Item,blank=True) class Item(models.Model): name = models.CharField(max_length=50) Serializers: class DSerializer(serializers.ModelSerializer): class Meta: model = models.D fields = ('name','items') class CSerializer(serializers.ModelSerializer): d_set = DSerializer(many=True, read_only=False) class Meta: model = models.C fields = ('d_set',) class BSerializer(serializers.ModelSerializer): c_set = CSerializer(many=True, read_only=False) class Meta: model = models.B fields = ('c_set',) class ASerializer(serializers.ModelSerializer): b_set = BSerializer(many=True, read_only=False) class Meta: model = models.A fields = ('name','b_set') def createD(d_set, c): for d in d_set: items = d.pop('items') newD = models.D(c=c,**d) newD.save() for item in items: newD.add(item) def createB(self, b_set, a): for b in b_set: newB = models.B(a = a) newB.save() c_set = b.get("c_set") for c in c_set: d_set = c.pop("d_set") newC = models.C(b = b, **c) newC.save() self.createD(d_set, c) def create(self, validated_data): b_set = validated_data.pop('b_set') newA = models.A(**validated_data) newA.save(); self.createB(b_set,newA) The issue is that d.items in createD() is empty, even when data is passed in the serializer. … -
Make it so the information the user provided in input field can be modified and redisplayed with Django
I am currently trying to make a password manager with Django. The code for it can be found here, and the version of the code I'm referencing is when commit id "39dd9110a8aa098399af0511a963e447a0d45afb" was pushed to GitHub. All code referenced will be in the django app titled "main". The home page looks like this: 2 This is what the page in question looks like: 3 (In the project, this page is displayed after clicking the text "GitHub") In the input area, the user provides their master password, and then clicks the submit button. I would like to retrieve that password and alter it(I will use it to decrypt their other passwords, but I do not need help decrypting, I need help altering it). And after altering it, I would like to display the altered text on the page. In the file named "detailed_view.html", the code containing the input field is wrapped in form tags. Code: <form method = "POST"> {% csrf_token %} <h1 style="display:inline; color: #4CAF50">Password</h1> <input type="password" name="Password" style="display:inline;"> <input style="position: absolute;left: 50%;display:block;" type="submit" value="Submit"> </form> After the user clicks "submit", the information is brought to the view() function in views.py (line 64): @login_required def view(request, pk): if request.method =="POST": … -
How can I update a many to many field in Django
I am trying to update a many to many field button when a user clicks a button The Payment model is to allow users to submit their receipts to be reimbursed. Each Payment has a "many to many" field named status. Currently, there are only two statuses a payment can have "complete" or "incomplete". When a user submits a payment the default is incomplete, and when the company issues a check to reimburse the user, the company needs to be able to click a button that will update the payment to 'complete'. To get a better idea of what this looks like, the HTML page looks like this. The Page My models.py from django.db import models from django.contrib.auth.models import User import uuid from django.urls import reverse # Create your models here. class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return f'{self.name}' class Status(models.Model): type = models.CharField(max_length=100) def __str__(self): return f'{self.type}' class Payment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) amount = models.DecimalField(max_digits=14, decimal_places=2) receipt_img = models.FileField(default='default.jpg', upload_to='receipt_pics') author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) type = models.ManyToManyField(Category) time_posted = models.DateTimeField(auto_now_add=True) description = models.TextField(null=True) status = models.ManyToManyField(Status) def __str__(self): return f'{self.id} Contribution' def get_absolute_url(self): return reverse('contrib-home') The button that sends the request in payment_detail.html <a href="{% … -
Using DRF serializer to add custom details to multiple models
Suppose I have three models model A : class A(models.Model): field1 = models.CharField(max_length=100) field2 = models.CharField(max_length=255) class B(models.Model): field1 = models.ForeignKey(A, on_delete=models.CASCADE) field2 = models.FloatField() class C(models.Model): field1 = models.CharField(max_length=200) field2 = models.BooleanField(default=False) Now I want to update C based on values that I input in models A and B. Currently, I am writing pretty lengthy views and violating DRY principle by using the same logic over and again for any new view I write Currently, the serializer that I am using are simple model serializers. So basically, I have thick views and thin views. -
Copy value of html element in django (forms) template
django form with ChoiceField (1,2,3)--> {{Choices.sollicitanten}} django form with ChoiceField (1,2,3) -->{{ form.vacature_contract }} the choice options of both fields are the same 1,2,3 What i want is when i select for example, choice 1 in choices.sollicitanten it wil copy this choice to field {{form.vacature_contract}} so that the choice is this field is also 1. <td class="tg-0lax">{{ Choices.sollicitanten}}</td>. //and i have <td name="vacature_doel" class="tg-0lax">{{ form.vacature_contract }}</td> //and in html function FillForm(f) { { f.vacature_doel.value = f.vacature_bron.value; f.sollicitanten_doel.value = f.sollicitanten_bron.value; } } </script> //when i hit the submit button the function is run (onclick=FillForm). //the code above does not seem to do much..what is going wrong. -
Django dumpdata in .json collides in UTF-8 problem
I archived migrations in .json file. (venv) D:\scraping_service>python manage.py dumpdata scraping > scraping.json PyCharm informs that "File was loaded in the wrong encoding: 'UTF-8'" And Cyrillic symbols are not displaying. How to deal with this, if, in theory, UTF-8 is the right encoding for Cyrillic symbols? -
merge two id data in python
I want to merge two different id conversation data. I tried something like this below but didn't got helpful, If anybody could help me for what i exact want to achieve would be much appreciated. thank you so much in advance. output result: "data": [ { "id": 13, "conversation": [ { "id": 31, "from_user": "shopowner", "to_user": "carowner", "message": "hello", } ], }, { "id": 14, "conversation": [ { "id": 32, "from_user": "carowner", "to_user": "shopowner", "message": "hey", } ], } ] expected result: "data": [ { "conversation": [ { "id": 31, "from_user": "shopowner", "to_user": "carowner", "message": "hello", }, { "id": 32, "from_user": "carowner", "to_user": "shopowner", "message": "hey", } ], }, ] what i tried is: for record in data: data1 = str(record['conversation']) data2 = str(record['id']) from itertools import chain all_results = list(chain(data1,data2)) sort_data = all_results.sort(key=lambda x: x["created_on"], reverse=True) main_data = [x for x in record['conversation']] print(main_data) If anybody could help me for what i exact want to achieve would be much appreciated. thank you so much in advance. -
Call a particular function of Class based view Django from urls.py
I have this views.py where I've implemented Class based views, but let's say I want to call a function get_featured_products when the url is https://localhost:8000/featured_products. What sould my urls.py look like to call the get_features_products function? from django.shortcuts import render from rest_framework import views from rest_framework.response import Response from .models import * from .serializers import * # Create your views here. class ProductView(views.APIView): model= Product serializer = ProductSerializer def get(self,request): qs = self.model.objects.all() serializer = self.serializer(qs, many=True) return Response(serializer.data) def post(self,request): serializer = self.serializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.error_messages()) def put(self,request,pk): product = Product.objects.get(id=pk) serializer = self.serializer(instance=product, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.error_messages) def get_featured_products(self,request): #some code here return None How should I refer to get_featured_products in my urls.py