Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin, ImageField: choose image from uploaded
I have a pretty simple model: class Article (models.Model): title = models.CharField(max_length=120) content = RichTextUploadingField(blank=True, default='') logo = models.ImageField(default='media/images/default.jpg', upload_to='media/images') I can upload images from local PC to the server, but how can I choose from already uploaded images? In Django Admin when I press "choose file" button, the local file system window is opening. -
Django Form: Calling foreign key field attributes in template
In a template I want to call a class attributes of a foreign-key form field item.pid like shown below {%for item in form.item %} {{item.pid}} {% endfor %} My question is simple and the solution should be as well but I am stuck here for way too long now. I have tried formsets, inlineformsets, clean and so many more things which are in the documentation and here on SO. It's even not possible to call a class method of a form field. calling {{form.instance.item.pid}} should be the solution but I can't get it running. model.py class Event(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE, blank=True, null=True, default=0) item = models.ForeignKey(Item, on_delete=models.CASCADE, blank=True, null=True, default=0) #many more class Person(models.Model): person_number = models.IntegerField(null=True) name = models.CharField(max_length=200, null=True) surname = models.CharField(max_length=200, null=True) #many more class Item(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE, blank=True, null=True, default=0) pid = models.IntegerField(null=True) #many more def save(self, *args, **kwargs): self.pid = Person.objects.filter(surname=self.person.surname, name=self.person.name).values("person_number") super(Item, self).save(*args, **kwargs) views.py def event(request, event_id=None): if event_id: instance = get_object_or_404(Event, pk=event_id) else: instance = Event() form = EventForm(request.POST or None, instance=instance) if request.POST and form.is_valid(): form.save() return HttpResponseRedirect(reverse('cal:calendar')) context = { 'form': form, } return render(request, 'cal/event.html', context) forms.py class EventForm(ModelForm): class Meta: model = Event fields = … -
How to save continually the countdown number of days in the database in django?
I am developing an insurance car web app where the customer can come and block his insurance at any time if the car has a problem. I would like to count daily and save in the database the number of days remaining, and also if the customer blocks his insurance, that I can stop counting until he comes to activate it. At the moment, I can only save when the customer blocks or unblocks their insurance via the insurance contract modification function. Here is the update contract function: def ContratUpdate(request, id=None): context = {} detail = get_object_or_404(Contrat, id=id) contract = request.POST.get('numero_de_contrat') form = ContratAddFrom(request.POST or None, instance=detail) if form.is_valid(): instance = form.save(commit=False) instance.save() id = form.instance.id contrats=Contrat.objects.filter(numero_de_contrat=contract) for contrat in contrats: if contrat.statut_assurance =='Reprise': nb_Days = contrat.nombre_de_mois+contrat.created.day-date.today().day contrat.remainingdays=nb_Days contrats.update(remainingdays=nb_Days) elif contrat.statut_assurance=='Suspendre': nb_Days = contrat.remainingdays+contrat.created.day-contrat.modified.day contrat.remainingdays=nb_Days contrats.update(remainingdays=nb_Days) return redirect('assurance_auto:Contrat_Liste') else: form = ContratAddFrom(instance=detail) context["form"] = form return render(request, 'auto/UpdateContrat.html', context) And this is what I am trying to do in the contract model in order to solve my issue but it does not working: class Contrat(models.Model): Statut_contrat = ( ('Encours', 'Encours'), ('Suspendre', 'Suspendre'), ) # numero_de_contrat = shortuuid.uuid() numero_de_contrat = models.CharField(max_length=10, unique=True, null=False, blank=False) statut_assurance =models.CharField(max_length=15, choices=Statut_contrat) vehicule = models.ForeignKey(Vehicule, on_delete=models.CASCADE) … -
how to display dynamically generated image in django template stored in variable with image path in local folder
im trying to display image in template but ive tried every method and it fails. I have a function that takes a user input image and search for the closest match in the database that also has a set of images and gives the result with the closest match. The database of these images are all stored in folder in a local folder (C:\Users\Sairar\Dev\image\src\makeup\db_images). Once the result is generated the image is then stored in a variable eg "mimg". Now mimg is a vaariable that contains my resultant image. when i write mimg.show, it works and the image is displayed on the screen but the only problem is dsplaying it on the template which im unable to figure. -
Is there any way in django to get a string representation of a url full path
So I'm trying to send a url to an external website as a callback url for some process and I was wondering if there's anyway or function where maybe if I pass in the url name from urlpatterns and required args it would return the full path of the url as a string instead of hard coding it in. The url in urls.py looks something like this: app_name = example_app urlpatterns = [ ... '<int:example_id>/, views.my_function, name='some_name' ] And I want something like this just as a string: https://my_site_domain.com/example/1/ # 1 is the example_id -
Django: how can i call a function from a HTML button click
I am trying to use buttons to change the values in my fields. I am looping through the fields to display the buttons. I think something like using a javascript onclick event that calls a function in the views that assigns a value to the field is what i need but i can't find how to call a function in the views from javascript. -
Why is migration for removing a base class from a model fails?
I've got this model that inherits from another: from postman import models class Message(models.Message): subclass_field = TextField(blank=True, null=True) Now when I remove the base class postman.models.Message and run makemigrations I get this: operations = [ migrations.RemoveField( model_name='message', name='message_ptr', ), migrations.AddField( model_name='message', name='id', field=models.AutoField(auto_created=True, default=1, primary_key=True, serialize=False, verbose_name='ID'), preserve_default=False, ), ] Now the only issue is that when running it it says this: django.core.exceptions.FieldError: Local field 'id' in class 'Message' clashes with field of the same name from base class 'Message'. Am I doing something wrong? This is a pretty basic case of removing base model from a model, you'd think it would work -- why is it not working? -
How to set a serializer field as not required in django rest framwork?
I want the story_media field to be optional when a story is created. This means that it is up to the user to add some media to a story or not. But if I submit the data without the story_media field, I get the error that story_media is required. I followed the approach from the Django documentation and added extra_kwargs = {'story_media': {'required': False}} as keyword argument. However, the error message remains. class StoryCreateUpdateSerializer (serializers.ModelSerializer): story_media = Story_Media_Serializer(many=True) class Meta: model = Story fields = ('title','description', 'place', 'audio','story_media', 'language', ) extra_kwargs = {'story_media': {'required': False}} def create(self, validated_data): current_user = self.context["request"].user story_media = validated_data.pop('story_media') story_instance = Story.objects.create(author=current_user, **validated_data) for img in story_media: Story_Media.objects.create(**img, story=story_instance) return story_instance -
Continue when task in celery chunks fails
I need to fetch millions of ids from a remote server. I do not want to create millions of tasks at once, because each fetch creates several another tasks and it could quickly overwhelm our queue (I am unable to create a new queue). I found out, that I could use celery.chunks. This would create a moderate amount of parallel tasks. FetchIdTask().chunks(milions_of_ids, 50000).apply_async() The problem I face now is that the fetch isn't reliable and sometimes returns 404. And when this happens the whole chunk fails and remaining tasks won't be executed. Is it possible to somehow continue when one of the tasks in a chunk fails? -
How can I fix this Django HTML template bug?
I have this weird bug with Django HTML templates, that everything seems to be placed inside the body nomatter what I do. Additionally it adds some invisible text that gives the whole page a little offset. How my browser displays the Sourcecode when I inspect the elements How the pages sourcecode looks when I open it inside the browser The second image is how it is supposed to look like. This is how my actual code looks like: base.html: {% block content %} {% endblock content %} home.html: <!DOCTYPE html> {% extends "blog/base.html" %} {% block content %} <html> <head> <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Name</title> </head> <body> <p>Text</p> </body> </html> {% endblock %} This only happens when I use inheritance. When I put alle the code in one .html file it gets displayed as it should. I've tried to move the block part and for example but the everything but the paragraph inside the base.html file but it didn't change anything. I hope someone can help me. This is my first post stackoverflow btw, so please be kind. -
React+Django or only Django?
I want to create a website using ReactJs for Frontend and Django for the backend, so is this possible? And if it's possible then is it that easy to build or integrate react into Django. Shall I go with Reactjs + Django or Only Django? What should I do? Please Help. -
Unable to point a domain to IP Address which is hosted at AWS Lightsail Ubuntu Instance
I am trying to point my domain to my IP Address which hosts my Django website on AWS Lightsail Ubuntu Instance. The Website is working fine on my IP Address (eg: http://12.123.123.123). But on my domain (api.repair.tntwatches.in) the Website is not running even after pointing the IP Address. It's just showing an nginx page. I have also added the domain name to Lightsail DNS setting. Where am I going wrong, please help me with it... Thank You -
Auto init Fields Form Django
I'm trying to get Request from HTML form and i used get_initial to initial fields. forms.py class RequestJobForm(forms.ModelForm): class Meta: model = Request fields = ('problem','employee', 'author',) views.py class EmployeeDetailView(FormMixin, DetailView): model = Employee form_class = RequestJobForm template_name = "employee_detail.html" def get_initial(self): initial = super().get_initial() initial['employee'] = self.get_object() initial['author'] = self.request.user return initial def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.save() return super(EmployeeDetailView, self).form_valid(form) form.html <form method="post"> {% csrf_token %} {% render_field form.problem %} <button class="btn btn-primary btn-block" type="submit">submit</button> </form> But i get employee_id can't be null. i need to render problem field only and get author & employee without rendering it. -
How to save a BeautifulSoup Tag object to django database?
I'm trying to parse some tags from a xml document and save them into django database so I can use them later. E.g.: I have a tag p which is a bs4.element.Tag. >>> print(p) <w:p w:rsidP="438FBAC8" wp14:paraId="3B92C830" wp14:textId="0384D974" xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordml"/> >>> type(p) <class 'bs4.element.Tag'> I want to save this tag into the django database so I can retrieve them later and perform .wrap() with them. How do I create a field that can accept a BeautifulSoup tag so the tag can be save into the database? I imagine it would look something like below: class SoupTag(models.Model): segment = models.ForeignKey(Segment, on_delete=models.CASCADE) tag = TagField() # I can use it like below outer_tag = SoupTag.objects.filter(segment=segment_object).first() inner_tag = SoupTag.objects.filter(segment=segment_object).last() wrapped_tag = outer_tag.tag.wrap(inner_tag.tag) >>> print(wrapped_tag) <w:p w:rsidP="438FBAC8" wp14:paraId="3B92C830" wp14:textId="0384D974" xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordml"><p>inner tag</p></w:p> Thank you in advance for your help! -
Django admin tabular inline lookup select dropdown box for a very large queryset
I have a django admin tabular inline, in which I have form = ProdForm which holds a modelchoicefield select box as follows; class ProdForm(forms.ModelForm): productid = forms.ModelChoiceField(queryset=Product.objects.filter(active=True), widget=Select2(select2attrs={"width": "400px"}), ) as you can see, I am using the easy_select2 module, that is enabling providing me with a look up field too. However, if I try to load this in the corresponding tabularInLine, it never loads because there is a very high number of records (suppose millions). Therefore loading the entire queryset is not possible. I need to find a way to do this so people using the admin can search the object they need, suppose by a name which is one of the attributes on the Product model. An idea is to keep the search box but not load the queryset initially and hit the db when there are, for example 3 or more letters in the search field, that could maybe work. However, that would include some js that I am not really familiar with and I would prefer some pythonic/django way of doing this. Or maybe there is a nice django way but I haven't found it and I am at my wits end. I would appreciate any … -
Django: How to reduce stock quantity when an order is made?
My goal is to reduce stock quantity when an order is created. My stock item is a Tyre. The tyre has a model field for quantity. Here is my views.py from django.shortcuts import render, redirect from .models import OrderItem from .forms import OrderCreateForm from cart.cart import Cart from stock.models import Tyre, Branch from django.contrib.auth.decorators import login_required @login_required(login_url="/accounts/login/") def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create( order=order, tyre=item['tyre'], price=item['price'], quantity=item['quantity'] ) # reduce tyre stock quantity order_item = OrderItem.objects.get(id=id) tyre = Tyre.objects.get(id=id) tyre.quantity = tyre.quantity - order_item.quantity tyre.save() cart.clear() return redirect('orders:sale-orders') # return render(request, 'orders/sale_orders.html', {'order': order}) else: form = OrderCreateForm() return render(request, 'orders/create_order.html', {'form': form}) When i run the code, I got this error: TypeError at /orders/create/ Field 'id' expected a number but got . I appreciate any help -
How to save file in perform_create method?
How to save file in perform_create method? class CreateItemAPIView(CreateAPIView): authentication_classes = (SessionAuthentication, ) permission_classes = (IsAuthenticated, ) serializer_class = CreateItemSerializer parser_classes = (MultiPartParser, FormParser) def perform_create(self, serializer): user = self.request.user if serializer.validated_data.get('receipt_source', None): format, imgstr = serializer.validated_data['receipt_source'].split(';base64,') ext = format.split('/')[-1] data = ContentFile(base64.b64decode(imgstr)) file_name = "'temp_name." + ext # obj.receipt_file.save(file_name, data, save=True) serializer.save(created_by=user, receipt_file=???) # receipt_file is just FileField in Django model -
What will be the corresponding django view function for the python script?
I have a python script that converts csv files into pipe delimiter files. If the total no of lines is above 7000, it creates new files, and headers of output files are also changed. I have a python function that works perfectly. headers = ['firstname', 'lastname'] def file_conversion(input_file, output_file_pattern, chunksize): with open(input_file,"r+") as fin: # ignore headers of input files for i in range(1): fin.__next__() reader = csv.reader(fin, delimiter=',') for i, chunk in enumerate(chunked(reader, chunksize)): with open(output_file_pattern.format(i), 'w', newline='') as fout: writer = csv.writer(fout,reader,delimiter='^') writer.writerow(headers) writer.writerows(chunk) print("Successfully converted into", output_file_pattern) # count total number of lines def total_lines(input_file): with open(input_file) as f: return sum(1 for line in f) print("Total Number of lines:",total_lines(input_file)) file_conversion(input_file,cn+'{:06}.csv',7000) I want to create a django application that has a form where input file is uploaded. What will be the corresponding django views function for the above function. I have tried too but more suggestions and ideas will be highly appreciated. views.py def index(request): csv_form = '' if request.method == 'POST': csv_form = CsvForm(request.POST, request.FILES) if csv_form.is_valid(): csv_file = csv_form.cleaned_data['csv_file'] messages.info(request,"Successfully converted the csv file into"+"") ???????? context = {'csv_form' : csv_form} return render(request,'index.html', context) forms.py from django import forms class CsvForm(forms.Form): csv_file = forms.FileField() -
Accessing the pk from GET request returns a tuple
I have a 'Search' form consisting of 3 fields that provide some criteria for the eventual database query. The form submits via the GET method. One of the fields is a ModelChoiceField and renders as a Select widget. The value of each option is the related object's primary key- In my case the default primary key assigned by Django. My understanding was that this value is an integer and is turned into a string in the request. Therfore, in my view to handle the data I have int(self.request.GET.get("name")). However the error I get suggests the value is a tuple: TypeError Field 'id' expected a number but got (11,). The above exception (int() argument must be a string, a bytes-like object or a number, not 'tuple') was the direct cause of the following exception: Is there something I'm doing wrong? or otherwise how can I best retrieve this value as a integer so that I can complete my database filter: Product.objects.filter(id=product_id)? -
I can't push django app in heroku Push rejected, failed to compile Python app
I can'y push my django app in heroku this is erorr message: -----> Python app detected ! Python has released a security update! Please consider upgrading to python-3.9.1 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> Installing python-3.9.0 -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 -----> Installing SQLite3 -----> Installing requirements with pip ERROR: Invalid requirement: 'Package Version' (from line 1 of /tmp/build_eb871c0d_/requirements.txt) ! Push rejected, failed to compile Python app. ! Push failed -
Django, have model to be related to many instances of itself
I have a model: class Industry(models.Model): name = models.CharField(max_length=60, unique=True, null=False, blank=False) I want it to have a sub_industries field that will hold all of its sub industries, which should be instances of Industry model. I cannot be ManyToMany because each industry has only one parent industry. -
Why my applied changes in urls.py is not reflecting after I tried reloading the Django web page?
In views.py from django.http import HttpResponse def home_page(request): return HttpResponse("<h1>Hello, World</h1>") In urls.py from django.contrib import admin from django.urls import path from .veiws import home_page urlpatterns = [ path('', home_page), path('admin/', admin.site.urls), ] Starting development server at http://127.0.0.1:8000/ -
NOT NULL constraint failed: shop_review.item_id
def order(request, item_id): item = get_object_or_404(Item, pk=item_id) if request.method == "POST": username = None username = request.user.username userInfo = username + '/' + request.POST["nameNum"] userAddr = request.POST["address"] new_order = Review.objects.create( reviewText = userInfo, votes = userAddr ) return HttpResponse("<script>alert('" + userInfo + '/ ' + userAddr + "');</script> 등록 완료") return render(request, 'order.html', {'item': item}) This is my views.py, and class Item(models.Model): def __str___(self): return self.item_name item_name = models.CharField(max_length=100) item_text = models.CharField(max_length=300) pub_date = models.DateTimeField('date published') item_amount = models.CharField(max_length=99999999) item_image = models.ImageField(upload_to='image/', blank=True) item_id = models.AutoField(primary_key=True) this is my models.py. And when I run this part, NOT NULL constraint failed: shop_review.item_id << this error occurs. How can I fix this error? enter image description here -
Django Form issue
I have the following code in <form action="{% url 'set_language' %}" method="post" id="setlocal" name="language"> {% csrf_token %} <input class="lang" id="language" name="language" type="hidden"> <input class="lang" id="language" name="language" type="hidden" value="ar"> <input class="lang" id="language" name="language" type="submit" value="Go"> <select name="language" onchange="this.form.submit()" > {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% for lang in LANGUAGES %} <option value="{{ lang.0 }}" {% if lang.0 == LANGUAGE_CODE %} selected="selected"{% endif %}> {{ lang.1 }} ({{ lang.0 }}) </option> {% endfor %} </select> The select option works fine and change the language and redirect properly . But if I use the "Go" button , nothing is changing . I am wondering what is issue. -
Conditionally calling __str__ in models.py in accordance to the "related_name" Django
Okay so here is my models.py first: class UserFollowing(models.Model): user = models.ForeignKey(CustomUser, related_name="following", on_delete=models.CASCADE) following_user = models.ForeignKey(CustomUser, related_name="followers", on_delete=models.CASCADE) created = models.DateTimeField(default=timezone.now, db_index=True) def __str__(self): return f"{self.user} follows {self.following_user}" So in this case, when I try like this: >>> user = CustomUser.objects.get(id=1) # just a user >>> user.following.all() # A follows B >>> user.followers.all() # B follows A However, I want to do it like this: >>> user.following.all() # B (Since A is following B) >>> user.followers.all() # B (Since B is a follower of A) But how can I differ the __str__ outputs according to the related_name? I couldn't find any information on this so is there a way?