Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I assign a static file to an initial forms.FileField?
I'm trying to initialise a django form FileField with a file from my static directories. I am using a ClearableFleInput widget for the field data_file = forms.FileField( #validators=FileExtensionValidator(allowed_extensions=['xlsx','csv']), label = "Timeseries Data File", widget=forms.ClearableFileInput() ) Within the view I'm trying to set the initial form data as follows: initial_data['data_file'] = open(settings.STATIC_ROOT + '/path/to/data_file.csv','r+') ctx['form'] = EntryForm(initial=initial_data) return ctx All my other initial data items load but not the filefield. Can I do this and if so, how? -
mod_wsgi [wsgi:error] 500 Internal Server Error [ModuleNotFoundError: No module named 'lncRNA' ]
I am trying to deploy a very basic Django application (lncRNA) in our web server.Below is my system version information: [yxu@localhost lncRNA]$ httpd -v Server version: Apache/2.4.6 (CentOS) Server built: Nov 16 2020 16:18:20 [yxu@localhost lncRNA]$ cat /etc/redhat-release CentOS Linux release 7.4.1708 (Core) [yxu@localhost lncRNA]$ which python3 /usr/local/miniconda3/bin/python3 [yxu@localhost lncRNA]$ which mod_wsgi-express /usr/local/miniconda3/bin/mod_wsgi-express The root directory of my lncRNA webpage is /var/www/html/lncRNA I can start my django server directly with python manage.py runserver, and I can also get my page http://127.0.0.1:8000/. But when I use mod_wsgi-express start-server wsgi.py --port 8080 or configure Apache also gets theI get the 500 Internal Server Errorfollowing error Log: [Wed Dec 16 16:42:30.358252 2020] [mpm_prefork:notice] [pid 27037] AH00170: caught SIGWINCH, shutting down gracefully [Wed Dec 16 16:42:31.459802 2020] [core:notice] [pid 28101] SELinux policy enabled; httpd running as context system_u:system_r:httpd_t:s0 [Wed Dec 16 16:42:31.461239 2020] [suexec:notice] [pid 28101] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Wed Dec 16 16:42:31.496036 2020] [lbmethod_heartbeat:notice] [pid 28101] AH02282: No slotmem from mod_heartmonitor [Wed Dec 16 16:42:31.522556 2020] [mpm_prefork:notice] [pid 28101] AH00163: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/5.4.16 mod_wsgi/4.7.1 Python/3.8 configured -- resuming normal operations [Wed Dec 16 16:42:31.522581 2020] [core:notice] [pid 28101] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' [Wed Dec 16 16:42:51.869513 2020] … -
Issues with Django form select field that queries the ORM when there is no migrated database?
I have a Django form which can be simplified to: class QuestionAnswerForm(ModelForm): class Meta: model = QuestionAnswer exclude = [...] widgets = { "link": Select( choices=[(None, "[none]"), ("summary", "Summary")] + [ (question.question_no, question.question_no) for question in Question.objects.all() ] ), ... } The choices for the link field are retrieved from a database query. However, this does not work when building a new environment where the database has not yet been migrated. It would make sense to migrate the database, but running python manage.py migrate results in a stack trace ending in: django.db.utils.ProgrammingError: relation "decision_tree_question" does not exist LINE 1: ..._tree_question"."display_answers_vertically" FROM "decision_... It seems that running this causes Django to attempt to populate this form field with the results of a database query before migrating the database! Amending the form to not include the database query fixes this issue: class QuestionAnswerForm(ModelForm): class Meta: model = QuestionAnswer exclude = [...] widgets = { "link": Select( choices=[(None, "[none]"), ("summary", "Summary")] ), ... } but I obviously want this. Am I getting the choices from the database correctly? Is there a better way to achieve the same thing without causing this issue? -
When i add the order from AdminPanel in django i got this error
Error:AttributeError at /admin/store/order/add/ 'bool' object has no attribute 'utcoffset' This is my models.py class Order(models.Model): o_id=models.AutoField(primary_key=True) o_date=models.DateTimeField(default=True) o_address=models.CharField(max_length=250,null=True) o_amount=models.FloatField() user=models.ForeignKey(User, on_delete=models.SET_NULL,null=True,blank=True) -
save django model queryset into another model
I have two Django models class Invoice(models.Model): id = models.IntegerField() is_converted = models.BooleanField(default=False) this model keeps the information about invoices and quotations and another model containing items details of particular invoice/quotation class Items(models.Model): document = models.Foreignkey(Invoice, on_delete=models.CASCADE) price = models.DecimalField(max_digits=8, decimal_places=2) name = models.CharField(max_length=50) now I want to convert the quotation record from model Invoice to Sales Invoice I have copied the data from the Invoice model row into another row (as I want to keep the Quotation record also) My problem is copying items from the Item model of quotation record into a newly generated invoice record. I've tried this quotation_items = Items.objects.filter(document=id) this returns normal queryset <QuerySet [<items: items object (238)>, <items: items object (240)>, <items: items object (241)>]> Now I want to save these records into the Items model for the converted invoices. Is there any way of saving querysets into Django models? -
Trouble with send form (nginx+django+ajax), upstream prematurely closed connection
I have problems using the send form on my website. I am using nginx + django + ajax. The form worked fine for more than a year, but suddenly it stopped working and now when a try submit the form i get nothing. In the nginx error log i see "upstream prematurely closed connection while reading response header from upstream". Here is the code: Ajax: $('#send_form').submit(function (e) { e.preventDefault(); $.ajax({ type: 'get', url: '/send', data: $(this).serialize(), success: function () { alert('form was submitted'); } }); }); Django from django.views.generic import View from django.http import HttpResponse from django.core.mail import send_mail from django.template.loader import render_to_string from django.conf import settings class Send(View): def get(self, request, *args, **kwargs): print(request.GET) message = render_to_string('email.html', {'data': request.GET}) send_mail( 'New message on site xxxxx.ru, message, settings.DEFAULT_FROM_EMAIL, [settings.EMAIL_DEFAULT_TO], fail_silently=False, ) return HttpResponse(status=200) Nginx: events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 150; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/sites-enabled/*.conf; server_names_hash_bucket_size 64; server { listen 80; server_name xxxxx.ru; location /static/ … -
Compare data faster in Django
I have a model with phone_number and I'm comparing this phone number with phone_number column uploaded in csv file from user. I'm fetching all data from DB, converting Django-query to Pandas Dataframe and comparing. This works, but takes too much time - Especially fetching and conversion of data to the Dataframe takes a lot of time. Is there a way to make this processing faster? For example comparing without conversion or so? BTW.main_dataframe (user's csv) doesn't need to be strictly Dataframe. Or maybe finding values in DB instead of fetching all DB data? def process(self): main_dataframe = pd.read_csv(self.save_path + "/" + self.file_name, encoding='cp932', dtype={self.main_col: object}) # loading csv file main_dataframe = self.cleaner(main_dataframe) # cleaning data from errors all_hikanshou_db = pd.DataFrame(list(Hikanshou.objects.all().values())) # getting data from DB(postgress) and converting it to DF m1 = main_dataframe[self.main_col].isin(main_dataframe['phone_number']) # comapring main_dataframe['compared_phone_number'] = main_dataframe[self.main_col].where(m1) main_dataframe.to_csv("abc.csv", index=False, encoding="cp932") -
Django - Q lookup search is slow for over a million records in MySQL
I have a Django application which involves a search in the database table and filters out all the results and data. models.py class TableData(models.Model): field1 = models.CharField(max_length=254, unique=True, null=False) field2 = models.CharField(max_length=254) field3 = models.CharField(max_length=254) field4 = models.CharField(max_length=254) field5 = models.CharField(max_length=50) field6 = models.CharField(max_length=10) field7 = models.CharField(max_length=10, null=False, default='200') slug = models.SlugField(max_length = 254, unique=True) search_qs = models.CharField(max_length=254, default='N/A') views.py def search(request): searchquery = request.GET.get("q") if searchquery: all_queryset_list = TableData.objects.all() queryset_list = all_queryset_list.filter(Q(search_qs__icontains=searchquery)) paginator = Paginator(queryset_list, 25) page = request.GET.get('page') searchres = paginator.get_page(page) res_count = queryset_list.count() context = { 'searchres': searchres, 'res_count': res_count, } return render(request, 'results.html', context) Here everything works fine as expected, but the searched results takes too much of time for the table having over a million records. How can I optimize the query to get the results faster ? Really appreciate for anyone who can help me this. -
How to do filtering in DateTime as null in Django rest framework?
I just want to build the filtering API with Django rest framework. One field is datetime2. I want to filter the records that have NULL value as datetime2. Here is my models.py ruleend = models.DateTimeField(db_column='RuleEnd', blank=True, null=True) Here is my serializer.py class ProductPriceSerializer(serializers.ModelSerializer): class Meta: model = ProductPrice fields = ['pricingruleid', 'productkey', 'productcode', 'customerid', 'customerchain', 'productpriceusd', 'rulestart', 'ruleend', 'creatorupn', 'created', 'customername', 'productdescription'] Here is views.py class ProductPriceViewSet(viewsets.ModelViewSet): serializer_class = ProductPriceSerializer pagination_class = pagination.PageNumberPagination filter_backends = [DjangoFilterBackend, filters.OrderingFilter] filterset_fields = ['customerid', 'customername', 'productkey', 'productdescription', 'ruleend', 'rulestart'] ordering_fields = ['customerid', 'productkey', 'rulestart'] def get_queryset(self): self.pagination_class.page_size_query_param = 'page_size' return ProductPrice.objects.all() urls.py path('productprice/', ProductPriceViewSet.as_view({'get':'list','post':'create'}), name="product-price"), This makes me implement pagination, filtering and sorting very easy. But I have one problem. I need to filter the records that have the null value in ruleend. What is the valid date/time of null? Or should I add something to my backend? -
Finding available workers for each date
In my application I have to display how many workers are available on each day from the current date to a year in advance. I have trouble figuring out how to do 2 things 1. How to calculate how many people are available The way I set it up is I create a new model object each time a worker is assigned to work on a project. There are multiple projects going on at the same time and workers only assigned to one project at a time. Model looks like this -> class AssignedToProject(models.Model): worker = models.ForeignKey(Worker, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) start_date = models.DateField(auto_now=False, auto_now_add=False) end_date = models.DateField(auto_now=False, auto_now_add=False) def __str__(self): return str(self.worker) + " - " + str(self.project) I had a few ideas how to go about this but none of them seem quite right. To create a string with length 365 that consists of 1s and 0s depending on whether the worker is available that day. Then I would just get availability strings for all workers and add them up for each day and that would give me a number telling me how many people are available that day. Problem with this is I think I would … -
What is the django version of "flask.request.url"?
I was just converting a code from flask to django and I was wondering what should I use in django instead of flask.request.url. -
How to download a newly created csv file in django?
I have created a django application that converts txt to csv files. Now, I want to create a view function to download the newly converted csv files. Any suggestions will be highly appreciated. views.py def submit(request): # this function converts txt to csv files. For example abcd.txt is converted into abcd0000.csv and abcd0000.csv is stored in /main/temp/ folder. Now I have just created the download function which is wrong. def download(request): file_path = os.path.join(BASE_DIR, 'main/temp/??') if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read()) response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 What should be the correct way to write the newly created path for the csv file that it downloads the newly created csv file? And also please suggest what should I write in urls.py to route to download view? -
In wagtail, wanna show user profile. if already user created means wanna show profile data, otherwise wanna show profile form
I already created user profile table for storing. now how can I redirect from same option to user profile data if already user data exist in table. -
Models aren’t shown in django admin
I am currently working on a science django blog. I've finished coding it all and I realized that the models items overview and content don't appear in my django.admin. Here's an image so you can see. I know there are other threads related to it. However, I couldn't find the solution in those. Models.py: class Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) content = HTMLField() author = models.ForeignKey(Author, on_delete=models.CASCADE) thumbnail = models.ImageField() categories = models.ManyToManyField(Category) featured = models.BooleanField() previous_post = models.ForeignKey( 'self', related_name='previous', on_delete=models.SET_NULL, blank=True, null=True) next_post = models.ForeignKey( 'self', related_name='next', on_delete=models.SET_NULL, blank=True, null=True) Admin.py: from django.contrib import admin from .models import Author, Category, Post, Comment, PostView # Register your models here. admin.site.register(Author) admin.site.register(Category) admin.site.register(Post) Settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'crispy_forms', 'tinymce', 'marketing', 'posts' ] And urls.py: urlpatterns = [ path('admin/', admin.site.urls), By the way, the models.py is in the app Posts. Just in case somebody needs this information. Also, the other models like author, category and featured are seen normally. -
i want to set maximum quantity but getting error
I am trying to add maximum quantity.Here is my code : def post(self, request): product = request.POST.get('product') cart = request.session.get('cart') remove = request.POST.get('remove') if cart: quantity = cart.get(product) if quantity: if remove: cart[product] = quantity - 1 else: cart[product] = quantity + 1 else: cart[product] = 1 if cart[product] < 1: cart.pop(product) else: cart = {} cart[product] = 1 request.session['cart'] = cart return redirect("cart/") here when I try if quantity <= 2 i get this error <= not supported. So I think there will be better way to set maximum quantity. Can someone please help? -
could not enter into if condition: if request.method == 'POST':
I have used Django 2.2 to build a website, however the if condition: "if request.method == 'POST': " could not be hit in the if condition. view.py: def check_discilpine(request): if request.method == 'POST': discipline_name=request.POST.get('discipline_name') dropdown_semester=request.POST.get('dropdown_semester') dropdown_year = request.POST.get('dropdown_year') print("-----------------------------------------------") print(discipline_name, dropdown_semester, dropdown_year) return render(request,'specific-semester.html', context={'discipline_name': discipline_name, 'dropdown_semester': dropdown_semester, 'dropdown_year': dropdown_year}) html: <form method="post" action="{% url 'bms:content_checklist_for_discipine_info' %}"> {% csrf_token %} <div class="row"> <div class="px-3"> <div class="d-sm-flex align-items-xl-stretch justify-content-between mb-4"> <h1 class="h4 mb-0 text-gray-800">&nbsp;&nbsp;Creating Content Checklist for:</h1> <select id="dropdown_semester_0" name="dropdown_semester_0" > <option value="">--Dropdown January or July--</option> <option value="Dropdown_Jan">January</option> <option value="Dropdown_Jul">July</option> </select> <select id="dropdown_year_0" name="dropdown_year_0" > <option value="">--Calender year since 2020--</option> <option value="Dropdown_2021">2021</option> <option value="Dropdown_2022">2022</option> <option value="Dropdown_2023">2023</option> <option value="Dropdown_2024">2024</option> <option value="Dropdown_2025">2025</option> <option value="Dropdown_2026">2026</option> <option value="Dropdown_2027">2027</option> <option value="Dropdown_2028">2028</option> </select> </div> </div> </div> <div class="row"> <div class="px-3"> <div class="d-sm-flex align-items-xl-stretch justify-content-between mb-4"> <h1 class="h4 mb-0 text-gray-800">&nbsp;&nbsp;Content Checklist(s) for Discipline:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</h1> </div> </div> <select name="discipline"> {% for discipline in query_results %} <option value="{{ discipline.name }}" name="discipline_name">{{ discipline.name }}</option> {% endfor %} </select> </div> <br> <br> <div class="col"> <label class="radio-inline"> <input type="radio" name="optradio" value="notspecific" checked>&nbsp;Latest Available Semester </label> <label class="radio-inline"> <input type="radio" name="optradio" value="specific">&nbsp;Specific Semester </label> <select id="dropdown_semester" name="dropdown_semester" > <option value="">--Dropdown January or July--</option> <option value="Dropdown_Jan">January</option> <option value="Dropdown_Jul">July</option> </select> <select id="dropdown_year" name="dropdown_year" > <option value="">--Calender year … -
Heroku Slug Size Too Large due to Keras [closed]
I'm deploying my app to heroku however their free tier only allow < 500MB packages, I'm currently using tensorflow and it takes > 500 MB, I can downgrade it to lower version or use the tensorflow-cpu instead, however, I'm also using Keras, which requires at least tensorflow=2.2.0 (so size > 500MB). I want to be able to use Keras while the size of my packages < 500MB. I have looked into these two questions but somehow downgrading Keras causes a lot of imcompatible issues. Deploy python app to Heroku "Slug Size too large" Error "Keras requires TensorFlow 2.2 or higher" -
nested annotations django with OuterRef
I want to annotate a field based on another queryset. return real_instances.annotate( submitted_count=user_enrolments.filter(course_progresses__module_progresses__module__id=OuterRef('id')).annotate( submitted_attempt=Exists( AssignmentModuleProgress.objects .filter( Q(module_progress__module__id=OuterRef(OuterRef('id'))) Q(module_progress__user=OuterRef('user')) & Q(module_progress__module_progress_course_progresses__course_progress_userenrolments__id=OuterRef("id")), is_submitted=True) )).filter(submitted_attempt=True).count(), Here i have a QuerySet by the name real_instances and i want to annotate a field submitted_count in it . user_enrolments is another queryset and im annotating another field in it by the name submitted_attemmpt to finally get my count . Here im having issue with OuterRef(OuterRef('pk')) which refers to the id of the real_instances object in iteration. Im getting the error: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. -
How to pass Django filtered object to views( xls download)?
I am trying to pass the filter object to my view function which is responsible to download data into .xls format(Earlier I am directly using the Model name so I am getting all the records.). My requirement is when the user will apply any filter then that object data should be pass to download views. Please find the below code. filter.py class Shift ChangeFilter(django_filters.FilterSet): id = django_filters.NumberFilter(label="DSID") class Meta: model = AAChange fields = ['ConnectID', 'EmailID','id','SerialNumber','Project_name','Shift_timing'] function in views.py to download DB records: ###########for Downloading ############### from django.utils import timezone now_aware = timezone.now() import xlwt,openpyxl def exportgen_data(request): model=ShiftChange allgen = ShiftChange.objects.all() gene_filter = ShiftChangeFilter(request.GET,queryset=allgen ) allgene = gene_filter.qs print('download:',allgene) response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="Gene_ShiftTiming.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('GenShiftChange Data') # this will make a sheet named Users Data # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['id', 'AConnectID', 'Shift_timing', 'EmailID', 'Vendor_Company', 'Project_name', 'SerialNumber', 'Reason', 'last_updated_time'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # at 0 row 0 column # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = allgene.values_list('id', 'AConnectID', 'Shift_timing', 'EmailID', 'Vendor_Company', 'Project_name', 'SerialNumber', 'Reason', 'last_updated_time') for row in rows: row_num += 1 for col_num in … -
how to take the hostname or base url
how to get a running base url? in admin.py, new function/method def your_api(self, object_id): """ Function save your api """ # print(reverse('admin:index')) parameters = Parameter.objects.filter(agregator=object_id) concate_endpoint_api = '' for parameter in parameters: if parameter.flag == 'NO': concate_endpoint_api += '{}{}={}'.format(BASE_URL, parameter.keys, parameter.values if parameter.values else 'None') concate_endpoint_api += '&' return concate_endpoint_api example javascript windows.location.origin http://example.com or http://localhost or http://127.0.0.1:8000 -
How to have a form in a DetailView page in django?
I'm building a really simple twitter clone with django. I have a TweetDetailView like this: class TweetDetailView(LoginRequiredMixin,DetailView): model = Tweet context_object_name = 'tweet' template_name = "twitter/tweet.html" What I want is a form for commenting on a tweet that appears on the TweetDetailView page. Can a django DetailView handle forms? Or should I use a function based view for this detail page? Any help is appreciated. -
Django, How to paginate a JsonResponse?
I'm working on a Django and JavaScript project. I'm aware that without JavaScript APIs the pagination would be much easier, but now I'm too far down the rabit hole :) My views.py from django.http import JsonResponse def post_list(request): posts_list = Post.objects.all() posts = [p.serialize() for p in posts_list] return JsonResponse(posts, safe=False) My JavaScript fetch('/post_list') .then(response => response.json()) .then(posts => { print_post(posts); }); Then the print_post function does its magic and finishes by appending all posts to a div. My HTML <div id="to_attach_post_1"></div> So, all posts print nicely in one page. However, if I have hundreds of posts that would not look nice, right? so I have to paginate the posts, lets say every 10 posts, while still sending a JsonResponse with the posts. Does anyone know how to paginate this? -
Django Not Found: /virtual/Scripts/dashApp/static/main.css
I have looked through SO and this seems to be a common issue among new django users however none of what I have attempted has fixed my issue. after running dev server http://127.0.0.1:8000/ I get not found error in CMD window Not Found: /virtual/Scripts/dashApp/static/main.css Not Found: /virtual/Scripts/dashApp/static/main.js the relevant html in my app as below <link href= virtual/Scripts/dashApp/static/main.css rel="stylesheet"></head> <script type="text/javascript" src= virtual/Scripts/dashApp/static/main.js ></script> both the .css and .js file live in C:\Users\James\Desktop\Scripts\django\dealerDash\virtual\Scripts\dashApp\static my settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR , 'static') I have tried wrapping virtual/Scripts/dashApp/static/main.css as "virtual/Scripts/dashApp/static/main.css " and /virtual/Scripts/dashApp/static/main.css but without joy.. -
Get the top n rows of each day from same table in Django
I am sure this is not a novel/new problem. I really tried to look into other solutions. However, I could not find how to solve this. I have a model like class Deal(models.Model): title = models.CharField(max_length=1500) viewCounter = models.SmallIntegerField(default=0) thumbsUpCounter = models.SmallIntegerField(default=0) createDateTime = models.DateTimeField(auto_now_add=True) Now I want to get top 10 (or less) deals ordering by thumbsUpCounter and viewCounter of every day. I tried to look into the Subquery and Outerref. However, I could not figure out how can I get the right results. ** I am using MySQL. Thanks in advance. -
Django url pattern to pass a date parameter [duplicate]
I'm passing date parameters "check_in" and check_out" from one view to another through URL. Right now, my url pattern defines them as string (ie, str:check_in), so I get something like this. http://127.0.0.1:8000/checkout/2020-12-16/2020-12-25 It works but it's not ideal; what if someone edited the url with other strings that are not dates? Is there a way for the url to throw an error if the pattern for a date is not respected or recognized? urls.py path('checkout/<str:check_in>/<str:check_out>', views.check_out, name='check_out') views.py def check_out(request, check_in, check_out): ...