Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError for model class in django
I ran into the following error. File "C:\django-project\CodingWithMitchBlog\demoproject\Blog\api\urls.py", line 3, in from demoproject.Blog.api.views import api_detail_BlogPost_view ModuleNotFoundError: No module named 'demoproject.Blog' Blog is my appname. This is my project structure. -
Django DateTimeInput returns incorrect format for Database
I'm looking for the simplest datetimepicker to implement on a Django form, and would like to use the included Django DateTimeInput widget. No matter what I try however, the widget returns a datetime value in an incorrect format which will not upload to my database. I need the format '%Y-%m-%d %H:%M:%S', but the widget returns '%d/%m/%Y %H:%M:%S' This problem has been discussed a little here: http://stackoverflow.com/a/35968816/1382297 I believe the problem may be from setting the input_type to DateTime-local, but i am unaware of other options and cannot find any in the documentation. I've tried passing format='%Y-%m-%d %H:%M:%S' to the widget, as well as FORMAT_INPUTS = ['%Y-%m-%d %H:%M:%S'], and tried initializing these in the DateInput class, all with no luck. Below is my forms.py class DateTimeInput(forms.DateTimeInput): input_type = 'datetime-local' class EnterMatchForm(forms.ModelForm): class Meta: model = match fields = ('match_name', 'player1', 'player2', 'victory', 'match_description', 'match_date') widgets = { 'match_date': DateTimeInput(), } What is the proper way to initialize the widget so that it returns datetime values in the format Y-m-d H:M:S? Thanks in advance. -
Django DRF send post request parameters as form data
I want to send post request api parameters as form data instead of passing it as url. -
Pass extra args with kwarg running function
Is it possible to pass extra args or kwargs in model photo_1 --> upload_to? I want to pass extra data (size) to prepare custom file name. i have tried def upload_to_id_image(self, filename, size=""): fname = filename.split('/')[-1] return f'thumbs/{fname}' photo_1 = ProcessedImageField( null=True, blank=True, processors=[Thumbnail(192)], options={'quality': 85}, upload_to=upload_to_id_image(size="192") ) but it seems doesn't work whole model: class Photo(AddedUpdatedModel): name = models.CharField(max_length=128, null=True, blank=True) file = ThumbnailerImageField(upload_to='temp/') photo_type = models.ForeignKey(PhotoType, on_delete=models.PROTECT, null=True, blank=True, default=None) def upload_to_id_image(self, filename): fname = filename.split('/')[-1] return f'thumbs/{fname}' photo_1 = ProcessedImageField( null=True, blank=True, processors=[Thumbnail(192)], options={'quality': 85}, upload_to=upload_to_id_image ) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.photo_1: self.photo_1 = self.file.file super().save(*args, **kwargs) i am looking for solution to pass size in model above -
Using django-fsm to determine the state of an object
How do I get the current state of a database item using django-fsm. I have tried get_state() but it returns a null value. Here is my code: from django.db import models from django_fsm import FSMField, transition STATES = ("Open", "In Progress", "Re Opened", "Done", "Closed") STATES = list(zip(STATES, STATES)) class Ticket(models.Model): title = models.CharField(max_length=40) state = FSMField(default=STATES[0], choices=STATES) Is there a way of getting the state field using django-fsm library. Also, how do I get the available state transitions using the model methods. -
Django Settings not configured
I created a web project using Django and PyCharm, everything was working fine. When I reopened the project and added git, all the files were in red and when I tried to runserver I got a huge error message. The last error message is: django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTING S_MODULE or call settings.configure() before accessing settings. Here is a screen shot:You must either define the environment variable DJANGO_SETTING I am trying to figure out why everything just stopped working. Any help would be awesome. Thank you in advance. L -
Can't access Django website deployed on EC2
I tried deploying my django project on an AWS EC2 instance but when I try to access the instance through its public DNS I do not get anything back. Things I have already done: Setup the NACL to allow all traffic for now Setup the Security group to allow all traffic for now Ensure that instance is inside a VPC and VPC is connected to an internet gateway Set the allowed hosts config in the django settings to ['.compute.amazonaws.com'] When I try to run the server on 0.0.0.0:8000 and try to access it through the browser I do not get any response. What could I possibly check to solve this problem? -
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 …