Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
{% with %} tag to store 'in' expression value in django template
I'm trying to store a boolean value in a variable within the {% with %} tag of Django. But its not working. is there any other way around to do this ? Can I create a custom filter for it or is there any pre-built filter for this? {% with isEnrolled=course in all_courses %} ..... {% endwith %} -
Append <tr> to HTML table progressively with a JQuery AJAX call (Django framework)
I am new to Javascript, Jquery and Ajax request and I have an issue with the execution of my scripts. Basically I have a very long list to display on my home page (1200+ items). I used to load the page normally but since my list would take a long time to load (and since it's right in the middle of the page) there would be an enormous delay before all my HTML elements would show. For example my footer would be the last item to load and it would appear almost a full second after my navbar. I decided to use AJAX requests to load my HTML first, get my navbar and my footer done and only then fetch my list to show it in the middle of my page. The first problem I encounter is that while my script is being processed, nothing appears. This means that even if my first list item's "tr" is ready, it will only show when the 1200th's "tr" is also ready. I would need the table to be populated progressively. I can see my "tr"s being generated in my console but they are only applied in my HTML after they are all … -
Append an item to a streamfield in wagtail
I have a streamfield which is working, and has data in, the code I wrote to do this looks something like: class NewYearBlock(blocks.StructBlock): year = blocks.IntegerBlock(verbose_name="Year (the year this data is rolling into)") holidayRollover = blocks.FloatBlock(verbose_name="How many hours are rolling over") overtimeRollover = blocks.FloatBlock(verbose_name="How many hours are rolling over") class Meta: icon = 'user' and newyearStream = StreamField([ ('newyear', NewYearBlock()), ], blank=True) What I would like to do is to append an item to this streamfield via some code, I know how to replace the item with the below (which works) employeeModel.newyearStream = newyearStream employeeModel.save() But this replaces what already exists. I was then thinking I could loop over the existing stream, and then create a new object to save, but when I try to do that I receive TypeError: cannot unpack non-iterable StreamChild object so I looked at the type, and see it is <class 'wagtail.core.blocks.stream_block.StreamValue'> Can anyone help point me in the right direction to either loop through the stream and get my results out, or a better way to append to my streamField. Thanks for your time helping, Dan -
How to print Django queryset in Tabular form in python3 manage.py shell
Is there a way or package to print Django queryset in Tabular form in python3 manage.py shell The queryset prints like this: But I want it to be printed like this -
Django auto_now count results in a certain date
I want filter of all request done is done in a certain date class Log(models.Model): request = models.CharField(max_length=255) created_at = models.DateField(default=now, blank=True) def __str__(self): return self.request But I don't how to do it correctly compare both the created_at and the date today quantity_of_requests = Log.objects.filter(created_at=now()).count() -
How to serve a rendered JPEG image with Django Rest Framework?
On a call to my Django API, I'm trying to generate an image with matplotlib and then serve this image back to the client using Django Rest Framework. I'm aware of Serve images with django-rest-framework and Return image using Django REST framework Render, but they can't quite get me there. I think I'm supposed to create a sort of CustomRenderer, then pass the result to the view. I'm unclear about how such a view.py should look. What would be really ideal would be to be able to generate the image in memory, and then serve this without having to save it as a physical file on my server. So I have the image renderer, render.py in my app's directory: # app/render.py from rest_framework import renderers from matplotlib import pyplot as plt class JPEGRenderer(renderers.BaseRenderer): media_type = 'image/jpeg' format = 'jpg' charset = None render_style = 'binary' def render(self, data, media_type=None, renderer_context=None): # data coming in would be a numpy array # Matplotlib can create the image from the numpy data array. # It would be cool to generate and return this as a Bytes IO object # to avoid persisting the file on my server as pass this to the view, … -
override save() and query_set() django admin
I'm searching for a way to customize the Django Admin to support permissions and data based on the user group. For example, I've just created the Developers1, Developers2 groups.. now I've also created the Transaction model, with AdminModel to specify how to list data. what im trying to do is i want each group to only access its own Transaction model, and each group can only add, delete, update and view their own Transactions (eg developers1 group cant access developers2 Transactions and vice versa) in the admin.py i've override the save() method as below.but im not sure how to make the filter to save data for each group @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): search_fields = ['chp_reference','familymember__name'] inlines = [FamilyGroupInline,FamilyMemberInline] def save_model(self, request, obj, form, change): obj.user = request.user.groups.filter() print(obj.user) super().save_model(request, obj, form, change) and after i make a queryset() as below def get_queryset(self, request): qs = super().get_queryset(request) print(qs.values('group__name')) if request.user.is_superuser: return qs return qs.filter(group__in=request.user.groups.all()) -
IndentationError: unindent does not match any outer indentation level in json.loads(request.body)
Im stuck at this error code, IndentationError: unindent does not match any outer indentation level and its located in my data = json.loads(request.body) . Can someone help me to find the error. I already search lot of google page about this error but its seems different with my problem, thx. from django.shortcuts import render from django.http import JsonResponse from django.http import HttpRequest import datetime import json def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('productId:', productId) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create( customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create( order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + 1) elif action == 'remove': orderItem.quantity = (orderItem.quantity - 1) orderItem.save() if orderItem.quantity <= 0: orderItem.delete() return JsonResponse('Item was added', safe=False) def processOrder(request): transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) total = float(data['form']['total']) order.transaction_id = transaction_id else: print('User is not logged in') return JsonResponse('Payment complete!', safe=False) -
Minify All Static Files Without Changing Their Names Django-Pipeline
I'm using Django Pipeline as a drop in minifier for my static files. What I would like to happen is that when I run collectstatic that the django-pipeline would minify the file and output it with the same filename in the output folder. e.g. static_input/myfile.js #50kb -> collectstatic -> static_output/myfile.js #25kb Looking through the docs, it only seems possible to output multiple files to one file e.g. PIPELINE = { 'PIPELINE_ENABLED': True, 'JAVASCRIPT': { 'stats': { 'source_filenames': ( 'js/jquery.js', 'js/d3.js', 'js/collections/*.js', 'js/application.js', ), 'output_filename': 'js/stats.js', } } } Is there a way to make django-pipeline simply minify my static files without trying to merge and rename them? -
Django CSRF_COOKIE_DOMAIN on Heroku
So we deployed Django app to Heroku and everything was working well. Until I looked at cookies. I have csrftoken cookies for both app-staging.herokuapp.com and .app-staging.herokuapp.com. But when I set CSRF_COOKIE_DOMAIN = 'app-staging.herokuapp.com' I automatically get the wrong thing .app-staging.herokuapp.com. I tried everything I could but nothing helped. I tried current Firefox (83.0) and Chromium. The biggest problem is invalid check for CSRF token. Since domains don't match it's invalid. csrftoken=E9sdyx5U61IaFP3YNJHk3ZKtnllkEnyZ6i9eimHYD31sn4qXRXv7FBDOpPfpWhyt; Domain=app-staging.herokuapp.com; expires=Fri, 19 Nov 2021 15:33:52 GMT; Max-Age=31449600; Path=/; SameSite=Lax; Secure Please don't suggest that I set CSRF_COOKIE_DOMAIN = None. In case one Django instance would run on more domains I would need to solve the same problem. Which we will have to do soon. -
Do we have Manage.py Task in VS code
I used to work with Pycharm But now i use VS Code for coding Django, so Does anyone know Do we have Manage.py Task in VS code or Do I have a way to make this Task? i use it Many times like when i call runserver or migrate i Take Screenshot from it in pycharm it is located below -> pycharm Manage.py Task I just need a button that opens Terminal (CMD) + 'Python Manage.py ...' when I click on it And do not need to Write 'Python Manage.py' several time. -
Django formview form_valid, form has no attribute `instance`
I'm trying to create a form view using the FormView class. It works fine displaying the post form but when posting the data form_valid function is called and here I get an error: AttributeError: 'GameForm' object has no attribute 'instance' As I can understand the form object passed in the form_valid method doesn't contain an instance but examples show that it is possible.. What am i missing? views.py from django.shortcuts import render, redirect from django.views.generic import (ListView, DetailView) from django.views.generic.edit import FormView from .models import Game from .forms import GameForm # ... Other views class GameCreateView(FormView): template_name = 'games/game_form.html' form_class = GameForm success_url = '/' def form_valid(self, form): # This method is called when valid form data has been POSTed. # It should return an HttpResponse. form.instance.author = self.request.user return super().form_valid(form) Website log AttributeError at /game/new/ 'GameForm' object has no attribute 'instance' Request Method: POST Request URL: http://127.0.0.1:8000/game/new/ Django Version: 3.1.3 Exception Type: AttributeError Exception Value: 'GameForm' object has no attribute 'instance' Django version = 3.1.3 Thanks in advance! -
How run makemigrations <app> --empty with Django and Docker?
I have a Django app with Docker and Docker-compose. So I can build, up or down my container but how can I run manage.py or django-admin command like makemigrationn <app> --empty ? In a "classical" Django project architecture, no problem But using Docker, I have an error django.core.exceptions.ImproperlyConfigured: Requested setting STATIC_URL, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I try django-admin makemigrations myapp --empty --settings=core.settings.dev but have another error no module core found -
Can I create a script, "Virtual Environment" and run it in crontab?
They help me, they know I need to run a script to start the services, I use Django with Python and ubuntu server. I have been seeing many examples in crontab, which I will use, every time I restart the server, I run the Script, which contains the command to run the virtual environment and in addition to the command "python3 manage.py runserver_plus", apart was to see restart the server all nights, I was also successful with crontab, but I can't execute what the script contains. They can help me, I am not very expert, but I managed to do something. Is it the path of the script? Tried running the command directly, got no results. -
How to not show pre selected form data in django form
i have form that give list of subject name with multiple choice but when student select one of those choice then i want next time next time they again come to choice they will not see pre selected data. how can have that in django form? what would be the approach to have that solution? much appreciate for your help. thank you so much. models.py class Registration_Course(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) course = models.ManyToManyField(Student_Course_Name, blank=True) def __str__(self): return str(self.user) views.py class Course_Registration(generic.CreateView): model = Registration_Course template_name = 'test/reg.html' form_class = RegForm def form_valid(self, form): form.instance.user = self.request.user form.save() return HttpResponse("saved form") forms.py class RegForm(forms.ModelForm): answer = forms.ModelChoiceField( queryset=Answer.objects.none(), widget=forms.RadioSelect(), required=True, empty_label=None) class Meta: model = Registration_Course fields = ['course', 'student'] widgets = { 'course': forms.CheckboxSelectMultiple } -
Unique=True message need to show in the vuejs template
I am developing the VueJs app using Django rest framework, In the question model, For the content field I added the unique = true because I want the content to be different. In the api it is validating the field. class Question(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) content = models.CharField(max_length=240, unique=True) slug = models.SlugField(max_length=255, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="questions") Now I want that error message in the vuejs template after the field . What I need to change in the script of the vuejs. <template> <v-container> <h1 class="mb-3">Ask a Question</h1> <v-form @submit.prevent="onSubmit" ref="form" v-model="valid" lazy-validation> <v-textarea v-model="question_body" placeholder="What do you want to ask?" rows="3" :counter= "240" :rules= "textarearules" auto-grow outlined row-height="25" shaped ></v-textarea> <v-btn type="submit" :disabled="!valid" color="primary white--text text-center" class="mr-4 mb-3" @click="validate" rounded>Publish</v-btn> </v-form> <div v-for="question in questions" :key="question.pk"> <h1>{{ question.content }}</h1> </div> <p v-if="error" class="muted mt-2">{{ error }}</p> </v-container> </template> <script> import { apiService } from "@/common/api.service.js"; export default { name: "QuestionEditor", props: { slug: { type: String, required: false } }, data() { return { questions: [], question_body: null, error: null, valid: true, textarearules: [ v => !!v || 'Answer is required', v => (v && v.length <= 240) || 'Answer must be less than 240 … -
Sudden 502 messages on Gunicorn
My server has been working great for about 18 months. My setup is Nginx, Gunicorn, Django on a Ubuntu server. I will share this next piece of information just for the sake of full disclosure. One of my hard drives died on this same server. It's not the hard drive with any of the data that I'm referring to, but this hard disk did end up getting a new uuid. I feel compelled to share this information because this was when I started having trouble. Could be coincidence, could be related, I dunno. This was last Friday and I've been struggling with it ever since. I get a 502 error. When I drill down a little bit that shows up as a Gunicorn error. I'll attach all of the information that I can think of below about my setup. But what gets me is that I can start Gunicorn from the command line, but not from the computer boot. This works from the command line, which tells me that I have something right: sudo service gunicorn stop sudo /media/Storage/sales_portal/venv/bin/gunicorn --chdir=/media/Storage/sales_portal --timeout 600 --access-logfile /var/log/gunicorn/access.log --error-logfile /var/log/gunicorn/error.log --log-level debug --workers 3 --bind unix:/run/gunicorn.sock sales_portal.wsgi:application My gunicorn.service file is: [Unit] Description=gunicorn daemon … -
Custom Django SlugField Validation and Breaks URL Matching
I wrote a custom field validator for slugs in my URLs (accepting periods in slugs for one model, SLUG_REGEX = '[-a-zA-Z0-9_.]+$'): def validate_my_slug(value): my_slug_re = re.compile(settings.SLUG_REGEX) if not my_slug_re.match(value): raise ValidationError( _('Slugs must consist of letters, numbers, ' 'underscores, hyphens, or periods.'), params={'value': value}, ) The field in models.py: slug = models.CharField(max_length=64, null=True, blank=True, validators=[validate_my_slug]) This works when saving models in Django admin. But then in my URLConf, this no longer works (it did work before changing the slug validation): path('product/<slug:slug>', ProductDetail.as_view(), name='product-detail') I found a solution using re_path, but I'm not sure it's the right/best way to do it: re_path('product/(?P<slug>[-a-zA-Z0-9_.]+)$', ProductDetail.as_view(), name='product-detail') Now this no longer works (comes before the re_path pattern above in urls.py): path('products', ProductList.as_view(), name='product-list') -
Django + AJAX Post method url 404 not found
Good afternoon, I am working on a simple like button in a Django Post class. I am using an Ajax get method but can't reach the like view and get a 404 error. Can anyone help, please? urls.py: urlpatterns = [ path('', views.home, name="wall-home"), path('like/', views.like, name="like") views: def like(request): if request.method == 'POST': user = request.user slug = request.POST.get('slug', None) post = get_object_or_404(Post, slug=slug) if post.likes.filter(id=user.id).exists(): post.likes.remove(user) else: post.likes.add(user) ctx = {'message': "success"} return HttpResponse(json.dumps(ctx), content_type='application/json') Ajax: <script> $('#likebutton').click(function(){ $.ajax({ type: "POST", url: "{% url 'like' %}", data: {'slug': $(this).attr('slug'), 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", // handle a successful response success: function(response) { alert(response.message); alert('Success'); }, error: function(rs, e) { alert(rs.responseText); } }); }) -
Create a confirmation message from model in Django
I have an app in Django that has multiple models. I have a particular model like this: models.py class MyModel(models.Model): model_id= models.AutoField(primary_key=True) model_date = models.DateTimeField(verbose_name="Label 1") model_counter = models.IntegerField(blank=True, null=True) What I need is that the user confirm that he wants to save the model, even if the date is greater than today, in doing so the user can create a model that can be wrong for other users, but sometime it's correct that the date is greater than today. I cannot use a custom HTML form, only the default one. The user must interact someway with the page, and give direct aknowledgement that he knows that is saving a new model that can be dangerous for other users. The user must be able to abort the saving or modify the date. So I tried to use another field of the model to store the counter: def clean(self): condition = False if self.model_counter is None: condition = True else: condition = self.model_counter == 1 if condition : self.model_counter = 1 raise ValidationError("Attention, the date inserted is after the current date, click the SAVE button another time to proceed with the saving") As a counter I use another field of the … -
Bootstrap modal pop up breaks when i send "schemaname.tablename" into id field using Django Jinjna template
Below is my html script when I am sending a schema_name.table_name to the 'id' attribute of my modal and pop up modal is not displayed and the popup modal breaks, but work well as mentioned in the below note note: when I only send table_name pop up is displayed but i need to send schema_name as well please help <input type="checkbox" id='dbo.segment_customer_hash_mapping_history' name="acs[]" value="dbo.segment_customer_hash_mapping_history"> dbo.segment_customer_hash_mapping_history <!-- <form action="/dwdatacatlog2/" method="GET">--> <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModaldbo.segment_customer_hash_mapping_history">Add filter <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-plus-circle" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/> <path fill-rule="evenodd" d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z"/> </svg> </button> <!-- <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Small Modal</button>--> <!-- Modal --> <div class="modal fade" id="myModaldbo.segment_customer_hash_mapping_history" role="dialog"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <h4>Add Filters</h4> <!-- <h4 class="modal-title">Modal Header</h4>--> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <p><small>Table name</small></p> <p>dbo.segment_customer_hash_mapping_history</p> <p> <select id="columnname" name="columnname" class="form-control" onchange="changecat(this);"> <!-- onchange="populatefilter()"--> <option value="int////audit_id"> audit_id<small>(int)</small></option> <option value="int////segment_id"> segment_id<small>(int)</small></option> … -
Django CKEditor clean files unattached to rich text fields
I am writing an image cleanup management command for my Django project. The principle of how this works is: get all references to files attached to object ImageFields like so: all_models = apps.get_models() for model in all_models: file_fields = [] filters = Q() for f_ in model._meta.fields: if isinstance(f_, FileField): file_fields.append(f_.name) is_null = {'{}__isnull'.format(f_.name): True} is_empty = {'{}__exact'.format(f_.name): ''} filters &= Q(**is_null) | Q(**is_empty) # Only retrieve the models which have non-empty, non-null file fields if file_fields: for file_field in file_fields: files = model.objects.exclude(filters).values_list(file_field, flat=True).distinct() db_files.update(files) get a list of stored image files delete all stored files not attached to an object ImageField This all works fine. But, I can't apply (1) to images that are embedded in objects using the CKEditor RichTextUploaderField. Any idea how I can get a list of those images to complete my cleanup? -
List of products
I have to complete a project this semester where I have to retrieve a list of products according to the user's search and make a report for selected items by the user. I searched a bit but is there any free API that provides a good amount of product data with some basic info. Reaching out to expert developers kindly help me -
Use query expression F() as input to a regular function in django
Suppose I have a model like this: class Order(models.Model): error_code = CharField(max_length=10, blank=True, null=True) I wish to create an annotated queryset where I will group all orders by error_code and count how many of each I have. Something like this: report = (Order.objects .values('error_code') .annotate(count=Count('id')) ) Also, I would like to look for descriptive messages for each possible error_code, which I have hard-coded on my code in a dict: messages = dict( '000'='Processing failure', '001'='Rejected credit card', '002'='Invalid credit card number', ... etc ) I would like to annotate the original queryset with a new value called message where I would get the error_code and check the messages dictionary. Something like this: report = (Order.objects .values('error_code') .annotate(count=Count('id')) .annotate( message=Value( messages.get(F('error_code')), CharField(), ) ) ) What I expected with the above code was to obtain the value of error_code on the query and pass it as a string to the messages.get() method. However F('error_code') doesn't return a str value; it returns a F expression object. Can I use expressions return values as input to regular Python methods? Is there any other way I could achieve what I explained above? I know I would be able to do this error_code to message … -
What is the best practice to update an html page on django using django-channels?
Django-channels is running with docker and redis. Everything is working fine. PROVA_CHANNEL.HTML {% extends 'base.html' %} {% block content %} <div id="refresh-this-div"> {% include 'prova_ordini_in_channel.html' %} </div> <script language="javascript"> var ws_url = 'ws://' + window.location.host + '/ws/ticks/'; var ticksSocket = new WebSocket(ws_url); console.log(ws_url); ticksSocket.onmessage = function(event) { var data = JSON.parse(event.data); console.log('data', data); // do whatever required with received data ... }; </script> {% endblock content %} When i run this function from the command center, the webpage prints out, in java console: { 'Nuovi ticks' : 12 } Django-channels is working! ''' from django.core.management.base import BaseCommand import json from asgiref.sync import async_to_sync import channels.layers from django.conf import settings class Command(BaseCommand): help = 'Displays current time' def handle(self, *args, **kwargs): ticks = {'Nuovi ticks': 12} channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)( settings.TICKS_GROUP_NAME, { "type": 'new_ticks', "content": json.dumps(ticks), }) ''' The question is: If i want to refresh variables that i'm passing from the view ('context['ordini']') i'm obligated to call the view with AJAX, or there is another way to refresh the page?? 'FUNCTION IN VIEW.PY' ''' def prova_ticks(request): context = {} ordini = Ordine_delivery.objects.filter(stato_ordine='processing') context['ordini'] = ordini return render(request, 'prova_channel.html',context) '''