Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to enforce validation in django forms
I have a form that takes in start_time and end_time, both of which are DateTimeFields in my model.py. However, I want to make sure that the start_time is less than the end_time. I have created a function in my forms.py but it does not seem to be taking any effect. How I can enforce this validation? my forms.py class EventForm(ModelForm): class Meta: model = Event # datetime-local is a HTML5 input type, format to make date time show on fields widgets = { "start_time": DateInput( attrs={"type": "datetime-local"}, format="%Y-%m-%dT%H:%M" ), "end_time": DateInput( attrs={"type": "datetime-local"}, format="%Y-%m-%dT%H:%M" ), "title": TextInput(attrs={"placeholder": "Title"}), "description": TextInput(attrs={"placeholder": "Description"}), "author": forms.HiddenInput(), } fields = ["title", "description", "start_time", "end_time", "author"] def clean_time(self): start_time = self.cleaned_data.get('start_time') end_time = self.cleaned_data.get('end_time') if start_time > end_time: raise forms.ValidationError("Start time cannot be greater than end time") return self.cleaned_data def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) # input_formats parses HTML5 datetime-local input to datetime field self.fields["start_time"].input_formats = ("%Y-%m-%dT%H:%M",) self.fields["end_time"].input_formats = ("%Y-%m-%dT%H:%M",) my views.py for creating event: def event_create(request): instance = Event() data = request.POST.copy() data["author"] = request.user form = EventForm(data or None, instance=instance) if request.POST and form.is_valid(): form.save() return HttpResponseRedirect(reverse("cal:calendar")) return render(request, "cal/create_event.html", {"event": form}) -
django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "products_customer"
After make migrations , i tried to do migrate, but i am getting the django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "products_customer" But iam remove this customer table from models.py how i solve this ? models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class product(models.Model): product_id = models.IntegerField(primary_key=True) product_name = models.CharField(max_length=255) product_price = models.FloatField() product_stock = models.IntegerField() product_image = models.CharField(max_length=2500) class order(models.Model): order_id = models.IntegerField(primary_key=True) product_id = models.ForeignKey(product,on_delete=models.CASCADE) user = models.ForeignKey(User,on_delete=models.CASCADE) order_quantity = models.IntegerField() order_total = models.IntegerField() order_shipped = models.BooleanField() class address(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) house_name = models.CharField(max_length=255, blank=True) town = models.CharField(max_length=255, blank=True) post_office = models.CharField(max_length=255, blank=True) pincode = models.CharField(max_length=255) district = models.CharField(max_length=255, blank=True) land_mark = models.CharField(max_length=255, blank=True) phone = models.CharField(max_length=15, blank=True) @receiver(post_save, sender=User) def create_user_address(sender, instance, created, **kwargs): if created: address.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_address(sender, instance, **kwargs): instance.address.save() -
Why does django show me existing rows error?
You are trying to add the field 'created' with 'auto_now_add=True' to user without a default; the database needs something to populate existing rows. Provide a one-off default now (will be set on all existing rows) Quit, and let me add a default in models.py -
how use super in django tables2 render_*
i create new Column and add customize render as below class PriceColumn(django_tables2.Column): def render(self, value): if isinstance(value, int) or isinstance(value, float): self.attrs['td']['title'] = f'{round(value, 2):,}' return number_convertor_to_milion(value) return '--- then i used it for field weekly_returns = PriceColumn(verbose_name=_('Weekly Returns')) def render_weekly_returns(self, value,**kwargs): final_result = value*100 // i want to call super().render() like below return super().render(final_result,**kwargs) i want to call super as in code writed but gives error how can do this? -
How to get access token and refresh token ( rest_framework_jwt ) in a single API in Django
I need to get access token and refresh token in a single API, Currently I have 2 API's for both access and refresh tokens url(r'^token-auth', view.ObtainJWTView.as_view(), name='token-auth'), url(r'^token-refresh', refresh_jwt_token), I need one more API for both -
How to remove first brackets from list in django?
I write a query to get the list like this: tStartEnd = APIHistory.objects.values('status_start','status_end') codereview = list(tStartEnd) expected output is: ['start', 'end'] but I'm getting : [('START', 'END')] using django query how get the output like this ['start', 'end'] -
serving media files in django with a small size
I'm building a Django app (call it Drive) to upload photos (2MB or higher) and use its links in another project. the problem is when uploading all photos on the drive and adding their links in the other project the photos take a lot of time to load, I found a solution to server these photos on the drive itself and compress them when uploading, but still takes a long time to load. this is the serve function: def serve(request, path, document_root=None): file_link = path file = File.objects.get(privacy__link=file_link) rendered_file = FileResponse(file.file) return rendered_file it returns the file as a FileResponse and then it will be returned in its full size and I think that is the problem, and I don't want something like this to happen, I just want to preview the photos with small sizes to load faster on the site. any help? -
Django : GET / HTTP/1.1" 404 2029
I'm a beginner Django. I get his 404 error, couldn't find why. Followed all the instructions step by step. Using Django version 3.1.1. Trying to find solution on google, no help. When I execute python manage.py runserver - I get the following message Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). November 16, 2021 - 06:17:59 Django version 3.1.1, using settings 'lecture3.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: / [16/Nov/2021 06:18:02] "GET / HTTP/1.1" 404 2029 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). November 16, 2021 - 06:25:43 Django version 3.1.1, using settings 'lecture3.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: / [16/Nov/2021 06:25:46] "GET / HTTP/1.1" 404 2029 Error on the page is : Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in lecture3.urls, Django tried these URL patterns, in this order: admin/ hello/ The empty path didn't match any of these. Hello/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index") ] hello/views.py from django.http import HttpResponse from django.shortcuts … -
'OperationalError ' when I insert : owner = models.ForeignKey(User,on_delete=models.CASCADE)
I'm very new in django, when I put this code : ''' owner = models.ForeignKey(User,on_delete=models.CASCADE) ''' the page gives ' OperationalError ' in a position . Is this code wrong, or it needs something ? I need a good new book in django to free download . -
django-admin start project returns command not found on mac with django version 3.10
I just started learning django and to start my first project, I have installed Python version 3.10.0 on mac. created a virtual environment and installed django but when trying to run django-admin startproject myproject in virtual environment, it returns command not found. could this be a bug on the latest version of python or there is something else I should try ? -
How to display rest api using AJAX in Django?
I want to be able to use the REST API below and display data on a single HTML page. This is the API (response) from a database connection function in my Django project. URL: http://127.0.0.1:8000/api/v1/test/ API output: { "message": "Success !", "server": "Connection established from ('PostgreSQL 12.7, compiled by Visual C++ build 1914, 64-bit',)" } I tried to display the data using AJAX. However, the data does not appear on the page. This is my attempt: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>API Calls Demo</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> </head> <body> <div class="container-fluid"> <h3>Test Output</h3> <br></br> <table class="table table-sm"> <tr> <th>Output</th> </tr> <tbody id="divBody"></tbody> </table> </div> </body> <script> $(document).ready(function () { BindConnection(); }); function BindConnection(){ $.ajax({ type:"GET", dataType: "JSON", url: "http://127.0.0.1:8000/api/v1/test", success: function(data){ console.log(data); var str = ""; var totalLength = data.length; for (let i=0; i < totalLength; i++){ str += "<tr>" + "<td>" + data[i].server + "</td>" "</tr>" } $("#divBody").append(str) } }); } </script> Note: The result can be displayed on the console and there is no error. Sorry for my poor attempt, cause I am still new with Django, REST API, and Javascript (AJAX). I have tried several attempts … -
How to download a file from S3 in django view?
The django view function downloads the files: def download(request): with open('path','rb') as fh: response = HttpResponse(fh.read()) response['Content-Disposition'] = 'inline; filename='+base_name_edi return response This function downloads the files. But I want to download the files from S3. How to find the path of the S3 File so that this function works? -
How to create dynamic database per tenant for multitenant application in Django
I building an app which need to have separate database per customer using Django . In my backend , I want to develop this. I will access my database through API. but I can not find any good solution for it. I can not find yet any Django package for it. -
How to preview image before uploading in django
I am trying to preview image before uploading it to the html page. I am using django. This is my model class Product(models.Model): image = models.ImageField(upload_to='uploads/') thumbnail = models.ImageField(upload_to='uploads/') class Meta: ordering = ['-date_added'] this is my form.py class ProductForm(ModelForm): class Meta: model = Product fields = ['image'] and this is my html page <form method="post" action="." enctype="multipart/form-data"> {% csrf_token %} {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.image.errors }} <br> <label for="{{ form.image.id_for_label }}"><br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;Image: &nbsp;</label> {{ form.image }} </div> <div class="field"> <div class="control" style="margin-bottom: 3%"> <button class="btn btn-theme" style="float:right;">SUBMIT</button> </div> </div> </form> I am able to upload and display the image in the html page but i want it so that before i upload i can see the image i am trying to upload. How can i do that? -
ProgrammingError at / not enough arguments for format string
I'm a Django beginner I'm trying to access a table which is already present in mysql database. for that I used - "python manage.py inspectdb" to get the model info as shown below` from django.db import models class Datatable(models.Model): def str(self): return self.ssid family = models.TextField(blank=True, null=True) validcopies = models.BigIntegerField(blank=True, null=True) location = models.TextField(blank=True, null=True) pool = models.TextField(blank=True, null=True) volume = models.TextField(blank=True, null=True) ssid = models.BigIntegerField(blank=True, null=True) cloneid = models.BigIntegerField(blank=True, null=True) savetime = models.DateTimeField(blank=True, null=True) clonetime = models.DateTimeField(blank=True, null=True) clretent = models.DateTimeField(blank=True, null=True) sumflags = models.TextField(blank=True, null=True) clflags = models.FloatField(blank=True, null=True) totalsize = models.BigIntegerField(blank=True, null=True) sumsize = models.TextField(blank=True, null=True) level = models.TextField(blank=True, null=True) name = models.TextField(blank=True, null=True) client = models.TextField(blank=True, null=True) vmname = models.TextField(blank=True, null=True) nfiles = models.BigIntegerField(blank=True, null=True) group = models.TextField(blank=True, null=True) backup_copy_cloneid = models.BigIntegerField(db_column='backup-copy-cloneid', blank=True, null=True) # Field renamed to remove unsuitable characters. scanned_size_bytes1 = models.BigIntegerField(db_column='scanned-size-bytes1', blank=True, null=True) # Field renamed to remove unsuitable characters. post_seg_bytes1 = models.BigIntegerField(db_column='post-seg-bytes1', blank=True, null=True) # Field renamed to remove unsuitable characters. transferred_size_bytes1 = models.BigIntegerField(db_column='transferred-size-bytes1', blank=True, null=True) # Field renamed to remove unsuitable characters. clone_copy_cloneid = models.BigIntegerField(db_column='clone-copy-cloneid', blank=True, null=True) # Field renamed to remove unsuitable characters. scanned_size_bytes2 = models.BigIntegerField(db_column='scanned-size-bytes2', blank=True, null=True) # Field renamed to remove unsuitable characters. post_seg_bytes2 = models.BigIntegerField(db_column='post-seg-bytes2', blank=True, null=True) … -
django views can't access webkitformboundary
i'm trying to send data with ajax to django views here's my js code messageSENDER.onsubmit = () => { formdata = new FormData(messageSENDER); $.ajax({ headers: {"X-CSRFToken": document.querySelector('[name=csrfmiddlewaretoken]').value,}, method: 'POST', processData: false, ContentType: false, data: formdata, url : '/send/message/', success: function(m){ messageSENDER.reset() } }) } in the view function this is the data i get <QueryDict: {'------WebKitFormBoundaryvME3ZcSodJ0Wyw6a\r\nContent-Disposition: form-data; name': ['"csrfmiddlewaretoken"\r\n\r\n7bsMDcWw2yme8P4FC7cEVnkrOuYLR22HFiyrxv9yTOE8rZzZkLta8DvKuf4SNMjt\r\n------WebKitFormBoundaryvME3ZcSodJ0Wyw6a\r\nContent-Disposition: form-data; name="partnerPK"\r\n\r\n2\r\n------WebKitFormBoundaryvME3ZcSodJ0Wyw6a\r\nContent-Disposition: form-data; name="content"\r\n\r\nmessage content\r\n------WebKitFormBoundaryvME3ZcSodJ0Wyw6a\r\nContent-Disposition: form-data; name="files"; filename=""\r\nContent-Type: application/octet-stream\r\n\r\n\r\n------WebKitFormBoundaryvME3ZcSodJ0Wyw6a--\r\n']}> so how to access it's data the view is working just fine with normal html form and postman but not with ajax def CreateMessage(request): pk = request.POST.get('partnerPK') text = request.POST.get('content') partner = User.objects.get(pk=pk) m = Message.objects.create(content=text, receiver = partner, sender=request.user) when i try to print any of the data it says either None or gives empty array -
Rejecting form post after is_valid
I'm attempting to overwrite the RegistrationView that is part of django registration redux. https://github.com/macropin/django-registration/blob/master/registration/backends/default/views.py Essentially, I want to implement logic that prevents the registration from happening if some condition is present. Checking for this condition requires access to the request. I'm thinking that I might be able to subclass the register function within this Class based view. def register(self, form): #START OF MY CODE result = test_for_condition(self.request) if result == False: messages.error(self.request, "Registration cannot be completed.", extra_tags='errortag') return redirect('/access/register') #END OF MY CODE site = get_current_site(self.request) if hasattr(form, 'save'): new_user_instance = form.save(commit=False) else: new_user_instance = (UserModel().objects .create_user(**form.cleaned_data)) new_user = self.registration_profile.objects.create_inactive_user( new_user=new_user_instance, site=site, send_email=self.SEND_ACTIVATION_EMAIL, request=self.request, ) signals.user_registered.send(sender=self.__class__, user=new_user, request=self.request) return new_user What is the correct way to do this using class based views? I've worked almost exclusively with function based views so far. Thanks! -
Problems getting while hosting django app on heroku
Hey there i have just hosted my Django app on Heroku and i faced theses two problem : "Failed to detect app matching no buildpack" Procfile declares types -> (none) and when i run heroku logs --tail i get this 2013-08-31T21:00:25.085053+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path=/favicon.ico host=cristowip.herokuapp.com fwd="189.137.81.39" dyno= connect= service= status=503 bytes= -
Application error - Deploying Django App on Heroku
I am trying to deploy My app on heroku. it is deployed successfully but when I am starting my app with provided link it is showing, Application error An error occurred in the application and your page could not be served. If you are the application owner This is logs which got after triggering heroku logs --app thefitlifegym command :- 2021-11-16T05:30:49.743962+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 850, in exec_module 2021-11-16T05:30:49.743962+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2021-11-16T05:30:49.743962+00:00 app[web.1]: File "/app/Gymnasium/wsgi.py", line 11, in <module> 2021-11-16T05:30:49.743963+00:00 app[web.1]: from notifications.config import get_notification_count, run_notifier 2021-11-16T05:30:49.743963+00:00 app[web.1]: File "/app/notifications/config.py", line 2, in <module> 2021-11-16T05:30:49.743963+00:00 app[web.1]: from members.models import Member 2021-11-16T05:30:49.743963+00:00 app[web.1]: File "/app/members/models.py", line 43, in <module> 2021-11-16T05:30:49.743964+00:00 app[web.1]: class Member(models.Model): 2021-11-16T05:30:49.743964+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/base.py", line 108, in __new__ 2021-11-16T05:30:49.743964+00:00 app[web.1]: app_config = apps.get_containing_app_config(module) 2021-11-16T05:30:49.743965+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/registry.py", line 253, in get_containing_app_config 2021-11-16T05:30:49.743965+00:00 app[web.1]: self.check_apps_ready() 2021-11-16T05:30:49.743965+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/registry.py", line 135, in check_apps_ready 2021-11-16T05:30:49.743965+00:00 app[web.1]: settings.INSTALLED_APPS 2021-11-16T05:30:49.743966+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 83, in __getattr__ 2021-11-16T05:30:49.743966+00:00 app[web.1]: self._setup(name) 2021-11-16T05:30:49.743966+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 64, in _setup 2021-11-16T05:30:49.743966+00:00 app[web.1]: raise ImproperlyConfigured( 2021-11-16T05:30:49.743968+00:00 app[web.1]: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before … -
How to properly design my models for stock manage?
I am seeking for some guidance here. System will have three depart. Owner, ControlUnit, Shop Every depart will have there own stocks. And also shop may request order for stocks with ControlUnit and ControlUnit may request with Owner. Every depart will have there own damaged stock list also. I am thinking of this approach class Owner(models.Model): name = models.CharField() class ControlUnit(models.Model) owner = models.ForeignKey(Owner) name = models.CharField() class Shop(): cu = models.ForeignKey(ControlUnit) name = models.CharField() class CUStock(model.Model): cu_id = models.ForeignKey(ControlUnit) name = models.CharField() price = models.CharField() qty = models.PositiveIntegerField() class CUDamageStock(): cu_stock = models.ForeginKey(CUStock) qty = models.PositiveIntegerField() class CUOffer(): cu_stock = models.ForeignKey(CUstock) offer = models.DecimalField() class CUOrder(): cu_stock = models.ForeignKey(CUStock) qty = models.PositiveIntegerField() order_by_user = models.ForeignKey(User) Similary there will be another 3 table for Owner and Shop. -
Django can't ordering model object to ascending or descending
I am getting this error when trying ordering my model object. my console error: django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: contact.Contact: (models.E014) 'ordering' must be a tuple or list (even if you want to order by only one field). System check identified 1 issue (0 silenced). here is my model: class Contact(MPTTModel): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True,related_name='contact_user') name = models.CharField(max_length=250) email = models.EmailField(max_length=500) subject = models.CharField(max_length=2000,blank=True,null=True) message = models.TextField() created_at = models.DateTimeField(auto_now_add=True,blank=True,null=True) updated_at = models.DateTimeField(auto_now=True,blank=True,null=True) class Meta: ordering = ('-created_at') where I am doing mistake ? -
How to reload a module in django?
I created a file named search_alg_parallel.py. Then I wanted reload this module from another module(another .py file). The problem is that I couldn't directly import the file with the import search_alg_parallel command, so I couldn't use the reload functionality. How can I solve this problem? I thinks this problem relates to django not python. -
What AWS Service I need for Docker Containers and team work
Right now I work as trainee in small IT Company I have a task to write a documentaion for other trainee "How upload our tg bot on AWS" & "How use Docker Containers in AWS" I don't have problems with Docker, because I have a lot of experience with it before, but I never work with AWS. It has a lot of service and I lost in them all What I need? Run a telegram-bot & Django server in Docker container Be able to have all trainee able to run their container Comfortable service to control containers Or if be simple, we need a AWS service to run a Docker Container which Run a telegram-bot and Django Server The question is: What service I need to work with? -
Excel export using loop in Django
I am working a project, which have some information about Customer. I am exporting Excel file using xlwt library. I have a booking list: [<Booking: +6055664554>, <Booking: +6055664554>, <Booking: +6055664554>, <Booking: +6055664554>, <Booking: +6055664554>, <Booking: +6055664554>] My export function: def export_shimpent_xls(request,id): response = HttpResponse(content_type='application/ms-excel') shipment = Shipment.objects.get(pk=id) file_name = "shipment_list_of_"+str(shipment.shimpment_number)+".xls" response['Content-Disposition'] = 'attachment; filename="'+ file_name +'"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Shipment Booking List') bookings_list = shipment.booking_list #taking existing booking list which is already added in shipment bookings = [] if bookings_list: for booking in bookings_list: data = Booking.objects.get(booking_reference=booking) bookings.append(data) # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Ref Number', 'Name', 'Destination', 'Mobile Number', 'Weight','Carton','Payment Mode','Remark','Delivery Status',] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() #issue is there, how can i itterate the bookings to get all value list? rows = Booking.objects.get(booking_reference=bookings).values_list('booking_reference', 'receiver_name', 'receiver_city', 'receiver_phone', 'gross_weight', 'total_carton', 'payment_method', 'comment', 'booking_status') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response I am having stuck on iteration for my bookings variable to get all value list in rows. How can i do that? Please? -
clicking on Anchor link does not jump down to the section of webpage
I have a blog website built using Django and Wagtail, where the blog article URL is http://example.com/posts/blog01 that blog has a few comments, and in HTML template file, each comment is given an id, <div id="c{{comment.id}}"> this is a comment for the blog article </div> But when I navigate to http://example.com/posts/blog01/#c12, it does not jump down to the comment whose id is 12, instead it just displays the blog article, and I have to scroll down to the specific comment. anything wrong for my setup ?