Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is there a way simillar to this way to save files (.docx, pdf...) in django?
I've been lately wondering how to save file for each user using django , i kinda thought about this way: the html page: <form acrion ="{% url 'register'%}"> name: <input type="text" name ="name"> resume: <input type="file" name ="myfile"> <input type="button" value="signup"> </form> the modes.py file: class someOne(models.Model): name = models.CharField(max_length = 200) resume = models.FielField(upload_to="wherever i want") the views.py file def register(request): if request.method == 'POST': name = request.POST['name'] resume = request.POST['resume'] new_user = someOne(name,resume) new_user.save() is there anyway should be easy like this or i need to search another way hope you guys undrestand me thanks. -
How to store a phone number in Django model?
I want to store a user's phone number in my model but don't know which format to store it in. What's the best practice when it comes to storing phone numbers and how can it be processed easily via a registration form (and through serializers etc...)? I am new to Django so I need some advice concerning this. Thank you -
what problems. does not display comments django
vews from django.shortcuts import render from .models import Article, Comment from django.http import HttpResponseRedirect, Http404 from django.urls import reverse def index(request): latest_articles_list = Article.objects.order_by('-pub_date')[:5] return render(request, 'articles/list.html', {'latest_articles_list': latest_articles_list}) def detail(request, article_id): try: a = Article.objects.get( id = article_id ) except: raise Http404('Статья не найдена') latest_comments_list = a.comment_set.order_by('-id')[:10] return render(request, 'articles/detail.html', {'article': a, 'latest_comments_list':latest_comments_list}) detail {% if latest_comments_list %} {% for c in latest_comments_list %} <p> <strong>{{c.author_name}}</strong> <p>{{c.comment_text}}</p> </p> {% endfor %} {% else %} Комментарии не найдены! {% endif %} -
Unable to edit the django table
Unable to perform the update operation. This function is for table update, but the code is not allowing me to pass the instance in the form because it is not a model form. Please suggest the changes. view.py @login_required def update(request, employee_id): alldrivers= Driver.objects.get(employee_id=employee_id) form = AddDrive`enter code here`rForm(request.POST) if form.is_valid(): form.save() return redirect("/fleet/driver/list_drivers/") return render(request, 'add_drivers.html', {'form':form}) forms.py class AddDriverForm(forms.Form): SHIFT_CHOICES = ( ('D','DAY'), ('N','NIGHT') ) ADMISSION_FORM_STATUS = ( ('Y','YES'), ('N','NO') ) FORM_COMPLETE_STATUS = ( ('Y','YES'), ('N','NO')) TRAINING_STATUS = ( ('Y','YES'), ('N','NO') ) STATUS = ( ('W','WORKING'), ('OL','ON_LEAVE'), ('E','EXIT') ) employee_id = forms.CharField(max_length=8,required=False) employer_id = CompanyModelChoiceField(required=False, queryset=Company.objects.all(), label='Employer', widget=Select2Widget) name = forms.CharField(max_length=255) uber_name = forms.CharField(max_length=255, required=False) mobile = forms.CharField(max_length=20, required=False) alternate_number = forms.CharField(max_length=20, required=False) salary_plan = forms.CharField(max_length=100, required=False) city_id = CityModelChoiceField(required=False, queryset=City.objects.all(), label='City', widget=Select2Widget) location_id = LocationModelChoiceField(required=False, queryset=Location.objects.all(), label='Location', widget=Select2Widget) present_address =forms.CharField(max_length=255, required=False) permanent_address = forms.CharField(max_length=255, required=False) source = forms.CharField(max_length=100, required=False) add.html <form role="form" method="post" action="{% url 'add_drivers' %}" autocomplete="off"> {% csrf_token %} <table style="width:50%"> {{ form.as_table }} </table> <div class="box-footer"> <button type="submit" class="btn btn-primary"> <span class="glyphicon glyphicon-ok-circle"></span> <span id="btn_txt">Save</span> </button> </div> </form> here i am trying t edit the table I want to update the table but it's not fetching the data, redirecting to the fresh new form … -
How to make an average from values of a foreign key in Django?
I have a book model and a review model like this in Django: class Book(models.Model): ratings = models.FloatField() class Review(models.Model): book = models.ForeignKey( Book, on_delete=models.CASCADE, related_name='reviews', ) review = models.CharField(max_length=5000) score = models.PositiveSmallIntegerField(null=True, blank=True, validators=[MinValueValidator(0), MaxValueValidator(10)]) How can I create a method in Book to calculate the ratings (which is the average from all Reviews associated to a specific book)? -
How to add Multiple items in Django Inventory Management System using Django Model Form
I tried to develop an Inventory Management System in Django. Here, i got a problem. In order, i can easily add single items. But i want to add multiple items under one invoice number. So, how can i do this? Here is my code link below: models.py: https://paste.ubuntu.com/p/pRGSPH9Xg6/ views.py: https://paste.ubuntu.com/p/FHjCfMn52w/ forms.py: https://paste.ubuntu.com/p/WCzXpZznRb/ Customer, Delivery Date, Ref No everything will be once. But product, price, quantity and discount price will be multiple times which i want. So, how can i do this? Thanks in Advance. -
dateutil conflict with django
to begin with, Merry Christmas. Here is the question: an error occurs when i import pandas: dateutil: No module named 'dateutil' So i installed dateutil, which is successfully installed, with pip: pip3 install python-dateutil but when i run my django project i got error like this: Watching for file changes with StatReloader Performing system checks... Exception in thread Thread-1: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 573, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/usr/lib/python3.5/threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 398, in check for pattern in self.url_patterns: File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 580, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'django_project.urls' does not appear to have … -
UnixDateTimeField not working as expected
I am using UnixDateTimeField to return integer but it is not working as expected or I am doing something wrong here is model class TimeStamp(models.Model): created_at = UnixDateTimeField(auto_now_add=True) updated_at = UnixDateTimeField(auto_now=True) class Meta: abstract = True I inherit this model into every model and when I call it in the shell i.e p = MyModel.objects.all().first() p.created_at and it returns like that datetime.datetime(2019, 12, 25, 19, 59, 44, tzinfo=<DstTzInfo 'Europe/London' +01+1:00:00 STD>) (imaginary timezone) not return integer something like this 543116432121 (imaginary integer) How to solve this problem? Thank you in advance! -
How to implement customized form with CreateView class
I would like to build creation object form using CreateView class , but when using it i don't have much customization ,at least i don't know how html code <form action="" method="POST"> {% csrf_token %} {{ form.as_p}} </form> I know i can add some bootstrap class like from django.forms import TextInput, Textarea class MyForm(modelForm): class Meta: widgets = { "name": TextInput({"class": "form-control"}), "comment": Textarea({"data-validation": "validate"}), } But i don't know hot do more "complex" staff like input-group-prepend with icon and get eventually form similar to image attached in example [form example1 Please advice Thanks -
How do I use Django default password reset mechanism into a custom view?
I have some custom registration logic in my project and I want it to work this way: Someone requests access using special page (Implemented) New User is created. (Implemented) Server sends an email using Django's send_mail with a single-use link to a password setup page. (Yet to be implemented) What's the simplest way to create a single-use link and/or password reset token this using Django's default password reset mechanism? -
Unable to log in as superuser on Django project
I am learning Django in order to create a small website, and I am still fairly new to coding. I have an issue with the creation of superusers within the integrated Django admin module. I have followed the tutorials from OpenClassrooms, SimpleIsBetterThanComplex and tried to go through the official Django documentation but without success: I am not able to log in as a superuser After I create a superuser, I cannot access the admin login page: http://localhost:8000/admin. I receive the following error: "Website is unaccessible. Localhost did not authorize the connection. ERR_CONNECTION_REFUSED" and this interrupts my "python manage.py runserver" command. I get the following in the CMD: "GET /admin/ HTTP/1.1" 302 0 "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1913 "GET /admin/ HTTP/1.1" 302 0 "GET /admin/login/?next=/admin/ HTTP/1.1" 200 1913 "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 (env) C:\Users\Me\fmg3\fmg3\ If I delete the database from my project folder and apply migrations, I can access the /admin page again, so I guess that there is something wrong happening when I am creating the superuser, but then of course I cannot login anymore with the superuser created as I guess the credentials were in the database. Below is the code of my settings.py """ Django settings for … -
Passind data to Django view using Python requests
In my Django view, i'm creating a system where an user submits a form or a button. After that, my Django view sends a request to an external Python script, this script receives the request, retrieves some data about that user and sends this data as a response to the Django view, which will perform some operations with this data (show it to the user and so on), all of that is made using Python-Requests. So the external Python script works like a microservice. I'm able to send the request, and i also managed to make my view receive the response from the external Python script, i only have a problem with authentication. Here is how i send data to the Django view: import json import requests session = requests.session() token = session.get('http://127.0.0.1:8000/loginview/') session.post('http://127.0.0.1:8000/loginview/', data={ 'username': 'USER', 'password': 'PASSWORD', 'csrfmiddlewaretoken': token}) token = session.get('http://127.0.0.1:8000/myTestView/') data = json.dumps({'test': 'value'}) session.post('http://127.0.0.1:8000/myTestView/', data={ 'csrfmiddlewaretoken': token, 'data': data}) This is what happens here: a request with some credentials is sent, then the login view authenticates those credentials, if the credentials are authenticated, the data is printed by myTestView. Here are my views: @login_required def myTestView(request): if request.method == 'POST': data = request.POST.get('data') print(json.loads(data)) print('received.') … -
Paginator unwanted shuffle queryset
I have a queryset of products that is sorted by exist flag. but after passing it to paginator, it shuffles products to an unwanted sorting. products = products.order_by('-exist_flag') paginator = Paginator(products, 12) try: page_num = int(page_num) except (TypeError, ValueError): page_num = 1 try: page = paginator.page(page_num) except InvalidPage: page_num = 1 page = paginator.page(1) products = page.object_list after running this code, products is not sorted. -
Inheritance in Django model vs template usage
I am quite new to Django framework. I have a question(problem) to solve. I have model design: Class "Pet" is abstract class. Three classes inherit from Pet: - Dog - Cat - Bird Also there is a class Registration that has foreign key linked to Pet that can be any of those three kind of Pets. Could you help me what is the best practice to design a database structure like this and how to deal with it using Django template framework? -
How can I fetch data from a website to my local Django Website?
I am rather new to Django and I need to fetch some data from a website. For example I want the top ten posts of the day from Reddit. I know of a "request" module for the same.But I am not sure where and how should I implement it and will it be important to store the data in a model or not. -
DRF+VueJS pagination wrong number of pages
I am trying to use DRF pagination backend and VueJs Frontend. I am trying to create pagination links but until now i only get first number. I have added PageNumberPagination to my settings.py. After articles viewset: class ArticleViewSet(viewsets.ModelViewSet): queryset = Article.objects.all() lookup_field = "slug" serializer_class = ArticleSerializer permission_classes = [IsAuthenticated, IsAuthorOrReadOnly] pagination_class = PageNumberPagination I have used Bootstrap-Vue Pagination <div class="col" id="article-list" :articles="articles" v-for="article in articles" :key="article.pk" :per-page="perPage" :current-page="currentPage">...</div> <b-pagination v-model="currentPage" :total-rows="rows" :per-page="perPage" aria-controls="articles-list" ></b-pagination> and VueJS script: export default { name: "ArticleList", components: { HelloWorld, } , data() { return { articles: [], next: null, loadingArticles: false, perPage: 2, currentPage: 1, size:2, } }, methods: { getArticles() { this.loadingArticles = true; let url = "http://localhost:8000/api/articles"; axios.get(url) .then(response => { this.articles = response.data.results; }); }, }, computed: { rows() { console.log(this.articles.length); return this.articles.length; } }, created() { this.getArticles(); }, }; If i check the api address in the browser, I can see the next and previous data. { "count": 4, "next": "http://localhost:8000/api/articles/?page=2", "previous": null, "results": [...] } How do I change the data of total-rows to make pagination work? Thanks -
creating django update form with ajax
I'm creating a django app where user can take part in course, but before it he or she have to 'subscribe' this course. From the logical point of view it is only adding course to his/her profile. It seems to be easy but I have two problems whitch I can't fix. First is how to build form which only add next course to profile intead of replace previouly added. The second issue is connected with ajax, I'm new into ajax so I don't know how it works in 100%. I want to open the same page, but when I submit form, the new site is opened, where 'data' dictionary is printed. Here is my models, views, forms and html file class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) projects = models.ManyToManyField(Project, null=True) class ProjectReadView(BSModalReadView): model = Project template_name = 'projects/project_shortcut.html' def post(self, request, pk): if request.method=='POST': project = Project.objects.filter(pk=pk) obj = Profile.objects.get(user=self.request.user) obj.projects.set(project) obj.save() data = {'is_valid': True, 'project': str(project),} else: data = {'is_valid': False} return JsonResponse(data) class TakePartForm(forms.ModelForm): class Meta: model = Profile fields = ['projects'] widgets = {'projects': forms.HiddenInput()} <form method="post" action=""> {% csrf_token %} {% for field in form %} <div class="form-group{% if field.errors %} invalid{% endif %}"> <label … -
Unable to load Static files using Django
Tried loading static files: CSS, Javascript using django static tag None of the Javascripts is working, and most of the css are also not loaded Error for Javascript(for all JS): The script from “http://127.0.0.1:8000/static/jquery.min.js” was loaded even though its MIME type (“text/html”) is not a valid JavaScript MIME type. Django version: - 3.0.1 My files and code: Base.html>> {% load static %} <link rel="stylesheet" type="text/css" href={% static 'animate.css' %}> <script src="{% static 'jquery.min.js' %}"></script> settings.py>> # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] STATIC_ROOT = os.path.join(BASE_DIR, "assets") I am not using any virtual environment. My project folder tree. My project Folder and sub directories -
Aggregating # of distinct dates across OneToMany relationships using Django's ORM
I have two Django models; MonitoringPeriod and AssignmentPeriod. Both models are defined with start_date and end_date fields. Business logic is such that a MonitoringPeriod can be covered by one or more AssignmentPeriod instances, which may or may not cover the entire range defined by the start and end of the MonitoringPeriod, and may or may not overlap. A MonitoringPeriod would be classed as "fully covered" if all dates between its start_date and end_date are included in the set of dates specified by its related AssignmentPeriods (duplicated dates only counted once). Classes are defined as: class MonitoringPeriod(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) start_date = models.DateField(default=now) end_date = models.DateField(default=get_future_date_default) class AssignmentPeriod(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) start_date = models.DateField(default=now) end_date = models.DateField(default=get_future_date_default) monitoring_period = models.ForeignKey("MonitoringPeriod", on_delete=models.CASCADE) I have also defined an auxiliary DateHelper model which is used in my current solution using raw SQL: class DateHelper(models.Model): date = models.DateField(primary_key=True, editable=False, default=dt.date.today) The problem statement is therefore how to identify/flag MonitoringPeriod rows which are not "fully covered" by AssignmentPeriod instances. These cases are identifiable by the fact that the count of unique dates between the start_date and end_date of the MonitoringPeriod (ie., the RequiredCoverage) is greater than the count of unique dates across … -
How to remove a time from a django DateTime query set?
I am currently querying out Date Time data from my database in order to pass it into a chart.js function as labels. This is the querying code: sales_project_closing_date_data = Sales_project.objects.values_list('sales_project_closing_date').filter(sales_project_status = 'p4') I am keen on only displaying the date and not the time , however i dont seem to be able to do it. Using the trunc function gives me the error : Object of type TruncHour is not JSON serializable In order to resolve that , I enveloped the object with another function to serialize it. Here is the error i got 'TruncHour' object is not iterable Any form of help would be greatly appreciated! -
Wagtail | multilingual content by duplicating the page tree - Duplicate locale in URL
Goal: Setup a very simple starting point for building a website with content editable in 2 languages. Meaning: Have 2 home pages, 1 for each language. When visiting the main URL, visitor should be redirected to 1 of those 2 home pages (depending on language settings). Be able to switch between those two language dependent home pages. Actual behaviour: Calling http://localhost:8000 redirects "correctly" to the respective home pages depending on the browsers language. If browser languages is de || en: URL is http://localhost:8000/de/de/ || http://localhost:8000/en/en/ If I in browser with de and click link to en home: http://localhost:8000/de/en/ is opened and shows en home correctly. Same issue vice versa. So: The browser default language locale always remains part of the URL. Steps I did to achieve the goal: Fresh installation (v2.7) exactly like described in the docs To base.py added: LANGUAGES variable and 'django.middleware.locale.LocaleMiddleware' To urls.py added: from django.conf.urls.i18n import i18n_patterns and adapted urlpattern Added new page RedirectLang on same level as /home in Project and added class as from the docs redirectlang/models.py: from django.utils import translation from django.http import HttpResponseRedirect from wagtail.core.models import Page class RedirectLangPage(Page): def serve(self, request): # Solution from official Docs language = translation.get_language_from_request(request) return HttpResponseRedirect(self.url … -
Values of checked and unchecked checkbox passed to Django view
I have a checkbox that I would like it to return different values when check/unchecked. <form id="cat">{% csrf_token %} <input type="checkbox" id="chk" value="1" unchecked> </form> <script type="text/javascript"> $(document).on('submit','#cat',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/cat', data:{ chk:$('#chk').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, In the cat function in views.py, I have chked=request.POST.get('chk', '') I want to assign chked with different values with the checkbox checked/unchecked. I was referring to https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_checkbox and thought that value would be different if checked or not. However, same value of 1 returned whether checked or not. What am I missing here or is there a better way to do this? Thanks. -
How to control initial value and label of django forms BooleanField
I have a form as (BooleanField) in Django forms, and I need to set it is the initial value (True or false) dynamically, also want to add a label to it. here is my code: views.py def category_edit(request, pk): current_category = get_object_or_404(Category, pk=pk) edit_category_form = EditCategoryForm(request.POST, request.FILES, name=current_category.name, is_pos=current_category.is_pos) if request.method == "POST": if edit_category_form.is_valid(): pass else: edit_category_form = EditCategoryForm(request.POST, request.FILES, name=current_category.name, is_pos=current_category.is_pos) context = { 'current_category': current_category, 'edit_category_form': edit_category_form, } return render(request, 'product/category_edit.html', context) forms.py class EditCategoryForm(forms.Form): def __init__(self, *args, **kwargs): self.the_name = kwargs.pop('name') self.is_pos = kwargs.pop('is_pos') super().__init__(*args, **kwargs) self.fields['name'].widget.attrs = { 'class': 'form-control', 'value': self.the_name } self.fields['is_pos'].initial = self.is_pos self.fields['is_pos'].label = _('View in Point of sale') name = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', })) image = forms.ImageField(widget=forms.FileInput(attrs={ 'class': 'form-control', })) is_pos = forms.BooleanField(widget=forms.CheckboxInput()) And here is how it looks like, No label nor Initial value for boolean field: Note: The screenshot are taking from a view where it supposed to have the init value is TRUE -
How to query pass 2 of multiple conditions
I need query objects passed 2 of multiple conditions. Example: We have a model: class A(models.Model): id = models.PositiveSmallIntegerField(primary_key=True) cost = models.IntegerField(null=True, blank=True) price = models.IntegerField(null=True, blank=True) quality = models.IntegerField(null=True, blank=True) code = models.CharField(max_length=255, null=True, blank=True) name = models.CharField(max_length=255, null=True, blank=True) address = models.CharField(max_length=255, null=True, blank=True) Conditions: cost < 5 price < 7 quality > 0 ... code = 1234 name contains 'apple' Result can be: - 'C' item with cost = 6, price = 6, quality = 2, code = 321, name = 'asd asdsd' - 'D' with value: cost=4, price=6, quality=2, code=322, name='xyz' How to query item passed as less 2 conditions? -
How to get more reputaion in stack overflow?
I want to know how to make more reputation from stack overflow? I'm new to this platform and I want to 8k+ reputation in 1-2 months. any tips for that?