Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pre-fill a Django ChoiceField inside a formset
I have a formset with a Runner field that should have some value from a Runner model. I use select2 widget to fill this value: when user types something, I use Ajax to query appropriate rows from the database. I want now to keep the values that this field stores when I submit my formset in case that there is some error and I have to show this form again. If I define this field as ChoiceField with choices=[], open the form and select some runner (e.g. with id=123), then after I send a POST request and try to initialize my formset with FormsetResult(data=request.POST), I get an error that the value provided is not presented in the choices list which is true. I tried to add this value to choices in the form constructor: def __init__(self, *args, **kwargs): runner_id = None if self.fields['runner'].initial: runner_id = kwargs['initial'].get('runner') runner = models.Runner.objects.filter(pk=runner_id).first() if runner: self.fields['runner'].choices = [('', ''), (runner_id, runner.get_name())] , but this still doesn't work after I submit the form: initial values are now empty, and in case of formsets, POST dictionary has ugly field names like form-0-runner which makes it hard to extract the value that I need. Another option is … -
Django use the same variable in different functions
What I am trying to do is, fetching data from a third party app and show it on the page. I will get the data in get_context_data function and use the same data in get_initial method as well. I could not manage to do that. Is there any way to do that? Example Code class UpdateView(generic.FormView): template_name = 'test.html' form_class = myForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) MYVARIABLE = fetch_data_from_3rd_party_app() context["MYVARIABLE"] = MYVARIABLE return context def get_initial(self): initial = super().get_initial() # I want to assign MYVARIABLE.data to initial["data"] here. initial["data"] = MYVARIABLE return initial -
displaying a date in django template using javascript
I'm not sure why the date won't display in this django template, using javascript and html: I've also found this helpful: how to display a javascript var in html body But following that, still can't get it to work. Currently I have: {% extends 'chattr.html' %} <section class=""> hello </section> <script> let d = new Date(); document.getElementById("date0").innerHTML = d; n = new Date(); y = n.getFullYear(); m = n.getMonth() + 1; d = n.getDate(); document.getElementById("date").innerHTML = m + "/" + d + "/" + y; </script> <p id="date"></p> {% block chatStream %} <b>smallest_steps:</b> <br> Hello! Please send me a message:) <span id="date0"></span> <br> <p id="date"></p> {% endblock %} and chattr.html <h1>ss</h1> {% block title %}{% endblock %} {% block chatStream %} {% endblock %} Thanks so much -
Django - sort json data from largest to smallest
i'm fetching the data from elasticsearch to html, but I want to sort the data in html from largest to smallest according to the amount, how can I do it? ex. of how i display error counts ( hiding div if is == 0) ; {% if test== 0 %} <div style="display: none;"><b>Test Service:</b> {{test}}</div> {%else%} <b>Test Service:</b> {{test}} <br> {%endif%} view; def dashcontrol(request): url = "http://XX/_search" headers = {'Content-type': 'application/json'} params = { TEST PARAM } print('OK') response = requests.get(url=url, json=params, headers=headers) data = response.json() test= data['hits']['total'] print(data['hits']['total']) print('BAŞARILI') return render(request, 'dashcontrol.html', {'test':test) -
How to send bloburls to FileForm in django
I have the following bloburl blob:http://127.0.0.1:8000/99bbb97e-79ee-4ac5-b553-796e1f5e897e How do I pass this to the Filefield in Django so that I can save this file ? My models.py looks something like this class UploadFile(models.Model): fileId = models.AutoField(primary_key=True) file = models.FileField(upload_to = file_upload_path) fileDescription = models.TextField() -
Best naming conventions for having multiple form fields, of same subject
Hey all simple question here, I have a Django form field like so player = forms.CharField(required=False, widget=forms.Textarea( attrs={ 'class': 'form-control'), max_length=200, help_text='Please enter a player name.') This charfield form takes a players name from the input, parses the DB, pulls stats of that player. Now, I want to add another player so on the front end, both player's stats can be compared like so player_2 = forms.CharField(required=False, widget=forms.Textarea( attrs={ 'class': 'form-control'), max_length=200, help_text='Please enter a player name.') If I want to do something like this, what's the proper naming convention I should make player_2? I learned it's not best practice to just add _2 to a variable name. Thoughts? -
Django display a video from model
I have a model that contains a video files uploaded to my media/videos folder. When i am on the admin page i can see the video and play it. I am now trying to render it on a template but it doesn't let me. Here is my model: class CheckList(models.Model): choices = (('', 'Select'), ('Good', 'Good'), ('Not Good', 'Not Good')) fuel_choices = (('', 'Select'), ('Full', 'Full'), ('3 Quarters', '3 Quarters'), ('Half Tank', 'Half Tank'), ('Almost Empty', 'Almost Empty')) cargo_choices = (('', 'Select'), ('Cargo Secured', 'Cargo Secured'), ('Cargo Not Secured', 'Cargo Not Secured'), ('No Cargo', 'No Cargo')) vehicle = models.ForeignKey(Trucks, on_delete=models.CASCADE, blank=True, null=True) driver = models.ForeignKey(User, on_delete=models.CASCADE) breaks = models.CharField(null=False, choices=choices, max_length=50, default='Select') wipers = models.CharField(null=False, choices=choices, max_length=50, default='Select') wiper_fluid = models.CharField(null=False, choices=choices, max_length=50, default='Select') cargo = models.CharField(null=False, choices=cargo_choices, max_length=50, default='Select') cargo_straps = models.CharField(null=False, choices=choices, max_length=50, default='Select') tires = models.CharField(null=False, choices=choices, max_length=50, default='Select') oil = models.CharField(null=False, choices=choices, max_length=50, default='Select') miles = models.IntegerField(null=False, default='0') gas = models.CharField(null=False, choices=fuel_choices, max_length=100, default='Select') seatbelt = models.CharField(null=False, choices=choices, max_length=100, default='Good') date_created = models.DateTimeField(auto_created=True) # Need video of vehicle video = models.FileField(upload_to='videos/') def __str__(self): return self.vehicle.nickname My View that handles the page render: @login_required() def report_detail(request, pk): checklist = CheckList.objects.get(pk=pk) context = {'checklist': checklist} return render(request, 'driver/report_detail.html', … -
I want make list with django
category1 = '' category1_tmp = ['a','b',c','d'] for n in category1_tmp: category1 &= n + '|' django error : unsupported operand type(s) for &=: 'str' and 'str' what i want : a|b|c|d how can I solve? -
how to add class {% render_field formset.empty_form %}
I would like my form to have their respective classes to give it a better view, at least to standardize the design {% render_field formset.empty_form %} Anyone have any ideas. The question is that I cannot standardize everything to the same class since there is a special class for the check -
How to write queryset to get data from different connected models in Django?
My models structure: PRODUCT_TYPE = ( ('s', 'simple'), ('v', 'varaible') ) class Products(models.Model): name = models.CharField(max_length=250,null=True, blank=True,) slug = models.SlugField(max_length=200, unique=True,null=True) product_type = models.CharField(choices=PRODUCT_TYPE, default='simple', max_length=50) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) is_published =models.BooleanField(default=False) class ProductAttribute(models.Model): product = models.ForeignKey(Products,on_delete=models.CASCADE, related_name='attributes', default=None) attributes = models.ForeignKey(Attributes,on_delete=models.CASCADE, related_name='attributes', default=None) values = models.ForeignKey(AttributeTerms, on_delete=models.CASCADE, related_name='attributes', default=None) class ProductVariant(models.Model): product = models.ForeignKey(Products,on_delete=models.CASCADE) variant = models.ForeignKey(ProductAttribute,on_delete=models.CASCADE, null = True, default=None) stock = models.IntegerField(default=None) stock_threshold = models.IntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) sku = models.CharField(max_length= 250, default=None) sale_price = models.DecimalField(max_digits=10, decimal_places=2) sale_start_date=models.DateField(auto_now_add=False, auto_now=False) sale_end_date=models.DateField(auto_now_add=False, auto_now=False) What I want to achieve: If product_type is varaibale and if product has more than one variations, get the minimum and maximum price and show in range( as shown on attached image0 If product has sale_price, get the lowest sale_price and get the regular price of same variant having lowest sale_price. if product_type is simple, if sale_price is not none show regular price and sale_price else show regular price if product has sale_price and if sale start date is less than today, and if sale end date is greater than or equal to today, get sale_end_date And show in template in the format as shown in image. Any help will be … -
Django referencing column incompatible with referenced column
I have Displays and Ads table. The Ads have a reference to Displays. What could be the issue there if it's a standard model.? def generate_uuid(): return uuid.uuid4().hex class DisplaysDJ(models.Model): id = models.CharField(primary_key=True, max_length=32, default=generate_uuid) from display.models import DisplaysDJ as Displays class AdsDj(models.Model): id = models.CharField(primary_key=True, max_length=32, default=generate_uuid) display = models.ForeignKey(Displays, on_delete=models.CASCADE, blank=False, null=True) _mysql.connection.query(self, query) django.db.utils.OperationalError: (3780, "Referencing column 'display_id' and referenced column 'id' in foreign key constraint 'orders_adsdj_display_id_4024e66a_fk_displays_id' are incompatible.") -
A dynamic site that does not use JavaScript
I started using the python django framework. Can I open a dynamic site without using JavaScript? I find python easy to use and for some reason I don't like JavaScript. -
Pass ForeignKey to page and retrieve data
I have a page that basically displays user-entered data based on a project. The initial page contains just a handful of fields one being the project_name, which I have set as unique project_name = models.CharField(max_length=50, blank=False, unique=True) From this page, I want to open up another page based on the project_name which enables additional details to be added and stored in a different model. Models.py class Project(models.Model): project_name = models.CharField(max_length=50, blank=False, unique=True) project_website = models.URLField(max_length=50, blank=True) project_description = models.TextField(blank=True) ckeditor_classic = models.TextField(blank=True) def __str__(self): return str(self.project_name) class Fundamentals(models.Model): project_name = models.ForeignKey(Project, to_field='project_name', on_delete=models.CASCADE) project_website = models.URLField(max_length=100, blank=True) project_roadmap = models.CharField(max_length=25) def __str__(self): return str(self.project_name) What I am struggling to do is load the second page but displaying the project_name and be able to associate the next set of data to the project I think i need to do this via the views and urls but I can't get it to work. View.py @login_required def AddFundamentals(request,project_id): project = Project.objects.get(pk=project_id) form = AddFundamentalsForm(request.POST or None, instance=project) if form.is_valid(): form.save() return redirect('dahsboard.html') return render(request, 'pages/critical_fundementals.html', {'project': project, "form": form}) The error returned is AddFundamentals() missing 1 required positional argument: 'project_id' but I am passing this in via the URL path('fundanmentals/<project_id>', view=AddFundamentals, name="add_fundamentals"), Do … -
static fills in django
I get this error when I run collectstatic File "C:\django\venv\lib\site-packages\django\contrib\staticfiles\storage.py", line 38, in path raise ImproperlyConfigured("You're using the staticfiles app " django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. enter image description here I learned the code from an educational video Does anyone know the reason ??? Thank you for answering -
What are the best practices for storing duplicated data in Django models such as first name, last name, and full name
I have built a project with a React frontend and a Django Rest Framework (DRF) API for my backend. Things are going well but I am quite curious about best practices for data saved against your models. As an example, I have a user model with first_name and last_name fields. There is a one-to-one relationship between my user and the two user domains (let's say Buyer and Seller as an example). In addition, we have a foreign key relationship for Seller on something like a Product. On my UI, I have tables that display the data and in general, the majority of tables display the user's full name (first_name + last_name). Generally, all table fields I will want to filter by and order by. I decided that I wanted the data returned from the REST API to represent the table data so I am now returning full_name by augmenting the serializer of Buyer and Seller to have full name using a SerializerMethodField like so: full_name = serializers.SerializerMethodField() ... def get_full_name(self, obj) -> str: return obj.user.get_full_name() However, I will also need to do this in all places where I want to show the Buyer/Seller where they are referenced by a Foreign … -
Django TestCase client.logout() is not logging out user correctly
I'm writing some tests for Django. I'm having trouble with the client.logout() method, which doesn't seem to be logging the test client out. Here's my setUp(): def setUp(self): # Set up a user to use with all of the tests and log in the user. User.objects.create_user(username='temporary', password='temporary') self.client.login(username='temporary', password='temporary') # Create second user for later use. User.objects.create_user(username='temporary2', password='temporary2') And here's my test method: def test_user_can_only_access_own_recipes(self): """ A user should only be able to access recipes they have created. """ # temporary1 user already logged in via setUp(). user_1_recipe = self.create_recipe() self.client.logout() # Login second user and create recipe. self.client.login(username='temporary2', password='temporary2') user_2_recipe = self.create_recipe() # Response_owned is a recipe made by user 2, who is still logged in, so the recipe should be viewable. # Response_not_owned is recipe made by user 1 and should not be viewable as they are logged out. response_owned = self.client.get( reverse('recipes:display_recipe', args=(user_2_recipe.id,))) response_not_owned = self.client.get( reverse('recipes:display_recipe', args=(user_1_recipe.id,))) self.assertEqual(response_not_owned.status_code, 403) # Convert to str, otherwise Django compares 'temporary' with just temporary no quotes. self.assertEqual(str(user_1_recipe.user), 'temporary') self.assertEqual(user_2_recipe.user, 'temporary2') self.assertEqual(response_owned.status_code, 200) This fails with the assertion error: self.assertEqual(user_2_recipe.user, 'temporary2') AssertionError: <User: temporary> != 'temporary2' So my test should create a recipe owned by user 1. User 1 should be … -
I need to limit my update and my delete to Purchases with status "EV"
I need to limit my update and my delete to Purchases with status "EV", those with status "AP", can only be read. Here is my models: class Purchases(TimeStampedModel): values = models.DecimalField(decimal_places=2, max_digits=10, default=0) cpf = BRCPFField("CPF") status = models.CharField(max_length=2, choices=[('AP', ('Aprovado')), ('EV', ('Em validação'))]) modified = datetime.today().strftime('%d-%m-%y %H:%M') def save(self, *args, **kwargs): if self.cpf == "15350946056": self.status = "AP" super(Purchases, self).save(*args, **kwargs) else: self.status = "VA" super(Purchases, self).save(*args, **kwargs) @property def clashback(self): api = requests.get("https://mdaqk8ek5j.execute-api.us-east-1.amazonaws.com/v1/cashback?cpf=12312312323") date = json.loads(api.content) valor_carteira = date['body']['credit'] if self.values <= 1000: info_payments = [("porcentual", "10%"), ("valor_clashback", self.values * Decimal('0.1')), ("valor_total", {self.values * Decimal('0.1') + valor_carteira})] return info_payments elif self.values <= 1500: info_payments = [("porcentual", "15%"), ("valor_clashback", self.values * Decimal('0.15')), ("valor_total", {self.values * Decimal('0.15') + valor_carteira})] return info_payments else: info_payments = [("porcentual", "20%"), ("valor_clashback", self.values * Decimal('0.20')), ("valor_total", {self.values * Decimal('0.20') + valor_carteira})] return info_payments def __str__(self): return self.values, self.cpf, self.clashback Here is my viewsets: from rest_framework.permissions import SAFE_METHODS from rest_framework.viewsets import ModelViewSet from orders.api.serializers import PurchasesInfoSerializers, PurchasesSerializers from orders.models import Purchases class PruchasesViewSets(ModelViewSet): queryset = Purchases.objects.all() filter_fileds = ("cpf",) def get_serializer_class(self): if self.request.method in SAFE_METHODS: return PurchasesInfoSerializers return PurchasesSerializers def get_queryset(self): def get_queryset(self): return super().get_queryset().filter(status='AP') I tried to create a filter to show only with status … -
Django template - Calculate the number of months between today and a variable date
I have a variable that is a date and I want to calculate the months' difference between it and today. The first try was to calculate this in the view but I prefer to do this calculation on the UI when it is needed. I have tried declaring and subtracting the values in the sample code here but I ran into syntax errors though in python this works well. This is what I tried in the templates {% with duration=(organisation.date_founded.year - today.year) * 12 + (date_started.month - today.month) %} { duration }} % endwith %} This is the python version of it today = datetime.datetime.today() num_months = (date_started.year - today.year) * 12 + (date_started.month - today.month) -
Django query which calculate most active post by like and dislike, and by each category
I want to calculate most popular post by each category, but i have this error DISTINCT ON fields is not supported by this database backend. after i use PostgreSql, but I also had a error. annotation and distinct together did not work model --> class Category(models.Model): title = models.CharField(max_length=150, verbose_name=_("კატეგორია")) def __str__(self): return self.title class Question(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name=_("მომხმარებელი") ) category = models.ManyToManyField(Category) title = models.CharField(max_length=150, verbose_name=_("სათაური")) body = models.TextField(verbose_name=_("ტექსტი")) image = models.ImageField(blank=True, null=True, verbose_name=_("ფოტო")) link = models.URLField( max_length=400, blank=True, null=True, validators=[RequireHttpOrHttpsUrl()], verbose_name=_("ლინკი"), ) time = models.DateTimeField(auto_now=True) send_notification = models.BooleanField( default=True, verbose_name=_("გავაგზავნოთ შეტყობინება?") ) def __str__(self): return self.title class LikeDislike(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name=_("მომხმარებელი") ) question = models.ForeignKey( Question, on_delete=models.CASCADE, verbose_name=_("კითხვა") ) point = models.BooleanField() time = models.DateTimeField() def __str__(self): return self.question.title view -> class CountLikeByCategory(generics.ListCreateAPIView): serializer_class = CountLikeByCategorySerializer def get_queryset(self): query=Question.objects.values_list( 'category__title','title' ).annotate( l=Count('likedislike',filter=Q(likedislike__point=1)), d=Count('likedislike',filter=Q(likedislike__point=0)), total=F('l')+F('d'), ).order_by('category', '-total').distinct('category') return query -
I'm working on an ecommerce project on mysql and django ,and during add to cart function i can't figure out where the trouble is ...?
i can't figure out where the trouble is ...? THis is the error occured * Environment: Request Method: GET Request URL: http://127.0.0.1:8000/cart/ Django Version: 3.2.7 Python Version: 3.8.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp.apps.MyappConfig', 'crispy_forms'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/akshay/Django/my_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/akshay/Django/my_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/akshay/Django/my_env/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/akshay/Django/Frooty/myapp/views.py", line 61, in add_cart customer = request.user.customer File "/home/akshay/Django/my_env/lib/python3.8/site-packages/django/utils/functional.py", line 247, in inner return func(self._wrapped, *args) File "/home/akshay/Django/my_env/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 421, in __get__ raise self.RelatedObjectDoesNotExist( Exception Type: RelatedObjectDoesNotExist at /cart/ Exception Value: User has no customer. THis is my models.py from django.db import models from django.contrib.auth.models import AbstractUser,User class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self): return self.name THis is my views.py @login_required def add_cart(request): if request.user.is_authenticated : customer = request.user.customer order,created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() else: item = [] context = {'items':items} return render(request,'store/cart.html', context) This is my forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User # Create your … -
Connect django to legacy postgresql database, already exist and have 1 table
am trying to connect postgresql database with a table already created (legacy). Not much documentation on the Internet to do so as the database already created. Am afraid to lose the data. Any guide to do that. Am using Windows and gitbash and have pgadmin4. Still learning. Default database in settings file changed to my database but what's next migrate or inspectdb or create tables in django?! Any help is appreciated. -
What is the equivalent for, SELECT * FROM table_name WHERE id IN (1,2,5,9) in Django
def post(self, request, *args, **kwargs): req = self.request.POST ids = req.get('ids') imported_data =table_import.objects.filter(id=ids) in which ids has values 1,2,5,7 -
Find objects with many-to-many relations Django
I have a model class Book(models.Model): name = models.CharField() class BookShelf(models.Model): books = models.ManyToManyField(Book, on_delete=models.CASCADE) I need to find a bookshelf with both book1 and book2 objects This works, but I don't think it is optimal shelf = BookShelf.objects.filter(books=book1).filter(books=book2) This should work too, but it doesn't: from django.db.models import Q shelf = BookShelf.objects.filter(Q(books=book1) & Q(books=book2)) What did i do wrong? -
I want to show img in my template from database?
i want to show image from model.py file in user app where i uplode my image. this is user.model.py file model.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to = 'profile_pics') def __str__(self): return f'{self.user.username} profile.' def save(self): super().save() img = Image.open(self.image.path) if img.height>300 or img.width > 300: img.thumbnail( (300,300) ) img.save(self.image.path) blog.model.py(blog is another app) . this is blog.model.py file model.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=100,help_text="enter within 100 charecter") content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title # this is for show demo form admin site (if you use this than genarate a button for demo ) def get_absolute_url(self): return reverse('post-detail', kwargs={'pk' : self.pk}) And this is my class base view funcatin in blog app Whose template name is home.html. this is blog.view.py file view.py class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['ip'] = self.request.session.get('ip', 0) return context home.html I show you only image tag. {% for … -
Why is my Django object deleted with no reason?
I know this question may not be in appropriate shape, but I have no other way to describe it. I have a Django project, deployed with Heroku. I'm using Postgres add-on. The problem is, few of the objects that my users created is being deleted for some reason. I tried to see if there's a pattern with this issue, but I haven't found one. It happens randomly. (This usually happens when I share(copy+paste) a user's post to other people, but I'm not sure if it's a pattern.) I know it's not the heroku ephemeral filesystem issue, because I'm using the Postgres add-on. So I started wondering if there could be something wrong with Heroku or the Postgres add-on itself. This is a quite serious issue, but I can't figure out what the problem is. Has anyone experienced similar issue or knows the answer to this? Thank you very much.