Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin - Allow inline entires once selected item
I am trying to populate a dropdown in the Django admin panel based on a selected item. I have a customer model class Customer(BaseModel): name = models.CharField(max_length=128) company = models.ForeignKey("Company", models.PROTECT) def __str__(self) -> str: return f"{self.name}" def save(self, **kwargs): return super().save(**kwargs) An invite model class Invite(BaseModel): full_name = models.CharField(max_length=128, blank=True) email = WIEmailField(unique=True) customer = models.ForeignKey( to="Customer", on_delete=models.PROTECT, related_name="invites", ) Customer Invite model that defines the invite and customer class CustomerLocationInvite(BaseModel): location = models.ForeignKey( to=Location ) invite = models.ForeignKey( to=Invite, blank=True, ) Inline for invite class CustomerInviteInline(admin.TabularInline): model = CustomerLocationInvite fields = ("invite", "location", "created_at", "modified_at") readonly_fields = ("created_at", "modified_at") extra = 0 When creating a new Invite, Is it possible to: Display the inline once a company has been selected? When selecting a location from the inline, Filter out the locations based on the company they selected? -
Python zipfile.ZipFile zips a corrupt file
I have a Django view which users can call to zip files at my local server. It uses zipfile.ZipFile to compresses multiple files into a single zip as follows: with ZipFile(env_dir + 'folder.zip', 'w') as zipObj: zipObj.write(dir + '1.json') zipObj.write(dir + '2.json') Then I return this file to the user in response: folder_file = open(full_path, "r", encoding='Cp437') response = HttpResponse(FileWrapper(folder_file), content_type='application/zip') But the downloaded file is corrupt, I can't open it using ubuntu archive manager. Then when i try to unzip the file using python with the same package in my django server, I still get the error: with ZipFile(file_path, 'r') as zip_ref: zip_ref.extractall(dir) The error I get is: File ".../views.py", line 38, in post with ZipFile(file_path, 'r') as zip_ref: File "/usr/lib/python3.8/zipfile.py", line 1269, in __init__ self._RealGetContents() File "/usr/lib/python3.8/zipfile.py", line 1354, in _RealGetContents fp.seek(self.start_dir, 0) OSError: [Errno 22] Invalid argument Any idea what am I doing wrong here? -
Django ignore TemplateSyntaxError. Vue Syntax
I'm building a pwa on top of django. In the pwa.html I use valid vue syntax: {{ counter() }} or {{ el| removehtml() | truncate(40) }} Works flawless in a non Django project. I get an TemplateSyntaxError on runserver, how can I ignore this, cause this is valid for vue syntax. -
Modify how a field displays on Django tables2 table
I am trying to take a date field and display it in a django tables2 table. The issue is my field uses Djangos DateTimeField and has the time added on to the end which I don't care to display. My initial thought was to use a property decorator, and reference that in my table rather than using my original date field. But when I try to use split inside my property function nothing gets displayed in my table. If I modify the function to just print a string without using split it seems to work as intended. It seems that I can't use split anywhere in the function, even if I return a hard coded string instead of whatever I am splitting. Using split within the function just breaks it and makes it display nothing. Why can I not use split inside my function, and is there an alternative or better way of modifying what the date looks like when it displays on my table? #tables.py class ReportTable(tables.Table): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: attrs = {"class": "mytable"} model = models.Report fields = ("formatted_date") #models.py class Report(models.Model): id = models.AutoField(db_column="RootCauseID", primary_key=True) date = models.DateTimeField(db_column="date", blank=False, null=True) @property def … -
how fix Django error column accounts_sitename.languageCode does not exist
i create models.py in accounts for the siteName model but i dont know how to fix error it. how fix Django error column accounts_sitename.languageCode does not exist ProgrammingError at /ar/admin/accounts/sitename/ column accounts_sitename.languageCode does not exist LINE 1: ...tename"."user_id", "accounts_sitename"."site_id", "accounts_... ^ class siteName(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) site = models.ForeignKey(Site, on_delete=models.CASCADE) languageCode = models.CharField( max_length=10, choices=LANGUAGES,unique=True ) nameHome = models.CharField(max_length=111, blank=True) imageHome = models.ImageField( upload_to='site/' ) bioHome = models.TextField(max_length=5500, blank=True) nameVideo = models.CharField(max_length=111, blank=True) imageVideo = models.ImageField( upload_to='site/' ) bioVideo = models.TextField(max_length=5500, blank=True) nameForum = models.CharField(max_length=111, blank=True) imageForum = models.ImageField( upload_to='site/' ) bioForum = models.TextField(max_length=5500, blank=True) def __str__(self): return self.nameHome ProgrammingError at /ar/admin/accounts/sitename/ column accounts_sitename.languageCode does not exist LINE 1: ...tename"."user_id", "accounts_sitename"."site_id", "accounts_... ^ -
how to use triple nested quotes in django tempates?
i'm trying to use inline CSS and loading an image as a background in Django template. i need three quotes but don't know how to do it. how can i fix the code bellow? <div class="full-background" style="background-image: url("{% static '/img/curved-images/white-curved.jpg' %}")"></div> -
Django Admin Page execute javascript on Custom Action Buttons
I'm trying to add a custom button in each row next to a user to the django admin page which makes it easier for the admin to click the button and generate a password reset link for a particular user rather than navigate to the hidden actions section of the django admin page. Something like this - https://hakibenita.com/how-to-add-custom-action-buttons-to-django-admin Following is the code I've implemented and it works and navigates to a new page with the correct reset-password request and the reset_password() method executes with a link being sent to the user. However, when I click the button, I would like to send an AJAX GET request to the same url as above and just a show an alert to the admin on request completion instead of navigating to a new page. Currently I'm unable to run the javascript code using the format_html method in Django (see code below) Is there a way to run the class UserAdmin(Admin.modelAdmin): list_display = ('name', 'email', 'custom_actions') form = forms.UserAdminForm def get_urls(self): urls = super().get_urls() custom_urls = [ url( r'reset-password/(?P<user_id>.+)', self.admin_site.admin_view(self.reset-password), name='reset-password', ), ] return custom_urls + urls def custom_actions(self, obj): user = user_model.User.get(user_id=obj.id) password_reset_url = reverse('admin:reset-password', args=[user.id]) return mark_safe(format_html( f'<a class="button" onclick="parent.location=\'{password_reset_url}\'" >Reset Password</a>&nbsp;' … -
How to substract custom date in models.DateField from now()?
I still can't find a working solution, hence I decided to throw my first post. Note, I'm a beginner in Django. Building a portal that displays days since the user has been verified. I tested my model without using custom DateField (verified_since), just with date_joined, and it works properly - showing the count of days remaining (I countdown from 365 days, I am not worried about the leap year yet) since the user has registered in the database vs. today. class Profile(models.Model): verified_since = models.DateField(default=now) @property def ver_since(self): return 365 - (now() - self.user.date_joined).days Now if I use verified_since instead date_joined, I get an error. I suspect this is due to a different format of a date, or maybe a string format instead of a date which can't be subtracted then from datetime.now() verified_since is manually entered date on the form by user. class Profile(models.Model): verified_since = models.DateField(default=now) @property def ver_since(self): return 365 - (now() - self.user.verified_since).days Here is settings: TIME_ZONE = 'CET' USE_I18N = True USE_L10N = False USE_TZ = True TIME_INPUT_FORMATS = ('%H:%M',) DATE_INPUT_FORMATS = ['%d/%m/%Y'] -
Post Blob Image to django rest framework with ajax
I have a html page that allows a user to take a screenshot from their camera. This screenshot is then rendered in the page with the function from main.js down below. If i do console.log(image) i get image tag with a src to a blob:http that has the image. Now for the fun part. I want to post this image to my api in django rest framework. Basically how do i go from a blob image to a post request to the api? I tried using $.ajax but I dont know how to format the "blob data" to be accepted for the "data:" parameter field in ajax. Note also that i'm not using forms in the html, when i do that the html page gets refreshed as soon as i take a screenshot so the image does not stay on the page.. If I have to use forms in order to make this work, please let me know and I will try another approach. main.js async function grabFrame() { const img = await imageCapture.grabFrame(); const url = URL.createObjectURL(await imageCapture.takePhoto()); document.querySelector("img").src = url #id_image is where the screenshot is located const image = document.getElementById('id_image') console.log(image) index.html <button onclick="grabFrame()">Grab Frame</button> <img id="id_image" … -
Hovering over Morris Chart is not working as expected
Hovering is not working for my chart, any suggestions as to what it could be? This is a django template with the Morris Chart within. I've got Morris Chart working on other django templates just fine so I'm not sure if it's the payload that the chart doesn't like or just a simple syntax issue - thanks!! {% for item in data_alpha %} <div class="row"> <div class="col-lg-12"> <div class="panel panel-primary"> <div class="panel-heading"> Load Time | {{ item.link }} <button class="btn btn-sm btn-default vertical-allign-baseline pull-right" data-toggle="modal" data-target="#helpLoadTime"> <i class="fa fa-question-circle" aria-hidden="true"></i> Help </button> </div> <div class="panel-body"> {% for key, value in regions.items %} <span class="regions" style="background-color: {{ value }}"></span> <span> {{ key }}</span> {% endfor %} <div id="tg-load-chart_{{ forloop.counter }}" style="height: 300px;"></div> <script> rawData = {{item.tg_load_time_graph|safe}}; aws_regions = Object.keys({{item.tg_load_time_graph|safe}}); processedData = processRawData(rawData, aws_regions); chartData = processToChartData(processedData); colours = Object.values({{regions|safe}}); new Morris.Line({ element: 'tg-load-chart_{{ forloop.counter }}', data: chartData, xkey: 'datetime', ykeys: aws_regions, labels: aws_regions, hideHover: 'auto', pointSize: 0, xLabels: '10min', lineColors: colours, }); </script> -
Django-ckeditor dialog box fields are not displaying properly
I'm trying to use Django-CKEditor for a RichTextField, the text editor is showing fine, but the dialog boxes for its options are displaying with a ruined text field in my forms. The editor and dialog boxes are working fine in admin forms, I tried to use bootstrap4 but the problem is still there. {{form.media}} is on my page here is a picture of the problem. -
.Env file in Django project
I write this lines in .env file in django project to link my project to my Data base but visual code make a problem to the file -
ZMQ - Multiple workers with the same socket Dealer
I have a Python package with the purpose of serving as Dealer to several pieces of code scattered in my solution. But until now it was only being used in a Django Views, so within an application. But now I would like to use this package in a separate script and it seems to me that the script is failing to execute zmq.Context.instance().socket(zmq.DEALER).connect(SOCKET_ADDR) because it is already being used by views.py. Does it make sense? dealer.py (package): imports... context = zmq.Context.instance() workerCnctn = context.socket(zmq.DEALER) workerCnctn.identity = 'xxxxx' workerCnctn.setsockopt(zmq.LINGER, 0) workerCnctn.connect(SOCKET_ADDR) class A: def __init__(self): self.workerCnctn = workerCnctn def send(self, arg1, arg2): ... self.workerCnctn.send_string(msg) views.py: imports ... import dealer ... @api_view(["POST"]) def send(request): ... dealer = dealer.A() A.send(arg1, arg2) ... script.py: imports ... import dealer ... def main(): ... dealer = dealer.A() A.send(arg1, arg2) ... The script is to be called manually and the Django application is running constantly. What I noticed is that in the logs of the Router I can only catch messages that come from views.py. So I ask, can't I have different workers with the same purpose using the same socket? -
Django websockets and channels group_send not working
I started looking into websockets and I would liek to implement realtime communication between web-client (Angular 13) and Python app. As backend I used Django with implemented websockets and channels As i am having problem i simplified code as much as i could so a lot of values are hardcoded for a sake to make it work. (Right now it is One WebClient and one Bot) I implemented 2 Consumers. Bot and webclient: class BotConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.channel_layer.group_add("bot","dev") async def disconnect(self, close_code): await self.channel_layer.group_discard("bot","dev") async def receive(self, text_data): await self.channel_layer.group_send("dev",{"type": "recv","text": "test"}) print("Data sent to group") class WebClientConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.channel_layer.group_add("client","dev") async def recv(self,event): print("Consumer received smthing from channels") async def disconnect(self, close_code): await self.channel_layer.group_discard("client","dev") async def receive(self, text_data): print("Smthing received") my channel_layer setup in Setting.py CHANNEL_LAYERS = { 'default': { # 'BACKEND': 'channels_redis.core.RedisChannelLayer', # 'CONFIG': { # "hosts": [('192.168.1.10', 6379)], # }, "BACKEND": "channels.layers.InMemoryChannelLayer" }} I tried both Redis with local server running and in memory channels My websocket's routing.py: from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'live/bot', consumers.BotConsumer.as_asgi()), re_path(r'live/webclient', consumers.WebClientConsumer.as_asgi()), ] My behavior: Django logs: HTTP POST /core/UpdateAvailableServers 200 [0.07, 127.0.0.1:50494] HTTP POST /core/GetPostInfo 200 [0.02, … -
Djnago Adding ManytoMany objects to an object after being created
Im trying to add a many to many field to an object after it is created but keep running into the same error: Direct assignment to the forward side of a many-to-many set is prohibited. Use dogs.set() instead. in my models.py class linkedDog(models.Model): linked_dog = models.ForeignKey(Dog, blank=True, null=True, on_delete=models.CASCADE) service_chosen = models.ManyToManyField(Service, blank=True) shampoos_chosen = models.ManyToManyField(Shampoo, blank=True) total_time = models.IntegerField(blank=True, default=0) class PsuedoAppointment(models.Model): client = models.ForeignKey(User, blank=False, on_delete=models.CASCADE) dogs = models.ManyToManyField(linkedDog, blank=True) total_time = models.IntegerField(blank=False, default=0) I am trying to add a linkedDog object to dogs field in my views I've used this question as a reference Direct assignment to the forward side of a many-to-many set is prohibited. Use emails_for_help.set() instead But can't figure out what I'm doing differently or where its going wrong @login_required def loggedin_appointment_view(request): if request.method == "POST": form = linkedDogForm(request.POST, user=request.user) if form.is_valid(): dog = form.save() dog_id = dog.id dogsquery = linkedDog.objects.filter(id=dog_id) appointment = PsuedoAppointment.objects.create(client=request.user, dogs=None, total_time=None) for dog in dogsquery: appointment.dogs.add(dog) return render(request, 'home.html') else: dog_form = linkedDogForm(user=request.user) return render(request, "appointment_template/loggedin_appointmentmaker.html", context={'dog_form' : dog_form}) I also tried dog = form.save() dog_id = dog.id dogsquery = linkedDog.objects.filter(id=dog_id) appointment = PsuedoAppointment.objects.create(client=request.user, dogs=None, total_time=None) appointment.dogs.set(dogsquery) -
Getting queryset with direct results
Is there any way to actually get queryset by direct values of params? I'm scraping data from api and sometimes there are 3 options. Single record can have full date which is year-month-day, another one could have only year-month and another could have only year. If there is certain date in my database, then i want to get it and add to the new object, but if there is not, then i want to create it. The problem is that, when i'm getting value of let's say year 2017, then i can get values of 2017, 2017-month, and 2017-month-day. Is there any way to search in database so it can act that if param have no value, then it's null? My model here: class Date(models.Model): year = models.PositiveIntegerField() month = models.PositiveIntegerField(blank=True, null=True, validators=[ MaxValueValidator(12), MinValueValidator(1)]) day = models.PositiveIntegerField(blank=True, null=True, validators=[ MaxValueValidator(31), MinValueValidator(1)]) -
Why should I only allow image upload during DEBUG mode?
I want to add a field for users to edit their profile pictures and checked out a few tutorials. However, every tutorial I've found included some form of this in urls.py: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT Why can't I do this with deployment and if it has to be like this? Is there any way for me to allow users to upload and modify their profile pictures? Any help would be appreciated. Thanks. -
IntegrityError in Django model
I am doing a little prototype of a (social network/chat), I have an app to chat and other to groups and when I post a message get this: ('23000', "[23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot insert the value NULL into column 'grupo_id', table 'redsocial.dbo.chat_mensaje'; column does not allow nulls. INSERT fails. (515) (SQLExecDirectW); [23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The statement has been terminated. (3621)") This is my models.py file in group app: from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse class Grupo(models.Model): nombre_grupo = models.CharField(max_length=50) descripcion = models.CharField(max_length=200, default="Sin descripcion") fecha = models.DateTimeField(auto_now_add=True) propietario = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.nombre_grupo def get_absolute_url(self): return reverse('lista_grupos') This is my models.py file in chat app: from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse # Create your models here. class Mensaje(models.Model): grupo = models.ForeignKey( 'grupo.Grupo', on_delete=models.CASCADE, ) mensaje = models.CharField(max_length=200) propietario = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.mensaje def get_absolute_url(self): return reverse('chat', args=[self.grupo.id]) This is my view.py file in chat app: from django.views.generic import ListView, CreateView from .models import Mensaje class MensajeView(CreateView): model = Mensaje template_name = 'chat/crear_mensaje.html' fields = ('mensaje',) def form_valid(self, form): form.instance.propietario = self.request.user … -
In Django is there a way to "Convert" admin inlines to formsets / front-end?
I have a project that I have been building with some nested relationships (foreign keys). I have come to the end of building the models and getting the admin set up using admin.py. A simple example is: class PhoneInlineAdmin(admin.TabularInline): model = Phone extra = 0 list_display = ["number", "type"] @admin.register(Person) class ContactAdmin(admin.ModelAdmin): list_display = ["last_name", "first_name", "email"] inlines = (PhoneInlineAdmin, ) I love how the admin page works. I can search filter and click save to update all the tables. I am reading through the formsets documentation and class-based views, which is how I have decided to build this learning project. It seems to be quite involved to replicate something that already, near perfectly, exists in the admin page of my app. Is there a simple way that I am missing to replicate the functionality, or do I need to rebuild everything to come close to replicating the admin functionality? If I need to roll up my sleeves, I will, but I thought it was worth asking. -
Django Group Entries by Month
I'm simply trying to group entries in my Data.active_objects that occur in the same month and year. I would like if entries sharing the same month and year would be annotated with the number of occurrences in Data.active_objects Data.active_objects has a few entries with the same month values in 'ts_create' What I've tried so far is test = Data.active_objects.annotate(ts_create__count=Count(TruncMonth('ts_create), distinct=True) However, this does not produce results that I would expect as every entry in Data.active_objects has an annotated value 'ts_create__count' of 1 even when the entries occur in the same month -
How Do I Add A Decorator To A Class?
So I'm able to add a decorator to several functions within my code but I'm unsure as to how to add it to a class. Here are my decorators: def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('index') else: return view_func(request, *args, **kwargs) return wrapper_func --------------------------------------------------------------------- def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorised to view this page') return wrapper_func return decorator --------------------------------------------------------------------- Here is the Class: class PasswordsChangeView(PasswordChangeView): form_class = PasswordChangedForm success_url = reverse_lazy('password-success') -
Getting Django view dictionary key in Javascript, but instead of considering it a String, considers a Variable Name
I am doing a project in Django. In my views I send data to the HTML pages with dictionaries. I can easily access that data on HTML, but when I try to access it on Javascript I can't because Javascripts thinks it's a variable name. For example, I have a log in page. If the credentials are wrong, I send them to the same page and tell them that the username or password are wrong. I want to keep the previously written username on the form, so the person only needs to rewrite the password. I send the username from the view to the Javascript, but I can't access it. My view code: def login_form(request): assert isinstance(request, HttpRequest) if 'username' and 'password' in request.POST: user = request.POST['username'] passw = request.POST['password'] if rightcredentials(user,passw): tparams = { 'message': 'login successful', } return render(request, 'about.html', tparams) else: tparams = { 'login' : 'failure1', 'username_info' : user } return render(request, 'login_form.html', tparams) Javascript code: {% if login == 'failure1' %} <form action="." method="post"> {% csrf_token %} <div class="program-info"> <h3 class="program-title">Sign Into Your Account</h3> <p>Wrong Username or password</p> <div class="form-group"> <input type="text" value="" class="form-control" name="username" id="username" placeholder="Username"> </div> <div class="form-group"> <input type="password" class="form-control" name="password" placeholder="Password"> … -
how to change the Model field value with logic to time
Say I have a model named Quote class Quote(models.Model): # date_validity will have persistent data like this 2023-11-30 15:00 date_validity = models.CharField(max_length=100, blank=True) quote_status = models.CharField( max_length=150, default='active') So I need to set quote_status expired if data_validity meets the current time, If validity is 2 days later from now then the quote should expire if validity time is over. How can I manage this automatically? As far as I know self.save() method does not trigger automatically. So any suggestions to solve this? -
Django error while serializing image model of child field
I am new to this tech, while working on django project i got some issues when i try to serialize Ticket's account.profile_pic models.py class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE profile_pic = models.ImageField(upload_to='images/profile_pics/', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) class Ticket(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE) descr = models.TextField(blank=False, null=False) likes = models.ManyToManyField(User) serializers.py class DetailedTicketSerializer(serializers.ModelSerializer): # Error occurs on below line: No file associated with ImageField author_profile_pic = serializers.ReadOnlyField(source='author.profile_pic') author_username = serializers.ReadOnlyField(source='author.user.username') class Meta: model = Ticket fields = ['id', 'author_profile_pic', 'author_username', 'likes', 'descr'] Anyone knows how do i serialize Account.profile_pic's url??? -
Unable to send context to django template
Didn't find a solution to similar issue. I have a list of tasks rendered on a page and after clicking on a title a modal window is popping up with a form to update the task. List and update are made in one class-based view. When a modal window is opened task id is received by views.py from AJAX to update my context in order to show saved data in form fields. I can see updated context with specific object when printing it in my views.py, but the object is not shown in HTML via template tag. Please, help me to figure out what am I doing wrong. Here is my views.py: class KanbanBoardView(PermissionRequiredMixin, View): permission_required = ('projects.view_taskassign',) def get(self, request, *args, **kwargs): context = { 'heading': "Kanban board", 'pageview': "Tasks", 'tasks': TaskAssign.objects.all(), 'statuses': Status.objects.all(), 'users': User.objects.all(), } if 'taskid' in request.GET: task_id = request.GET.get('taskid') task_object = TaskAssign.objects.get(id=task_id) context['task'] = task_object return render(request, 'tasks/kanbanboard.html', context) return render(request, 'tasks/kanbanboard.html', context) def post(self, request): if 'edittask' in request.POST: id = request.POST['id'] deadline = request.POST['deadline'] status = request.POST['status'] user = request.POST['user'] task = TaskAssign.objects.filter(id=id) task.update(deadline=deadline, status=status, user_id=int(user)) return redirect('tasks-kanbanboard') else: status_id = int(request.POST.get('status')) task_id = int(request.POST.get('task_id')) task = get_object_or_404(TaskAssign, pk=task_id) task.status_id = status_id …