Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get a value in querytset on basis of foregin key value django
I have a queryset in which I am getting all products like this products=Products.objects.all() and other table of wishlist class Wishlist(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) isFavourite=models.BooleanField(default=True) customer = models.ForeignKey(Customer ,on_delete=models.CASCADE , null=True) Now I have want to get value of wishlist in every product in form of True or False. like In product 1 customer 1 have True or False value of that product or not. -
Conditional within def __str__(self) in Django
I have this model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile', null=True, blank=True) name = models.CharField(max_length=120, null=True, blank=True) As you can see, both user and name are nullable. This is because a profile might be linked to a user or not. If it is not, then only the name field is provided. How can I return name if the profile is not linked to user, and the user.name properties if it is? This: def __str__(self): return if self.user: f"{self.user}'s profile" else: self.name returns a __str__ returned non-string (type NoneType) error. -
Django - "Model already exists" error while submiting form
I'm working on a question management system for my online quiz, especially, making the question modification page. When I submit the form, Django considers it's not valid because the object already exists, won't save my modifications and just render a new form. Here is my question model : class Question(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) num_question = models.IntegerField(default=0) question = models.TextField(max_length=1000, unique=True) reponse = models.IntegerField(default=0) class Meta: verbose_name = 'Question' verbose_name_plural = 'Questions' def __str__(self): return f'Question n°{self.num_question}' My creation form (that I also use to modify questions): class Creation_Question(forms.ModelForm): num_question = forms.IntegerField(label='Numéro de la question') class Meta: model = Question_Num fields = ['num_question', 'question', 'reponse'] I want to pre-fill the fields with the actual question data so I instanciated the form. My views.py: def question(request, id): if not request.user.is_superuser: return redirect('/accueil') else: if Question_Num.objects.filter(id=id).first(): q = Question_Num.objects.get(id=id) form = Creation_Question(instance=q) context = {'form': form, 'question': q} if request.method == 'POST': if form.is_valid(): form.save() return redirect('/questions') return render(request, 'questions/question.html', context) And my HTML file: {% extends "home/index.html" %} {% block title %}Questions{% endblock %} {% block content %} <div class="accueil"> <h1>Gestion des questions</h1> <hr> <form method="POST"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ … -
Is there a way to reuse a queryset wih a ModelFormSet foreign key field in Django?
I currently have a formset set up where a user can go in and select a product to substitute an order line item with. However, when an order has a larger amount of lines, it takes a long time to query all of the products for each ModelChoiceField in the Form. Is there any way I can query all the products once, and then just pass that into the ModelChoiceField for all of the forms in a formset? Here is my Model: class OrderLineItem(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='details') product = models.ForeignKey(Product, on_delete=models.CASCADE) price_before_discounts = models.DecimalField(default=D(0.00), max_digits=7, decimal_places=2) discount = models.DecimalField(default=D(0.00), max_digits=7, decimal_places=2) has_applied_discount = models.BooleanField(default=False) total = models.DecimalField(default=D(0.00), max_digits=7, decimal_places=2) line_number = models.IntegerField(default=1) added_by_promotion = models.ForeignKey('Promotions.CouponRedemption', on_delete=models.CASCADE, blank=True, null=True, default=None) substitute = models.ForeignKey(Product, related_name='substitute', on_delete=models.CASCADE, blank=True, null=True, default=None) Here is the Form: class OrderDetailSubstitutionForm(ModelForm): def __init__(self, *args, **kwargs): super(OrderDetailSubstitutionForm, self).__init__(*args, **kwargs) self.fields['substitute'].widget.attrs.update({'class':'form-control text-center','style':'width:100%'}) self.fields['substitute'].label = "" class Meta: model = OrderLineItem fields = ('substitute',) Everything works as intended, however it is querying all products every time it renders a substitute field, which might be 100 times for an order. -
Django searching listview with multiple queries and pagination
I have this problem https://www.reddit.com/r/django/comments/52vmyg/pagination_with_search/ but instead of 1 search term being passed to my pagination links I need to list multiple. for example <a class="page-link" href="?status={{ request.GET.status }}&page={{ page_obj.next_page_number }}">Next</a> works fine but I need to put in multiple objects and scared the template code will become unreadable, is there any way I can access request.GET items with a generic for loop? or perhaps a better way to code the pagination -
Modifying the model with class method when creating the instance in Django?
I have a model which represents bought adverts: class Bought(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) advert = models.ForeignKey(Advert, on_delete=models.CASCADE) amount = models.IntegerField() The adverts may expire or the quantity has been sold out and in this moment the Advert instance is being deleted (signals) and the mirror-reflection instance of AdvertArchives is being created. In this moment the Bought instance of Advert is being deleted because of models.CASCADE. Before it happens, using the same signal, I want to recreate the Bought instance but to do it I need to change the advert attribute's ForeignKey to AdvertArchive. Is there any way to accomplish this via simple @classmethod ? -
Develop a graphical interface for Python applications
I am developing a python application. This application generates as a final result a table of type .xlsx To reach the final table I used Anaconda's jupyter. I would like to create a graphical interface for the python application. However, I have some theoretical doubts on the subject: Since, I would like to enter the table and show the statistical results to the user (according to filters applied by the users). What would be the most appropriate approach? Option A) Use an interpreter, such as TkInter? Are these interpreters capable of generating an executable? Is it able to receive a data entry table? Option B) Use a web framework, such as Django. Does this framwork host the built page? It is capable of receiving a data entry table. I am open to more options. Thank you. -
Best way to organize models for django Recipe app with ingredients, recipes, and components
Would love some feedback here on how to structure a new app (learning project) that helps chefs build recipes. A recipe is a specific amount of ingredients (ex: 1c sugar) and/or components (a small collection of ingredients. ex: simple syrup, which is a recipe of 1c sugar + 1c water). For my models, here's what I'm thinking: class Ingredient(models.Model): name = models.CharField(max_length=150) ... class Recipe(models.Model): FULL = 1 COMPONENT = 2 TYPE_CHOICES = ( (FULL, 'Full Recipe'), (COMPONENT, 'Component'), ) name = models.CharField(max_length=150) type = models.IntegerField(choices=TYPE_CHOICES, default=FULL) ... class RecipeIngredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) amount = models.FloatField() ... My issue is I'm not sure how to account for the component (a subset of ingredients used in multiple recipes). I've made it a Recipe.type since that's really what it is, but not sure how to account for that in my RecipeIngredient model. I could add component = models.ForeignKey(Recipe) to my RecipeIngredient model and use either that OR ingredient. But just guessing. Anyone have a suggestion of a better way to do this? -
Pagination with AJAX in Django
I have an account page where objects saved in a database by the user are displayed as a list. I use Pagination to navigate through the different objects. Everything is working as it should. But now I would like to use AJAX on top of it. I already use it to save and delete objects from the list but this case is a lot trickier.... or not. My list is loaded to a page which url contains the user_id to filter the objects. What I would like to do, but maybe it's not the best solution, it's to bound the button I have in the nav bar to acces the account and the button at the bottom of the page that switches pagination. My AJAX: $(".next-button").on('click', function(event) { event.preventDefault(); var page_n = $(this).attr('href'); url = '/register/pagination' console.log(page_n); $.ajax({ type: "POST", url: url, data : { 'page_n' : page_n, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() }, success: function (data) { console.log(data); }, error: function () {} }); }); My views.py: def account(request, user_id): if request.method=='POST': data['success'] = True return JsonResponse(data) else: sub_list = SavedProduct.objects.filter(username = user_id) paginator = Paginator(sub_list, 5) page_number = request.GET.get('page') saved_list = paginator.get_page(page_number) context = { 'saved_list': saved_list, } return render(request, 'account/account.html', … -
Allow users to delete their own comments via the front end
I have been trying to follow this tutorial - How to provide a delete button for django built in comments framework. Unfortunately it is an old tutorial and some of the code is now out of date. In it he uses the code from django.contrib.comments.view.moderate import perform_delete. I then got an error message ModuleNotFoundError: No module named 'django.contrib.comments'. I did pip install django-contrib-comments. And I tried the following - from django_comments.view.moderate import perform_delete. Does anyone have any other suggestions? -
How can I pass an argument from a view to a form?
I am initializing a form with an argument. Part of my view: items = Location.objects.filter(patient=pk) query_form = QueryForm(items) forms.py class QueryForm(forms.Form, items): period = forms.IntegerField() location = forms.ModelChoiceField(queryset=Location.objects.all().order_by('location_name')) but I get the error NameError: name 'items' is not defined. -
how can I count events-- django project
hello everyone I am still beginner in programming but I need to do this project. I can't code this part so I need your advices . Okey I don't wanna make it long I will show you here the code models.py from django.db import models # Create your models here. class Pays(models.Model): Pays = models.CharField(max_length=100) def __str__(self): return '{} '.format(self.Pays) class Raison(models.Model): Raison_cd = models.IntegerField(blank=True) Raison_NM = models.CharField(max_length=100, blank=True) def __str__(self): return '{}, {} '.format(self.Raison_cd,self.Raison_NM) class Mesure(models.Model): Mesure_cd = models.IntegerField(blank=True) Mesure_NM = models.CharField(max_length=100,blank=True) def __str__(self): return '{}, {} '.format(self.Mesure_cd,self.Mesure_NM) class Client(models.Model): Nom = models.CharField(max_length=250) Prenom = models.CharField(max_length=250) Adresse = models.CharField(max_length=560) Ville = models.CharField(max_length=100) code_postal = models.IntegerField() telephone = models.IntegerField() mail = models.CharField(max_length=100) def __str__(self): return '{}, {},{} '.format(self.Nom,self.Prenom,self.Ville) class Delivery_Agent(models.Model): Nom = models.CharField(max_length=250) Prenom = models.CharField(max_length=250) def __str__(self): return '{}, {} '.format(self.Nom,self.Prenom) class Office(models.Model): office_cd = models.CharField(max_length=10) office_NM = models.CharField(max_length=50) def __str__(self): return '{}, {} '.format(self.office_cd,self.office_NM) class Mail_item_Event(models.Model): mail_item_fid = models.CharField(max_length=36) Event_cd = models.IntegerField() office_Evt_cd = models.ForeignKey(Office, on_delete=models.CASCADE, related_name='office_Evt') Date_Evt = models.DateTimeField() Date_Capture = models.DateTimeField() Next_office = models.ForeignKey(Office, on_delete=models.CASCADE, related_name='Next_office') def __str__(self): return '{}, {} , {}'.format(self.Event_cd,self.Date_Evt,self.mail_item_fid) class Delivery_info(models.Model): mail_item_fid = models.CharField(max_length=36) Event_cd = models.ForeignKey(Mail_item_Event,on_delete=models.CASCADE, related_name='Eventcd') office_Evt_cd = models.ForeignKey(Office,on_delete=models.CASCADE, related_name='office_Evt2') Date_Evt = models.DateTimeField() Agent_delivery_cd = models.ForeignKey(Delivery_Agent,on_delete=models.CASCADE,related_name='agentDelivery') Signatory_NM = models.ForeignKey(Delivery_Agent, on_delete=models.CASCADE, … -
How to get attributes from foreignkey model in Django?
I have three models, item, variation and item_variations. The item has a foreignkey relation with variation, which in turn have a foreignkey relation with ItemVariation model. My question is, how do I access the attributes of Item variation to get hold of dynamic data by using the model Item. But I'm not being able to do so. Can anyone please help me with this? My models.py: class Item(models.Model): title = models.CharField(max_length=120) price = models.FloatField() class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) name = models.CharField(max_length=50) # size, color class ItemVariation(models.Model): variation = models.ForeignKey(Variation, on_delete=models.CASCADE) value = models.CharField(max_length=50) # small, medium large etc My admin.py: class ItemVariationAdmin(admin.ModelAdmin): list_display = ['variation', 'value'] list_filter = ['variation', 'variation__item'] search_fields = ['value'] class ItemVariationInLineAdmin(admin.TabularInline): model = ItemVariation extra = 1 class VariationAdmin(admin.ModelAdmin): list_display = ['item', 'name'] list_filter = ['item'] search_fields = ['name'] inlines = [ItemVariationInLineAdmin] admin.site.register(ItemVariation, ItemVariationAdmin) admin.site.register(Variation, VariationAdmin) My views.py: class ItemDetailView(DetailView): model = Item template_name = 'products/product.html' My product.html: <h1 class="product-title">{{ item.title }}</h1> <a href="#"> <span class="badge purple mr-1">{{ object.get_category_display }}</span> </a> <form class="form" method="POST" action="{{ object.get_add_to_cart_url }}"> {% csrf_token %} {% if object.itemvariation_set.all %} <h5>{{ object.itemvariation_set.all }}</h5> {% endif %} <div class="action"> <button class="btn btn-success">Add to Cart</button> </div> </form> -
How to delegate an object in django?
I have two models User and Object (both are custom models). Different users have different objects based on their attribute values. Basically, user1 has obj1, obj2 and user2 has obj5 and etc. So I need a simple delegation method to be able to delegate objects to different users temporarily (and later on revoke them). So far I could not find something similar. I hope someone could help. -
Passing html as a template variable django
I am passing some html to my template like this passDict["problemText"] = <p> Some html</p> return render(response,'main/base.html',passDict). And then displaying {{problemText}} in my html file.I get Some html as my text and not Some html in a paragraph like i want. -
Error activating virtualenv with docker ENTRYPOINT script
I am trying to build a simple Django Docker container with virtualenv setup on Windows 10. The image itself is build successfully, however when I attempt to start the containers with the entrypoint script, I am getting a weird error that my virtualenv files are not found. Note that the container was working perfectly fine before I decided to add the virtualenv section (as per my TODO note in the Dockerfile). The container was UP and running. Can anyone share their thoughts as to why this is happening? Note this is my first alpine image. PS. I am using PyCharm as my IDE and I have changed all line separators to be LF D:\Code\Projects\Test_virtualenv_Dockerfiles>docker-compose ps Name Command State Ports ------------------------------------------------------------- django_test /venv-entrypoint.sh sh -c ... Exit 2 docker-compose.yml version: '3.2' web: build: context: . dockerfile: Deploy/Django/Dockerfile image: django_test container_name: django_test volumes: - .:/app_server ports: - "9000:8000" tty: true command: > sh -c "python manage.py runserver 0.0.0.0:8000" Dockerfile FROM python:3.8-alpine MAINTAINER cBeTyLkaTa # Setup environment variables ENV PYTHONUNBUFFERED=1 \ RUN_USER=www-data \ ENV_DIR=/app_server \ VIRTUALENV_DIR=/app_server/venv \ BIN_DIR=/app_server/venv/bin \ HOME_DIR=/var/www # Create new run user RUN adduser -D $RUN_USER # Setup work directory RUN mkdir $ENV_DIR $HOME_DIR WORKDIR $ENV_DIR # Install packages # … -
A 404 error with "id-" in slug on multilingual website with Indonesian language in Django 3.0
http://example.com/de/id-button/ - 200 OK http://example.com/id/id-button/ - 200 OK http://example.com/any-other-slug/ - 200 OK http://example.com/id-button/ - 404 error: Using the URLconf defined in example.urls, Django tried these URL patterns, in this order: id/ The current path, id-button/, didn't match any of these. urls.py file: urlpatterns = i18n_patterns( path('admin/', admin.site.urls), path('', cache_page(cache_homepage)(homepage_views.index), name='index'), path('search/', search_views.search, name='search'), path('<slug:slug>/', emoji_views.emoji, name='item'), prefix_default_language=False, ) The item have a slug field in DB "id-button". If I rename this to "idbutton": http://example.com/idbutton/ - 200 OK But I need to have url like: http://example.com/id-button/ -
Ajax call with django on bootstrap dropdown
Problem Statement : I am not getting a way by which I can load the whole chart html in the div by calling a function from views.py and passing the context to the refernece_page.html without refreshing the page. I have a chart just like any stock chart. I have a durtion dropdown for which I have used a Bootstrap dropdown. <div class="dropdown show " style="float:left; "> <a aria-expanded="false" aria-haspopup="true" role="button" data-toggle="dropdown" class="btn btn-secondary dropdown-toggle" href="#"> <span id="selected" >Event Time</span><span class="caret"></span></a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">1 Hour</a></li> <li><a class="dropdown-item" href="#">1 day</a></li> <li><a class="dropdown-item" href="#">1 Week</a></li> <li><a class="dropdown-item" href="#">1 Month</a></li> </ul> </div> I want to make to update the dive which has the chart in place without refreshing the page. For this I have a "per_hour_data" function in views.py which loads with default value of duration "1 Hour". def per_hour_data(request, app_id, record_count): app_detail = get_object_or_404(AppDetail, app_id=app_id) line_data = line_chart_data(app_id,record_count) app_data = AppDetail.objects.all() context = { 'line_data':line_data, 'app_detail': app_detail, 'record_count':{'1day':'1day', '1hour': '1hour', '1week':'1week', '1month':'1month'}, 'app_data':app_data, } return render(request, 'status_monitor/reference_page.html', context) The reference_page.html has the chart data and where I am parsing the context. Now I want to do something like when I select different duration then the chart should get updated without refreshing … -
Python/HTML: Using form inputs as variable, submit form and print output in HTML file
I am a beginner in Python. I have created a Python script that requires two variables to be entered as input that works without problem. I have created a Django project and I intend to have an HTML page with a form with two input and a submit button. When the submit button is pressed, the script should run with the two form inputs as variables. Then the output from the script should be printed in a separate HTML page. I have read about views, httpresponse, websockets... As I said, I am an almost complete beginner to Python so every bit of help is appreciated! Thanks! -
Django audio, video and image upload
I have trying to solve this problem for so long somebody please please please help me. So I am a newbie I'm django and I am learning it. I made an app where you can upload files. I have used the filefield in my models but the problem is if I want to upload a image file I have to use the img tag in html and if I want to upload a video I have to use the video tag and similarly for audio I have to use the audio tag but the problem is if I upload a video it won't show in img tag and vice versa. So how do I make that the user just upload a file and it automatically use the required tag in html just like instagram, you can upload video audio image. If any one knows anything please help please please please. -
Creating a Serializer to work with model relationships
I am new with Django Rest Framework and wanted to understand what's the accepted practice for writing Serializers that work with nested relationships. Say, I have a models called Client and Invoice (this is just an illustrative example): class Client(models.Model) name = models.CharField(max_length=256) class Invoice(models.Model) client = models.ForeignKey(Client) date = models.DateTimeField() amount = models.DecimalField(max_digits=10, decimal_places=3) I want to create a Serializer for Client that supports the following use cases: Create a Client When I create an Invoice, refer to the Client using its id. Let's say I use this implementation: class ClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = ['id', 'name'] class InvoiceSerializer(serializers.ModelSerializer): client = ClientSerializer() class Meta: model = Invoice fields = ['id', 'client', 'date', 'amount'] def create(self, data): client = Client.objects.get(pk=data['client']['id']) invoice = Invoice(client=client, date=datetime.fromisoformat(data['date']), amount=Decimal(data['amount'])) invoice.save() With this code, if I try to create an Invoice, I need the client object in the POST data to contain name as well. There is no config of the name field (read_only=True, write_only=True, required=False) that allows me to create and read Client as well as not be required when creating the Invoice. How should this be solved? Is the accepted practice that the request include the name field anyways? Can … -
Image files upload to AWS S3 Bucket, but don't render on django heroku App
I have a Django webapp that is hosted on Heroku. The site functions perfectly except or the image rendering. I am using AWS S3 buckets. How my images currently look. This is the output when right click and view image in a new tab This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>InvalidRequest</Code> <Message> The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256. </Message> <RequestId>B965F49FC9AD8BD8</RequestId> <HostId> NyDkC2+pLPd/5tzWgJb+dEJOWu7eNCfbVyqLdZWOr1JyIFTe6rZ8BbRJHlbweCLU1MJ7xmlrxEM= </HostId> </Error> Settings.py import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # (os.environ.get('DEBUG_VALUE') == 'True') ALLOWED_HOSTS = ['xxx.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'users.apps.UsersConfig', 'blog.apps.BlogConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_cleanup', 'taggit', 'hitcount', 'storages', ] *************** *************** # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' CRISPY_TEMPLATE_PACK = 'bootstrap4' LOGIN_REDIRECT_URL = 'blog-home' LOGIN_URL … -
Is it possible to call as_view from the controller?
Is it possible to call the as_viev() method of class from the controller? I need to pass a variable that is initialized in the controller. It looks like routing urlpatterns = [ path('form/check/', room_check, name='room_check'), path('contact/', BookWizard.as_view(FORMS, initial_dict=initial)), ] Book Wizard - a class inherited from SessionWizardView from 'formtools' module The following is a piece of the controller where the variable is created initial = { '0': {'check_in_date': check_in_date, 'date_of_eviction': date_of_eviction, 'category': category, 'number_of_adults': number_of_adults, 'number_of_children': number_of_children}} return redirect(BookWizard.as_view(FORMS, initial_dict=initial)) As a result, I get this error: error Maybe there is another way to pass the variable and call the method? -
Django,referring objects with double underscore
I have a function in the view file of Django Rest Framework project. Where it filters out comments (A model) with related to the specific Post class CommentListCreate(APIView): def get(self, request,pk): comment = Comment.objects.filter(post_id=pk) serializer = CommentSerializers(comment, many=True) return Response(serializer.data) The above function is able to filter according to the post_id, but if I change filter arguments as mention below def get(self, request,pk): comment = Comment.objects.filter(post__id=pk) The function works fine, why do we use double underscore to refer the the post id ? Git Link to my views.py https://github.com/Anoop-George/DjangoBlog/blob/master/blog/views.py -
Django, how to calculate monthly salary from constraints
I have the following models.py: class PersonaleDipendente(models.Model): start=models.DateField end=models.DateField monthly_salary=models.DecimalField monthly_number=models.DecimalField I want to obtain a queryset that yearly calculate the monthly salary ( given by the following formula monthly_salary*monthly_number/12) taking into account the start and end date. Just an example: If the data are the following: start=1/10/2020 end=1/08/2020 monthly_salary=100 monthly_number=12 the queryset will be: [100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 0, 0, 0, 0] I have tried the following code but does not give me the result wanted. for year, month, totale in (PersonaleDipendente.objects.values_list('start__year', 'start__month').annotate(totale=ExpressionWrapper(Sum(F('monthly_number')*F('monthly_salary')/12), output_field=FloatField())).values_list('start__year', 'end__month', 'totale')): personale_dipendente=list(defaults) index=month-1 personale_dipendente[index]=totale