Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to upload multiple Image in Django
I am trying to upload multiple images in my Django project, but it is not working. Although, I have tried many things but there is no error. My HTML FILE <input type="file" class="form-control" name="photo" id="photo" accept=".png, .jpg, .jpeg" onchange="readFile(this);" multiple> My Models class MyGeneralModel(models.Model): some_name=models.CharField(max_length=50,blank=True, null=True) ..... Here I am generating dynamic file name. def get_image_filename(instance, filename): title = instance.image_for.some_name slug = slugify(title) unique_slug = slug return "scammer_images/%s-%s" % (unique_slug, filename) Here is my Image Model. class Images(models.Model): image_for = models.ForeignKey(MyGeneralModel, default=None,on_delete=models.CASCADE) image = models.ImageField(upload_to=get_image_filename, verbose_name='Image',blank=True, null=True) And my views.py is here. The variable get is the instance of MyGeneralModel. for file in request.FILES.getlist('photo'): instance = Images.objects.create(image_for=get,image=file) -
How to pass a value to the template in class based views in django?
I want to send a value of a variable to a PostDetail template, Here's the function of the views.py file class PostDetailView(DetailView): model = Post def get_object(self): obj = super().get_object() obj.view_count += 1 obj.save() return obj def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) texts = self.object.content Read_Time=get_read_time(texts) print(Read_Time) return context Here's the output of the terminal:- [04/Sep/2020 19:29:04] "GET /post/this-blog-contains-an-image-with-it/ HTTP/1.1" 200 6089 0:02:00 [04/Sep/2020 19:29:24] "GET /post/this-blog-contains-an-image-with-it/ HTTP/1.1" 200 6089 I want to send the 0:02:00 to my template, How can I make this happen? -
Why Does Django Query to Check Uniqueness?
tl;dr: Why does Django's uniqueness check on INSERT require a SELECT query, and can I permanently disable it? I'm working to highly optimize a Django app that is writing to a PSQL database. I have a uuid column which is a primary_key as part of my model. It is the only unique field in the model. id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False, null = False, blank = False, help_text = 'The unique identifier of the Node.' ) The issue I'm encountering is that when attempting to save a new item, Django automatically performs a uniqueness check query prior to the insert: SELECT (1) AS "a" FROM "customer" WHERE "customer"."id" = \'1271a1c8-5f6d-4961-b2e9-5e93e450fd4e\'::uuid LIMIT 1 This results in an extra round trip to the database. I know that the field must be unique, but of course Django has already configured this at the database level - so if it tries to insert a row with a non-unique field it will get an error. I've implemented a workaround which suppresses the query by adding the following to my model: def validate_unique(self, *args, **kwargs): # Make sure that we never validate if ID is unique. Duplicates OK. current_exclude … -
Annotate count of related related filtered objects
I have these models: class Shop(..): category = ForeignKey... class Product(..): category = ForeignKey... is_active = BooleanField... class Category(..): name = ... I need to annotate the number of active products for each category. Basically this: for cat in Category.objects.all(): count = Product.objects.filter(shop__category=cat) I tried: Category.objects.annotate(product_count=Count('shop__products'),filter=Q(shop__products__is_active=True)) django.core.exceptions.FieldError: Related Field got invalid lookup: is_active This raises an error. Do you know how to annotate this? -
Convert SQL query in Django model format
I'm trying to convert an SQL query into django format but as I'm quite new to django I'm having some trouble. My query: select make_name, count(*) as count from main_app_make as make join main_app_model as model on make.id = model.make_id join main_app_vehicle as vehicle on model.id = vehicle.model_id group by make.make_name The result: Audi 1 Mercedes-Benz 2 My models: class Make(models.Model): make_name = models.CharField(max_length=50) make_logo = models.CharField(max_length=400) def __str__(self): return self.make_name class Model(models.Model): model_name = models.CharField(max_length=50) make = models.ForeignKey(Make, on_delete=models.CASCADE) def __str__(self): return self.model_name class Vehicle(models.Model): type = models.ForeignKey(VehicleType, on_delete=models.CASCADE) model = models.ForeignKey(Model, on_delete=models.CASCADE) body_type = models.ForeignKey(Body, on_delete=models.CASCADE) ... This is what I tried: options = Make.objects.all().values('make_name').annotate(total=Count('make_name')) -
Call not yet defined Model's manager in predefined Model Method Django
I have 2 models: class Person(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class Message(models.Model): sender = models.ForeignKey(Person, related_name='messages_sent', on_delete=models.CASCADE) recipient = models.ForeignKey(Person, related_name='messages_recieved', on_delete=models.CASCADE) text = models.TextField() def __str__(self): return self.text Notice Person was defined before Message. I can reference Message before it's definition in Person if I use a ForeignKey like so: class Person(models.Model): myfield = models.ForeignKey('message', on_delete=models.CASCADE) to call a not yet defined Model before definition. But what's the best way to call a not yet defined Model in a previously defined Model's method? Example: class Person(models.Model): name = models.CharField(max_length=150) myfield = models.ForeignKey('message', on_delete=models.CASCADE) # First reference before definition def __str__(self): return self.name def send_message(self, message, recipient): sent_message = Message.objects.create(sender=self, recipient=recipient, text=message) # Second reference before definition in a method somehow? return sent_message class Message(models.Model): sender = models.ForeignKey(Person, related_name='messages_sent', on_delete=models.CASCADE) recipient = models.ForeignKey(Person, related_name='messages_recieved', on_delete=models.CASCADE) text = models.TextField() def __str__(self): return self.text Is there a way to do this without defining the Person model below the Message model? If so, what'd be the best approach? Thanks in advance! -
Django authentication from mobile app using DRF API: how to?
I am neewbie in DRF. To resume, in one hand I have a Django web app with a Django authentication and a Django Rest API app layer. In the other hand, I have a Flutter mobile app. I would like users to be able to connect to mobile app using Django authentication and DRF API. below the start code for a very basic API, just to test the "concept" my first idea was to use a POST method even if I don't want to save record but just send data in Json format from mobile app to Django but as I could have expected I get an HTTP 400 Bad Request ("A user with that username already exists.") None of the APIView views match what I need so Should develop a simple API with pure Django? How should I do that? ***serializer.py*** class LoginSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password'] ***views.py*** class UserLogin(APIView): def post(self, request): serializer = LoginSerializer(data=request.data) if serializer.is_valid(): if get_object_or_404(User,username='admin'): pront('true') return True else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ***urls.py*** urlpatterns = [ path('user/', views.UserLogin.as_view(), name='user-login'), ] ``` -
xhtml2pdf not loading font's
Trying to load fonts with static. When rendering/loading page directly everything loads. But when loading as pdf it doesn't load the correct fonts! pdf.html (also yes I am loading static on pdf page. also yes link_callback is added as supposed.): @font-face { font-family: 'Mulish'; font-weight: 600; src: url("{% static 'fonts/Mulish-Regular.TTF' %}") } @font-face { font-family: 'Mulish'; font-weight: 700; src: url("{% static 'fonts/Mulish-Bold.TTF' %}") } html { font-family: 'Mulish' !important; } utils.py def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.CreatePDF(BytesIO(html.encode("UTF-8")), result, encoding='UTF-8', link_callback=link_callback) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None def link_callback(uri, rel): s_url = settings.STATIC_URL # Typically /static/ s_root = settings.STATIC_ROOT # Typically /home/userX/project_static/ m_url = settings.MEDIA_URL # Typically /static/media/ m_root = settings.MEDIA_ROOT # Typically /home/userX/project_static/media/ if uri.startswith(m_url): path = os.path.join(m_root, uri.replace(m_url, "")) elif uri.startswith(s_url): path = os.path.join(s_root, uri.replace(s_url, "")) else: return uri # handle absolute uri (ie: http://some.tld/foo.png) if not os.path.isfile(path): raise Exception( 'media URI must start with %s or %s' % (s_url, m_url) ) return path I know that adding a full URL path to src does WORK but it is not acceptable because I don't want to change path every single time I need to load something -
How to make and use custom template-loader in Django
I am trying to write a custom template loader in django which serves html templates which are present in a folder in my s3 bucket. Following is my custom_loader file from django.conf import settings from django.template import Origin, Engine from django.template.loader import TemplateDoesNotExist from django.template.loaders.base import Loader from boto3.session import Session from django.template import engines ACCESS_KEY_NAME = getattr(settings, 'AWS_ACCESS_KEY_ID', getattr(settings, 'AWS_ACCESS_KEY_ID', None)) SECRET_KEY_NAME = getattr(settings, 'AWS_SECRET_ACCESS_KEY', getattr(settings, 'AWS_SECRET_ACCESS_KEY', None)) TEMPLATE_BUCKET = getattr(settings, 'AWS_STORAGE_BUCKET_NAME') django_engine = engines['django'] template = django_engine.from_string("Hello {{ name }}!") class S3Engine(Engine): def __unicode__(self): return "s3_engine" def __str__(self): return "s3_engine" class Loader(Loader): is_usable = True def __unicode__(self): return "loader" def __init__(self, *args, **kwargs): django_engine = engines['django'] print(engines.all()) template = django_engine.from_string("Hello {{ name }}!") print(template) params = args[0] print(args) print('params', params) session = Session(aws_access_key_id=ACCESS_KEY_NAME, aws_secret_access_key=SECRET_KEY_NAME) s3 = session.resource('s3') self.bucket = s3.Bucket(TEMPLATE_BUCKET) super(Loader, self).__init__(*args, **kwargs) # self.engine = S3Engine(dirs=params['DIRS'], context_processors=options, loaders=Loader) def getKeys(self): keys_objects = [] for obj in self.bucket.objects.filter(Prefix="media/festive_html/"): key = obj.key keys_objects.append({ 'key': key, 'object': obj }) return keys_objects def get_contents(self, origin): print(111111) print('origin', origin) try: keys_objects = self.getKeys() for key_object in keys_objects: print('origin', origin) print('key_object', key_object) if key_object['key'] == origin: return key_object['object'].get()['Body'].read() except FileNotFoundError: raise TemplateDoesNotExist(origin) def get_template_sources(self, template_name, template_dirs=None): tried = [] # print('template_name', template_name) # … -
Append css while removing the previous css in multipage Django Dash application
I have implemented a multipage Dash Django application. I have two different apps and I want each app to have its own external css file. I tried to configure the css in each page app with app1.py cssStylesheets = ['app1.css', 'app1.bootstrap.css'] for stylesheet in cssStylesheets: app.css.append_css({ "external_url": '/static/' + stylesheet }) app2.py cssStylesheets2 = ['app2.css', 'app2.bootstrap.css'] for stylesheet in cssStylesheets2: app2.css.append_css({ "external_url": '/static/' + stylesheet }) I also tried to configure the external css based on the pathname input received dash_app.py @app.callback(Output('page-content', 'children'), [Input('url', 'pathname')]) def display_page(pathname): cssStylesheets = ['app1.css', 'app1.bootstrap.css'] cssStylesheets2 = ['app2.css', 'app2.bootstrap.css'] for stylesheet in external_stylesheets: app.css.append_css({ "external_url": '/static/' + stylesheet }) if pathname == '/app1/': for stylesheet in cssStylesheets: app.css.append_css({ "external_url": '/static/' + stylesheet }) return app1.layout elif pathname == '/app2/': # for stylesheet in cssStylesheets: # app.css.append_css({ # "external_url": '/static/' + stylesheet # }) return app2.layout But the problem is that for the first time that it loads the page it gets the previous css (ex. Loading /app1 --> No css, Refresh app1 --> app1.css, Loading /app2 --> app1.css, Refresh app2--> app2.css) -
django testcase with --keepdb is not resetting object ids between tests
Recently I updated my django app, which was made with Python 2.7 and Django 1.11, to Python 3 and Django 3.1. I had several testcases using django.test.TestCase. Several of these tests were made assuming the database would be completely reset between test executions and, among other things, it was expected that the last id for the models would be reset as well, such as that if I create an object on a test and save it to the database, the object would always receive the same id starting from 1. This behaved exactly like this on Django 1.11, and I was able to use the --keepdb flag to avoid recreating the database everytime. However after I upgraded to Python 3 and Django 3.1 I noticed this is no longer the case. I noticed that all objects are deleted from the database after the test execution, but on next test executions the new objects are created with pk starting from the last used pk, so I can no longer count with the fact that the created objects will have a predictable pk. This leads to a really annoying behavior that if I run my test just after recreating the db the … -
Django and AJAX - replaceWith not replacing my element, it is adding it and not removing the original
I am doing an AJAX call on my django application to update data on the page without refreshing. When I submit the AJAX request and use replaceWith() the element I am trying to replace is getting added to the page, but not replacing the original. Simplified code: page.html <table> {% for form in formset %} <tr> <td>{{form.evidence}}</td> {% include 'detail.html' %} </tr> {% endfor %} </table> detail.html {% if obj %} {% if updated %} <td id='{{obj.id}}-detail' colspan=2>Updated</td> {% else %} <td id='{{obj.id}}-detail'>not updated</td> {% include 'save_container.html' %} {% endif %} {% else %} {% include 'save_container.html' %} {% endif %} save_container.html <div class='btn-group mr-1 mb-1'> <button id='{{ form.instance.id }}-save-button' action="{% url 'results:save_class' %}" type='button' class="btn btn-warning save-classification">Save</button> </div> views.py def save_class(request): data = dict() if request.method == 'POST' and request.is_ajax(): obj = Table.objects.get(id=request.POST['id']) form = Form(data=request.POST, instance=obj, saved=True) if form.is_valid(): ... save form to table ... data['form_is_valid'] = True obj = VariantClassification.objects.get(id=obj.id) data['html_detail'] = render_to_string( 'details.html', {'obj': obj, 'updated': True }) else: data['form_is_valid'] = False data['form_errors'] = form.errors.values() return JsonResponse(data) save.js $(function () { $(".save-classification").click(function () { var id = $(this).attr('id').replace('-save-button',''); var url = $(this).attr('action'); var var_n = $(this) var evidence = $(this).closest("tr").find("td." + id + '-evidence-cell').find("li.evidence-cohort-li").find("input.textinput").val(); // some … -
Uploading Files through django rest api
Question 1: I want the user to be able to upload files through the Api, I am using postman to test the api, here is my code: views.py: class FileUploadView(APIView): parser_classes= (MultiPartParser, FormParser) permission_classes = [permissions,] def post(self, request, *args, **kwargs): file_serializer = SLRSerializer(data= request.data) if(file_serializer.is_valid()): file_serializer.user = request.user return Response(file_serializer.data, status= status.HTTP_401_UNAUTHORIZED) else: return Response(file_serializer.errors, status= status.HTTP_400_BAD_REQUEST) models.py class SLRModel(models.Model): user = models.ForeignKey(AUTH_USER_MODEL, on_delete= models.CASCADE, null= True) user_folder = models.FileField(upload_to= /path/to/folder, null= True) whenever I try to upload something through the api using postman, I dont get an error, but I get the following on postman: { "user_folder": null, "user": null } even though I am logged in, and have uploaded a file. Question 2: When I login into the admin dashboard, and then try to access the models from there. I get the following error message Error Message: OperationalError at /admin/App/model/ no such column: App_model.user_id Request Method: GET Request URL: http://localhost:8000/admin/App/model/ Django Version: 3.1 Exception Type: OperationalError Exception Value: no such column: App_model.user_id Thanks. -
Django and Vue - Vue variable in Django Tag
On a Django-Html Template I need to render this line of code: <form action="{% url 'meal:submit_comment_rating' meal_id=meal.id comment_id=[[ comment.comment_id ]] %}" method="post"> Inside of a Vue for-loop: <div v-for="comment in comments" id="comment_[[ comment.pk ]]"> ... </div> Where [[ comment.comment_id ]] is replaced with the corresponding Vue variable: meal_comments_sort = new Vue({ delimiters: ['[[', ']]'], el: '#meal_comments_section', data: { comments: [ { "meal_id":1, "user_id":1, "username":"admin", "comment_id":1, "comment_type":"mealcomment", "date":"2020-09-01T14:18:24.563Z", "content":"time for comment", "rating":-1 }, ], }, }); As-is I receive the Django error Could not parse the remainder: '[[' from '[[' which I expected, but cannot find a work-around for. What is the best way to do this? I have tried wrapping the [[ comment.comment_id ]] variable in {% verbatim %} tags, but it does not help (probably because that's not how those tags are supposed to be used). -
How to add common fields in django models?
I am preparing db schema using django for an application school management system. A little confusion happened while making the relationship between three tables i.e. User, Staff and Student. User table stores primary user fields such as first_name, last_name, email etc. Staff fields stores staff qualification, department, designation etc and a foreign key of User to store the primary details of the staff. And Student also has Foreign key with User to store its primary info and rest other student related fields such as registration details, guardian details etc. To add contact details of Student and Staff, I came up with below approach of storing a contact field in both the tables: models.py # from 'common', A separate django application to store common database tables such as Contact, User, Language, Timezone, etc. from django.contrib.auth.models import User, Group class Contact(models.Model): address = models.TextField(_("Permanent Address"), blank=True, null=True) landmark = models.CharField(_("Landmark"), blank=True, max_length=80) city = models.CharField(_("City/Town"), blank=True, max_length=80) ... models.py # From 'students', separate django application to handle student details such as student admissions, and corresponding other tables. class Student (models.Model): reg_number = models.CharField(_("Reg. Num"), max_length=20) member = models.OneToOneField(User, verbose_name=_("Student"), related_name="students", on_delete=models.CASCADE) contact = models.ForeignKey(Contact, on_delete=models.CASCADE, ...) ... models.py # from 'staff', separate … -
Django date with event
I've got model: class LinkShortener(models.Model): long_url = models.URLField('Long URL', max_length=2000, blank=False) usage_count = models.PositiveIntegerField(default=0) I've got function in view: @login_required(login_url='/accounts/login/') def redirection(request, token=None): # noqa: D103 #zmienionno z Home na home if not token or token is None: return redirect('shortener:generate') else: try: check = LinkShortener.objects.get(shortcut=token) if check.active: check.usage_count = check.usage_count + 1 else: check.usage_count_inactive = check.usage_count_inactive + 1 check.save() url_to_redirect = check.long_url if check.active: return redirect(url_to_redirect) else: return redirect('shortener:generate') except LinkShortener.DoesNotExist: return redirect('shortener:generate') So every time when URL adress (LinkShortener object) is clicked, usage_count increments by 1. Does Django saves somewhere date of such action/click or i have to create some field in my LinkShorener model where dates of every click will be added ? Is there any query command that can give me date of such click ? -
How to render a 3D object to HTML file by using pythonOCC in Django?
I have a Django application and I'm using pythonOCC package in it. I have to display the 3D .stl, .stp, .igs files in my template. Normally, when I call the render() function, the following outputs appear on my vscode console and since flask app created by pythonocc instead of django starts running in localhost, my index.html is never rendered. However I need to display the files in a Django template. That's why I have extended the X3DomRenderer Class such as below. My custom X3DomRenderer class: class CustomX3DomRenderer(x3dom_renderer.X3DomRenderer): def render_to_string(self): self.generate_html_file(self._axes_plane, self._axes_plane_zoom_factor) return open(self._html_filename, 'r').read() the HTML codes that returned from render_to_string() function: <html lang="en"> <head> <title>pythonOCC 7.4.0 x3dom renderer</title> <meta name='Author' content='Thomas Paviot - tpaviot@gmail.com'> <meta name='Keywords' content='WebGl,pythonOCC'> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="https://x3dom.org/release/x3dom.css"> <script src="https://x3dom.org/release/x3dom.js"></script> <style> body { background: linear-gradient(#ced7de, #808080); margin: 0px; overflow: hidden; } #pythonocc_rocks { padding: 5px; position: absolute; left: 1%; bottom: 2%; height: 38px; width: 280px; border-radius: 5px; border: 2px solid #f7941e; opacity: 0.7; font-family: Arial; background-color: #414042; color: #ffffff; font-size: 14px; opacity: 0.5; } #commands { padding: 5px; position: absolute; right: 1%; top: 2%; height: 65px; width: 180px; border-radius: 5px; border: 2px solid #f7941e; opacity: 0.7; font-family: Arial; background-color: #414042; color: #ffffff; font-size: 14px; … -
Django annotate Avg of foreign model
Two models, article and review, relationship is one to many (one article has many reviews). Some articles don't have any review. I want to order articles by review ratings, therefore I use the annotate with AVG: ArticleQueryset.annotate(rating=models.Avg('reviews__rating')).order_by('-rating') The issue is that the articles without reviews the rating value is False and somehow that comes before the maximum rating. The result is that the first results don't have any rating, then the highest rated articles show up. -
django uploading multiple images with one submit button
I'm new to django I want to upload multiple pictures by clicking one submit button I've saw people using formsets but it is limiting the number by using extra = # but I don't want to limit the number and some people are using filefield but I want people to only upload images. Is there a way to upload multiple picture by clicking one submit button without limiting the number of image files and only allowing image file? -
Django Rest Framework Filter not Working, The filter button is not showing on browsable API
Good day I am new with django and django rest framework. I am trying to do some filtering. I followed the steps on the docs https://www.django-rest-framework.org/api-guide/filtering/ but nothing is working, it doesnt even show the filter button on browsable api. hope someone can help. thank you -
How can I store non exist value of multiselect field into database in Django?
I am working on a project and I have a problem like whenever I create a tag that is not exist in my Tag table which is mapped to as foreign key in this form, It shows me like tag not exist validation error I tried to store it in forms.py file. ''' def save(self, commit=True): tags = self.cleaned_data['tag'] for tag in tags: if tag not in Tag.objects.values('title'): obj=Tag(title = tag) obj.save() instance = super().save() if commit: instance.save() return instance ''' I have used select2 jquery for crating dynamic tag.how can i add dynamic tag to database called Tag -
Apscheduler runs with Django but not running with gunnicorn
I am setting my scheduler using apscheduler inside a file called Scheduler.py - def start_scheduler(): scheduler = BackgroundScheduler() scheduler.add_job(xyz_job, trigger='cron', hour=21, minute=0) scheduler.start() Now inside my apps.py - from. Scheduler import start_scheduler class AppNameConfig(AppConfig): name = 'appname' start_scheduler() Then from cmd I use - python manage.py runserver My scheduler works fine and everyday at 9pm, scheduler started working in background. P.S. - This was an API with entry and end points. I tested it using postman. I was getting the output correctly. Now on my linux server, I am doing the same thing, but instead of using django, I am using gunicorn to expose my api. I am using the command - gunicorn -b server_ip:port project.wsgi --workers=2 --daemon Using the above gunicorn command, my api is still working fine and I am getting the output but my scheduler isn't working. Can anyone give some insight on what can be the possible solution for this? -
Is it possible to load django admin inlines dynamically?
i.e, load the inlines only when clicked on it. If possible, how can this be achieved. I have gone through various answers but could not find what I was looking for. -
Django model, how to allowing only two booleanfield to be True
How to allow that only 2 objects can be true? class Book(models.Model): is_active = models.BooleanField( default=False, verbose_name='is active' ) def save(self, **kwargs): if self.is_active: Book.objects.exclude(pk=self.pk).filter(is_active=True).\ update(is_active=False) super().save(**kwargs) -
Capture an arbitrary number of values from url
I created a url pattern in Django which captures a category in the url and passes it in the view. For example the url mysite.com/category/shoes/ matches the path: path('category/<category>/', views.Feed.as_view(), name='feed'), And it will pass to the view a variable called category with the value "shoes". Now I want also to capture subcategories. Categories and subcategories will be organized as a tree structure, and a subcategory may have more subcategories within it. How could I write a url path pattern which captures an arbitrary number of nested subcategories, for example: mysite.com/category/shoes/winter/leather/... and how would this be passed to the view?