Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create an Excel sheet using xlwt in django
I want to create an excel file like below.But I do not know , how to implement it.Excel sheet contains headers,sub headers and sub-sub headers. Actually the excel sheet is generated based on the from date and to date.If there is three months between from date and to date,these three months should be shown as columns in the excel sheet. from_date = request.POST.get('f_date') to_date = request.POST.get('t_date') file_name = "Report" content_disposition = 'attachment; filename="' + file_name + '.xlsx"' title = str(file_name) + " {} TO {}".format(from_date, to_date) header = ['Plant Locality', 'Plant', 'Product', 'UOM', 'Previous Year FTP', 'Previous Year YTP'] Can anyone suggest a solution to create this excel sheet using xlwt? -
Django OneToOneField - Add to parent or Child?
What is the proper way to add a OneToOneField in Django? Does it go in the parent class or child class? The official docs don't really explain this. Which way works better with the built-in admin interface? Does it matter? Is there a convention? What is the "correct" way? class Client(models.Model): name = models.CharField(max_length=30) portfolio = models.OneToOneField(to="Portfolio", null=True, on_delete=models.CASCADE) class Portfolio(models.Model): ... portfolio fields ... or class Client(models.Model): name = models.CharField(max_length=30) class Portfolio(models.Model): client = models.OneToOneField(to="Client", null=True, on_delete=models.CASCADE) ... portfolio fields ... I see most examples add it to the child, but it seems adding it to the parent works better with the admin interfaces and makes more sense logically. -
Updating Django ORM with filter is updating unexpected fields
I have a very simple DjangoRestFramework api_view where i am grabbing an id and filtering a queryset by that id and a start date greater than today. My Model is pretty simple, it has a patient (FK), is_cancelled (boolean), start (Datetime) and end (Datetime). The issue is that when i run the below update, it is setting the start date to the date and time that i run this view. @api_view(['POST']) def BookingCancelAppointmentsView(request): if request.method == 'POST': patient_id = request.data today = date.today() bookings = Booking.objects.filter(patient=patient_id, start__gte=today).update(is_cancelled=True) return Response({'message': 'Appointments cancelled'}) so for example, if find an entry that is greater than today for that patient_id, it does update the "is_cancelled" field for the correct record but it is setting the Start datetime from whatever datetime i had in there originally to the date.today() value even though i am only updating the "is_cancelled" field. Does anyone have any idea why it would touch the "start" field at all and how i might get around this issue? Software Versions: Python Version: 3.10.5 Django Version: 3.2.15 Django Rest Framework Version: 3.13.1 -
use postman to test websocket showing 403
I wrote a demo like channels' document(https://channels.readthedocs.io/en/stable/tutorial/index.html).But when I used postman to test websocket, it showed Error: Unexpected server response: 403. I just wrote an adress, someother should I have to set? -
How to visualize MySQL data with python web development modules
I have a requirement to visualize Linux servers patching status. So I added the patching status into MYSQL but still I want to visualize those data on web using python. I want to visualize the data on the web page from MySQL table using python web development I am trying to provide visibility to everyone in the project can find the details simply accessing the website. -
Python/Django f-strings interpreting a string as input
Running out of ideas where to look. I am trying to set up a string that can be edited outside my code and stored by the user and have that string feed into an f-string inside my code. Example: Take the following value that is stored in database CharField: Hello {user}! How are you? I want to grab that and feed it into Python to treat as the content of an f-string such that: >>> user = 'Bob' >>> stringFromOutside = 'Hello {user}! How are you?' >>> print(f'{stringFromOutside}') Hello {user}! How are you? prints "Hello Bob! How are you?" I oversimplified for the example, because that's the core of where I'm lost. I have tried nesting the {stringFromOutside} in a second f-string, but that doesn't work. I have also tried double {{user}} inside the template file, but that did not work. Use Case in case I'm just being obtuse and doing the whole thing wrong I have an application that I want to expose to the administrator the ability to write templates and save them in the database. The templates need to be able to pull from several different objects and all the properties of those objects, so it would … -
Django DeleteView success_url to previous/different page
I have these url patterns: app_name = "posts" urlpatterns = [ path('global/', PostListView.as_view(), name='global-list'), path('personal/', PersonalPostListView.as_view(), name='personal-list'), path('<int:pk>/', PostDetailView.as_view(), name='detail'), path('<int:pk>/delete/', PostDeleteView.as_view(), name='delete'), ] Inside each of the templates of PostListView, PersonalPostListView, and PostDetailView is a delete option like this: <a href="{% url 'posts:delete' object.id %}">Delete</a> What I want to happen is after deleting the object, it will redirect to the last page where the delete link was clicked (except for detail view). Thus, there are 3 possible cases as follows: Case 1: PostListView template -> click delete -> PostDeleteView confirm delete template -> back to PostListView template Case 2: PersonalPostListView template -> click delete -> PostDeleteView confirm delete template -> back to PersonalPostListView template Case 3 (the exception): PostDetailView template -> click delete -> PostDeleteView confirm delete template -> back to PostListView template This is my attempt so far: class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Post def get_success_url(self): return self.request.META.get('HTTP_REFERER') However, clicking delete from the PostListView returns posts/15/delete/ which should just be posts/global/. Moreover, it should return posts/personal/ if deleted from PersonalPostListView template and (the exception) posts/global/ if deleted from PostDetailView template. An alternative I've thought is to assign different DeleteViews (with different success_url) for each template. However, this … -
django web project - connected with https. Forbidden (403) CSRF verification failed
There was no problem when connecting to the http server. If you log in from the web server after connecting to https, the following error works: In login.html {% csrf_token %} is written Forbidden (403) CSRF verification failed. Request aborted. More information is available with DEBUG=True. Is there any way to enable this when DEBUG= False? -
How to render filtered data using django and ajax
I'm very much new to AJAX and JQuery. So, my problem is: I want to show a filtered list of a django model called "Recipe" when a user clicks on a checkbox but I don't know how to pass in the data in ajax so that it reloads it correctly for example: I have a Recipes List in my home page which displays all the recipes and right next to it is a filter sidebar where a user can check multiple checkboxes in multiple categories to filter the data according to the input. But I don't know how to pass the data in the views so that ajax loads it into the page. Any help would be appreciated! Here's my code: views.py # filter recipes def filter_recipes(request): print(request) recipes = Recipe.objects.all() diff = request.GET.getlist("difficulty[]") if len(diff) > 0: filtered = recipes.filter(difficulty__in=diff) print(f"recipes =============== {filtered}" ) ajax = render_to_string("ajax/recipes_list.html", {"data": filtered}) return JsonResponse({"data": ajax}) <!-- JQuery script in landing_page.html--> <script> $(document).ready(function () { $(".ajax-loader").hide(); // start of filter by value $(".form-check-input").on("click", function () { let _filterObj = {}; $(".form-check-input").each(function (index, element) { let _filterValue = $(this).val(); let _filterKey = $(this).data("filter"); _filterObj[_filterKey] = Array.from( document.querySelectorAll( "input[data-filter=" + _filterKey + "]:checked" ) ).map(function … -
Unexpected behavior with Django migrations when trying to leverage MSSQL schemas
I currently maintain a Django project that uses a Postgres database and follows the principles in this article to leverage multiple schemas. This keeps all the tables nice and namespaced. I have a 'core' app, where I have defined a base model that has a couple foreign keys to my custom 'Auth' model. These fields are '_created_by' and '_last_updated_by'. Every model in every other app inherits from this model, and as a result every table in every schema has a foreign key relationship with my custom 'Auth' model. When using Postgres, I can migrate my custom 'Auth' app, and it creates all the necessary tables in the default 'public' schema. And then I can do: python manage.py migrate app --database=app_db for my other apps, and the relevant tables get created in the correct schema. (I have created the schemas beforehand, django does not do that for you) This is perfect. However recently it has become apparent that my life would be easier were we to use MSSQL for the backend. After some work, everything almost works, however when I migrate an app using the above command, it creates duplicate 'Auth' tables in the app schema. So now I have a … -
Hi everyone I'm struggling with a for loop in attempt to make a categories filter (Django - Bootstrap)
Like the title say's I have a problem trying to make a categories filter, already did one for my Blog because only has a couple of categories without subcategories, but this one is different because it has categories and subcategories with one to many fields and already tried multiples approaches but I couldn't make it work. I would be glad if someone lend me a hand. This one was my last attempt, I tried to make it like my other less complex categories filter. Store unique html template. <section class="page-section cta rounded p-6 p-md-5 m-md-4 text-center bg-light"> <div class="container"> <div class="row"> <div class="col-xl-9 text-center mx-auto"> <h2 class="section-heading mb-4"> <span class="section-heading-lower">Horizontal</span> </h2> <div style="padding-bottom: 1%; padding-top: 3%;"> <h4><span class="section-heading-upper">CATEGORIAS: </span></h4> {% for itemWide in itemsWide %} {% for category in itemWide.categories.all %} <a type="button" class="btn btn-dark" href="{% url 'storePacks' %}"> <span class="section-heading-upper" style="font-size:small;">{{category.name}}</span> </a> {% endfor %} {% endfor %} </div> </div> </div> </div> </section> Store model class ItemCategory(models.Model): name = models.CharField(max_length=50) created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now_add=True) class Meta: verbose_name = 'itemCategory' verbose_name_plural = 'itemsCategories' def __str__(self): return self.name class SubCategoryVert(models.Model): parentCategory = models.ForeignKey(ItemCategory, on_delete=models.CASCADE) name = models.CharField(max_length=50) created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now_add=True) class Meta: verbose_name = 'SubCategoryVert' verbose_name_plural … -
How to restore deleted files from a GitHub account
I accidentally deleted the code from my GitHub account using Github Interface and wanted to recover it through.Is there anyway I can run commands directly through my github account and not through github console? -
AttributeError: 'str' object has no attribute '_meta' Migrating django 4.1
Whenever I try to use the migrate command on django, this error pops up for the migration file in app "fonte". The model inside uses a ManyToMany field with the through argument on the model "FonteVariavel", which then connects to "Variavel". Applying fonte.0001_initial...Traceback (most recent call last): File "/APP/manage.py", line 22, in <module> main() File "/APP/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/.venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/.venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "/.venv/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 349, in handle post_migrate_state = executor.migrate( File "/.venv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 135, in migrate state = self._migrate_all_forwards( File "/.venv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( File "/.venv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 252, in apply_migration state = migration.apply(state, schema_editor) File "/.venv/lib/python3.9/site-packages/django/db/migrations/migration.py", line 130, in apply operation.database_forwards( File "/.venv/lib/python3.9/site-packages/django/db/migrations/operations/models.py", line 96, in database_forwards schema_editor.create_model(model) File "/.venv/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 453, in create_model if field.remote_field.through._meta.auto_created: AttributeError: 'str' object has no attribute '_meta' Here is the relevant code from django.db.models import DateField, ManyToManyField, Model, TextField from core.fonte_variavel.models import FonteVariavelModel from core.variavel.models import VariavelModel from .managers import FonteManager from .querysets import FonteQuerySet class FonteModel(Model): nome … -
Send user's email to developers email django
Lets say i have an email when a user logs in . Could there a way to recieve an email that {user's email} has logged in and for log outs too. I have tried to do reaserch on this but didnt know how to start as i am a new to making websites -
Having an error 'AttributeError at /register/ '
Full of error : AttributeError at /register/ 'DataEbotUser' object has no attribute 'session' I abstracted the User and created a DataEbotUser as models then created a form which takes this as a model. But when I try to add user with using this form Im taking such an error. And there is also one more problem. When I try to add user with Django Administraion having an KeyError 'first_name' (if I delete the init function in forms it becomes normal). I need a proper register form which works properly. I cant understands the problems clearly. (I created the models in different app and imported) class DataEbotUser(AbstractUser): phone=models.CharField(max_length=20) LastClientLogin = models.DateTimeField(null=True , blank = True) LastServerLogin = models.DateTimeField(null=True , blank=True) AllowServerLogin = models.BooleanField(default=False) LoginType = models.IntegerField(null=True , blank=True) class DataLoginType(models.Model): user = models.ForeignKey(DataEbotUser, null=True , on_delete=models.CASCADE) name = models.CharField(max_length=200) detail = models.CharField(max_length=200) isActive = models.BooleanField(default=False) def __str__(self): return self.name class CustomUserCreationForm(UserCreationForm): class Meta: model = DataEbotUser fields = ['username','first_name','last_name','email','phone','password1','password2'] def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter username...'}) self.fields['first_name'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter First Name...'}) self.fields['last_name'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter Last Name ...'}) self.fields['email'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter Email...'}) self.fields['phone'].widget.attrs.update( {'class': 'form-control', 'placeholder': 'Enter Phone...'}) self.fields['password1'].widget.attrs.update( {'class': … -
Django - adding gamification features
I have a medium size Django REST app that I'm looking to add gamification features to. The application in question is a school webapp where students can create mockup quizzes, participate in exams that teachers publish, and write didactical content that gets voted by other students and teachers. I want to add some gamification features to make the app more interesting and to incentivize participation and usage of the various features: for example, each student will have a personal "reputation" score, and gain points upon completing certain actions--a student may gain points when completing a quiz with a high score, when submitting some content, or when receiving upvotes to such content. The tricky part is I want to be able to have this logic be as separate as possible from the existing codebase, for various reasons: separation of concerns, ability to plug the engine in/out if needed, ability to easily deactivate features for certain groups of users, etc. What I'm looking for here is some software engineering advice that's also Django-specific. Here's a high level description of what I'm thinking of doing--I'd like some advice on the approach. create a new gamification app. Here I will have models that describe … -
Django formset error for ID "Select a valid choice. That choice is not one of the available choices"
I am posting a formset in Django. The form on the client side is generated dynamically using a file uploaded by the user. I render it like this: <form method="post" id="add3"> {{ formset.management_form }} {% csrf_token %} <table id="forms"> <tbody> {% for lst in result %} <input type="hidden" name="form-{{ forloop.counter0 }}-id" value="{{ forloop.counter }}" id="id_form-{{ forloop.counter0 }}-id"> <tr> <td> <input type="hidden" name="form-{{ forloop.counter0 }}-expense" id="id_form-{{ forloop.counter0 }}-expense" value="{{lst.0}}"/> </td> <td> <input type="hidden" name="form-{{ forloop.counter0 }}-amount" id="id_form-{{ forloop.counter0 }}-amount" value="{{lst.1}}"/> </td> {% endfor %} </tbody> </table> </form> I get the following error on the server side when I receive the formset. Formset is_valid returns False and I get the error: id: Select a valid choice. That choice is not one of the available choices How can I fix this? What's the right way to pass an ID? Note: I am updating management_form total-forms using Javascript. If that matters. -
Django NoReverseMatch after deleting object
Im hard stuck here, everything is connected via pk, and on group of accounts can see only their data whiel an other group can see all data from the other group. But I have a model where ONLY the staff group can add update and delete while the other group can only update. While it works fine and all when the staff group deletes all 'teachers' in that case I get no reverse match error. The thing is, In the view the staff needs to see everything compact in their template like the school and teacher and so on. right now I either have atleast two type of teacher and the template works or the school is sorted normaly while the teachers are all shown under every school template hope you get what I mean. I only need something that dont break if a FK is deleted so that if staff makes a new teacher everything works template <ul> <li>{{Ansicht.Lehrer_FK.Leitung_der_Klasse}}</li> <a href="{% url 'LehrerAktualisierenVerwaltung' Ansicht.Lehrer_FK.pk %}" >Lehrer Aktualisieren</a> <a href="{% url 'LehrerEntfernenVerwaltung' Ansicht.Lehrer_FK.pk %}" >Lehrer L&ouml;schen</a> </ul> form class LehrerAktualisierenVerwaltung(LoginRequiredMixin, UpdateView): model = LehrerTabelle fields = '__all__' template_name = 'SCHUK/LehrerAktualisierenVerwaltung.html' context_object_name = 'LehrerAktualisierenVerwaltung' def get_success_url(self): return reverse('Dashboard') url path('LehrerAktualisierenVerwaltung/<int:pk>/', LehrerAktualisierenVerwaltung.as_view(success_url="Dashboard"), … -
How to build Django external URLs with differing protocols
I am soliciting and parsing user content for all types of URLs (starting with http|https|ftp as well as only www.xxx.xxx), e.g. http://www.foo.bar and www.google.com and https://guardian.co.uk. At a later stage I am presenting these URLs back in a template and want to create links that go straight to those destinations: <a href="//{{resource.text}}" target="_blank" role="button">{{resource.text}}</a> However, if I don't prefix with // I get relative URLs (which obviously isn't working), but if I do add the prefix and create absolute URLs, I'm up the creek as the protocols differ between the various URLs. Is there a way to tell Django to treat the URLs naively and let the browser sort out the context? -
How to set relation between Product Sales and Product Costs Tables in Django
probably basic question but I need help how to set up relations between my models. I have the first model SalesData, where I import from csv sales data of products for particular periods - so this table can contain a product multiple times with different dates, quantities and sales: class SalesData(models.Model): date = models.DateField("Date", null=True, blank=True) product = models.CharField("Product", max_length=150, null=True, blank=True) sales = models.DecimalField("Sales", max_digits=10, decimal_places=2, null=True, blank=True) quantity = models.IntegerField("Quantity", null=True, blank=True) I have the second model ProductCosts, where I have the product and its production costs. And one product can have only one specific production costs. class ProductCosts(models.Model): product = models.CharField("Product", max_length=150) costs = models.DecimalField("Costs", max_digits=10, decimal_places=2) And I need help with: how to connect these two tables to be able to get production costs for particular product to each row in SalesData table, so I will be able to calculate profit, margin etc. for particular rows? what to do, to be able to create form, where I can fill production costs for rows, where are these costs missing for new sales data inputed to table? And if it is possible to have the form as a table with products with missing costs in the first column … -
I want to collect visitors information on a website im building
I want to be able to get my web visitors email only when the signup and get notified when the logout. How should i go about this -
Django: How can I use inlineformset to save multiple forms that all share the same FK as another object being created on the same form page?
I have two models Animal and Gene_Animal_Bridge. I have a form page that allows a user to add a new animal to the database and attach any genes that they have. The genes are stored in Gene_Animal_Bridge which contains the FK of the animal it belongs to, and the FK of the Gene that is stored in the GeneInfo Model. Everything works fine but when it comes to iterating over the formset, only 1 gene will be saved and any other gene forms added on the page won't save. Models.py from django.db import models import datetime class Animal(models.Model): animal_id = models.AutoField(primary_key=True, editable=False, null=False) gender = models.CharField(max_length=6, choices=(('m','male'), ('f','female')), null=True) name = models.CharField(max_length=14) description = models.CharField(max_length=75,blank=True, null=False) dob = models.DateField(default=datetime.date.today, blank=True, null=True) purchase_date = models.DateField(default=datetime.date.today, blank=True, null=True) image = models.ImageField(blank=True, null=True) prey_type = models.CharField(max_length=20,choices=(('1','2XL Multi'),('2','Large Weaner'),('3','Live Multi'),('4','Small Rat'),('5','Small Weaner')),blank=True, null=True) last_feed = models.DateField(default=datetime.date.today, blank=True, null=True) last_shed = models.DateField(default=datetime.date.today, blank=True, null=True) weight = models.IntegerField(blank=True, null=True) class GeneInfo(models.Model): gene_id = models.AutoField(primary_key=True, editable=False, null=False) gene_name = models.CharField(max_length=20, null=False) type = models.CharField(max_length=20,choices=(('1','pos het'),('2','het'),('3','visual'),('4','co-dominant'),('5','super'),('6','dominant')),null=False) def __str__(self): return (self.gene_name) class Gene_Animal_Bridge(models.Model): animal_id = models.ForeignKey(Animal, on_delete=models.CASCADE, related_name="bridge_animal_id", null=True) gene_id = models.ForeignKey(GeneInfo, on_delete=models.CASCADE, related_name="bridge_gene_id", null=True) class Breeding(models.Model): sire_id = models.ForeignKey(Animal, on_delete=models.CASCADE, related_name="breeding_sire_id", null=True) dame_id = models.ForeignKey(Animal, on_delete=models.CASCADE, related_name="breeding_dame_id", null=True) … -
How to use form.as_table and crispy forms together?
I want to use form.as_table and crispy forms together, but it is generating an error as shown in the screenshot below :- Here is my code :- <form action="{% url 'create' %}" method="post"> {% csrf_token %} <table> {{form.as_table|crispy}}<br> </table> <input class="btn btn-outline-primary" type="submit" value="Create" id="create"> </form> -
Django: Get count of specific values by month in queryset
my model is like so: class Project(models.Model): name = models.CharField(max_length=1000, null=True, blank=True) date_created = models.DateTimeField(auto_now=True) status = models.CharField(max_length=1000, null=True, blank=True) The status field has about 5 different options (won, lost, open, pending, cancelled). I need to know how to get the number of projects with x status in each month in a given time range query. I was able to get the sum total of projects each month with the following annotation: Project.objects.all().annotate(month=TruncMonth('date_created')).values( 'month').annotate(total=Count('pk'), ).order_by('date_created') However, I am looking for an output like this: [{date: 'January 2020', total: 30, won: 10, lost:10, open: 10, pending: 0, cancelled: 0}, {date: 'February 2020', total: 30, won: 10, lost:10, open: 10, pending: 0, cancelled: 0}, {date: 'March 2020', total: 30, won: 10, lost:10, open: 10, pending: 0, cancelled: 0}] Ideally I would like the keys within the final output to be dynamic (i.e. if a new status is added, we won't need to hardcode a new key into the query) but I don't know if this is possible or not. Thanks for your time! -
How to add a custom button beside the list display in django admin panel? To edit the form from list display it self
Here is my admin.py code: `from django.contrib import admin from .models import * from django.utils import * import csv from django.http import HttpResponse class ProductAdmin(admin.ModelAdmin): search_fields = ('name',) list_display = ('name','price',) admin.site.register(Product,ProductAdmin)` [I have attached my admin panel screenshot][1]