Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to deal with inconsistent dates in Django?
I am trying to show the birth and death dates for artists. Some artists have incomplete dates. For example: Johannes Vermeer is "Delft, October, 1632 - Delft, 15 December, 1675". How can one deal with this in Django model.Datefield()? Should I save the year, month and day separately? -
Generic Relation not reflecting in migrations in django?
I'm trying to add a GenericRelation field to the Notification model to my "Bond" model. The issue is that whenever I run makemigrations, this field does not get acknowledged. What could be the issue? Error: django.core.exceptions.FieldError: Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. class Bond(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follower") bond_created = models.DateTimeField(default=now) notifications = GenericRelation(Notification) class Notification(models.Model): #337, 777, 765, 843, 124 notification_type = models.PositiveIntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') -
How to set default as request.user in a model
I have a ForeignKey in a model, and a class based view: models.py class Book(models.Model): author = models.ForeignKey(get_user_model()) views.py class BookCreate(CreateView): model = Book ... How can I set a default value for the author to be the logged in user. E.g. something like author = models.ForeignKey(get_user_model(), default=request.user), although this obviously doesn't work. -
Building a poll application with Django
Okay guys so I'm building a financial planner application. The beauty of this application is that when a user inputs certain variables such as: salary, cost of asset and monthly saving goal a formula will work out how much is needed to save over x amount of time. So for example a formula I wrote up earlier: b = monthly saving/700 y = salary/40,000 x / (12b + y) = x x = amount needed to save Based on the user input the desired outcome would return the length and amount of time it will take to achieve z. I plan to create this project using Django but would really appreciate some recommended material or similar apps that you guys may have seen that I can learn from. -
How to stop my repo from cloning into new folder and clone into direct folder instead
I have a template I created but when cloning into the Django project folder it creates a subproject folder. I want it to just clone the subfolders and files when cloning the repo. Is there a way to do this? -
How to update a form and update table cell in Django
I am very new Django and python, trying to learn and build a webapp. I want to show some data to user in a table format. The user should be able to add, delete and update records in the table view. I am able to achieve the add, delete part but, cannot get my head around updating the existing records. Ideally, i want the row data to be populated in a modal view as a django form when clicked on "edit" button of a particular row. But unable to even get the basic update from a editable table row. Here is my sample code.. I tried this at below link but, did not help .. or may be i did not understand. Django: updating database row via table cell models.py # Create your models here. class customerDataModel(models.Model): customerName = models.CharField(max_length=200) custormerLocation = models.CharField(max_length=200) custormerAge = models.CharField(max_length=200) custormerLanguage = models.CharField(max_length=200) def __str__(self): return self.customerName forms.py from django import forms from . models import customerDataModel class addCustomerForm(forms.ModelForm): class Meta: model = customerDataModel fields = ('customerName', 'custormerLocation', 'custormerAge', 'custormerLanguage') widgets = { 'customerName': forms.TextInput( attrs={ 'class': 'form-control' } ), 'custormerLocation': forms.TextInput( attrs={ 'class': 'form-control' } ), 'custormerAge': forms.TextInput( attrs={ 'class': 'form-control' } ), … -
How to serialize multiple images(as in url) of an object in DRF?
I have a Image model related to Item model via ForeignKey, but the API endpoint of this resource only shows the images's name instead of image's url. (I have a single imagefiled in Item model, which can be shown as url/uri). So, how to serialize the data in order to get all the media urls for the images. Models : class Item(models.Model): title = models.CharField(max_length=200) ... img = models.ImageField() class ItemDetailImg(models.Model): item = models.ForeignKey( Item, on_delete=models.CASCADE, related_name='images') image = models.ImageField() Serializers: class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ("id", "title", ... "images" ) one API response: { "id": 16, "title": "Venice", ... "img": "http://127.0.0.1:8000/media/roman-kraft-g_gwdpsCVAY-unsplash.jpg", "images": [ 7, 8 ] } I expect this kind of api response { "id": 16, "title": "Venice", ... "img": "http://127.0.0.1:8000/media/roman-kraft-g_gwdpsCVAY-unsplash.jpg", "images": [ "http://127.0.0.1:8000/media/image1.jpg", "http://127.0.0.1:8000/media/image2.jpg" ] } Thank you, any help would be appreciated! -
is possible to use django rest framework for a build APK?
I am working whit django rest framework my link is this: http://hernancapcha.webfactional.com/licencias/ and for angular and IONIC local works Ok but when I build my APK a got one error "http failure response for 0 unknown error" I undestand that is becouse the headers in django, but is there a way to comunicate both? this is my Service: getOneLicencia(pet):Observable<any>{ return this.http.get(this.baseUrl+'/milistac/lice/?q=' +pet+ '', {headers:this.httpHeaders}); } -
What will happen if i create a group and didn't add a specific permissions to it?
I have two groups 'user' and 'moderator' with no specific permissions added (Chosen permissions empty). I have also three views to add/edit/delete objects, user can only add whereas moderator can edit/delete views.py class AddView(GroupRequiredMixin, CreateView): model = Post form_class = UpdateForm template_name = 'post_add.html' group_required = u"user" class UpdateView(GroupRequiredMixin, UpdateView): model = Post form_class = UpdateForm template_name = 'post_update.html' group_required = u"moderator" class DeleteView(GroupRequiredMixin, DeleteView): model = Post template_name = 'post_delete.html' group_required = u"moderator" The question is do i need to add permissions to the groups? for exmple add a permission to group 'user' that he can only add objects to model post ? or it is not needed ? thanks -
How to pass a custom tag parameter from a form field?
In order, i need to extend a model DetailView page with a specific custom function. That function need to be called from DetailView page and return some data, depending on the parameter entered by user into custom form on DetailView. That data, responded by custom function, i need to display on the same DetailView page, without database record, when user enter a form field value and press 'submit'. I think to implement that function by custom tag, which is located in /app/templatetags/func.py #/app/templatetags/func.py from django import template register = template.Library() def get_data(current_version, previous_version, some_data): return current_version+' works!' and call it in template, something like that: <!--templates/detail/article_detail.html--> {% load func %} ... {% get_data article_object.value %} <form action="" method="get"> {{ form }} <input type="submit" value="Compare"> </form> ... it works then i trying to specify an argument here in template. But i cannot understand how to take it from the form. Here is views.py: class ArticleDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView): model = Version context_object_name = 'article_object' template_name = 'detail/article_detail.html' login_url = 'login' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = GetChangelog() return context forms.py class GetChangelog(forms.Form): diff_version = forms.CharField(label='difference',max_length=10) Looks like it's impossible to pass a parameter through the url, because of that: -
Appropriate schema to design a notification system in django?
I am trying to create a notification system in Django. Is it better to have a notification_type field, user_id and a foreign key to different tables (like, comment, relationship tables)? Or should they all have a separate table for each type of notification like "LikeNotification", "CommentNotification", etc in addition to all of them having a user_id field? Design 1: class LikeNotification(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) class CommentNotification(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) class PostNotification(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) class BondNotification(models.Model): bond = models.ForeignKey(Bond, on_delete=models.CASCADE,) user = models.ForeignKey(User, on_delete=models.CASCADE) Design 2: class Notification(models.Model): notification_type = models.IntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) like = models.ForeignKey(Like, on_delete=models.CASCADE) comment = models.ForeignKey(Comment, on_delete=models.CASCADE) bond = models.ForeignKey(Bond, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) -
Correctly parsing XML in python
How do I pass my XML data into my view correctly? The workstation element should have multiple fields, and I only want a few. How do I tie those fields together and pass them correctly? Right now my code is only showing the last child in the first element called 'last_scan_time' so how can I pick apart other aspects that I may want. And how can I pass those to the view? like wanting to show the two workstations into a table? I imagine it'll be like a for each statement, but i'm stuck. Thanks! I'm using the latest version of Django. I know that my code is incomplete, I just need to know what I should be asking for during my request! for child in root for elements in child: print(elements.tag, elements.text) context = {'Name': child.tag, 'description': child.text} return render(request, 'pages/dashboard.html', context) Sample Response <?xml version="1.0" encoding="ISO-8859-1"?> <result created="2019-09-02T14:10:38-05:00" host="www.systemmonitor.us" status="OK"> <items> <workstation> <guid> <![CDATA[96d1fc87beb50e78b693ef4f73ce9056]]> </guid> <name> <![CDATA[DESKTOP-IV3PGUT]]> </name> <description> <![CDATA[Andy]]> </description> <install_date>2018-03-02</install_date> <last_boot_time>1565914977</last_boot_time> <dsc_active>1</dsc_active> <atz_dst_date>0000-03-02:00T02:00:00</atz_dst_date> <utc_apt>2019-09-02 17:34:46</utc_apt> <utc_offset>14400</utc_offset> <user> <![CDATA[DESKTOP-IV3PGUT\Andy]]> </user> <domain> <![CDATA[WORKGROUP]]> </domain> <manufacturer> <![CDATA[Gateway]]> </manufacturer> <model> <![CDATA[DX4850]]> </model> <ip> <![CDATA[192.168.0.3]]> </ip> <external_ip> <![CDATA[]]> </external_ip> <mac1> <![CDATA[]]> </mac1> <mac2> <![CDATA[]]> </mac2> <mac3> <![CDATA[]]> </mac3> <os> <![CDATA[Microsoft Windows … -
Nodemcu POST response -1
Nodemcu device is returning -1 http response for a POST request on django rest api. I tried the same http request to Postman, and it works perfectly fine. if(WiFi.status() == WL_CONNECTED) { HTTPClient http; http.begin(host_url); http.addHeader("Content-Type", "application/x-www-form-urlencoded"); httpCode = http.POST(postData); payload = http.getString(); http.end(); } The expected result is 200, whereas I get -1. Can someone please explain? -
how to pass a function loggin from an app to other
thanks for your time. i'm having some trouble to setup my loggin system, besides having a "login.html" i'd like to let displayed the loggin system on the navbar on my "base.html" and after the user login let displayed the user logged in. i don't know hot to call the login_view on other apps from the same project. i've succeded to let displayed the username and the form before the login. although i've created an app just for the accounts and its displaying the form just in the 'accounts/login' (not shure if creatting an app just for this is the best way). login_view.accounts.views.py def login_view(request): next = request.GET.get('next') form = LoginForm(request.POST or None) # se estiver escrito certo# if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') # autenticando o usuario# user = authenticate(username=username, password=password) # se estiver tudo certo (autendicado) chamar a função login# login(request, user) if next: return redirect(next) return redirect('/c2vconfig/MP4') context = { 'form2': form, } return render(request, "base.html", context) the login section on navbar on base.html: <li class="nav-item"> <a class="nav-link">{{request.user.username}}</a> </li> </ul> <form class="form-inline my-2 my-lg-0" action="{% url 'login' %}"> {{form2}} <button class="btn btn-outline-success my-2 my-sm-0" type="submit">login</button> accounts.urls.py: urlpatterns = [ path('login', views.login_view, name='login'), path('register', views.register_view, name='register'), path('logout', … -
Django Templates List of Checkboxes
I Want a list of checkboxes. When I tap them I want my model Checker.checked == True or False. My problem now when I tap one all of them are connected so only the first one changes value when I click number 2 or 3. And right now its not connected to the database. And I want it to be connected. class Checker(models.Model): name = models.CharField(max_length=100) checked = models.BooleanField(default=False) sender = models.ForeignKey(UserProfile, blank=True, on_delete=models.CASCADE, related_name="person_who_checks_checker"), canview = models.ManyToManyField(UserProfile, blank=True, related_name="can_view_checker") @login_required def detailTaskPage(request,pk): username = request.user checkers = Checker.objects.filter(task__id=pk) tasks = get_object_or_404(Task,pk=pk) return render(request, 'nav-side-task.html', {'task': tasks, 'MyName': username, 'Checkers': chrs}) {% for checker in Checkers %} <div class="row"> <div class="form-group col"> <span class="checklist-reorder"> <i class="material-icons">reorder</i> </span> <div class="custom-control custom-checkbox col"> <input type="checkbox" class="custom-control-input" id="checklist-item"> <label class="custom-control-label" for="checklist-item"></label> <div> <input type="text" placeholder="Checklist item" value="{{ checker.name }}" data-filter-by="value" /> <div class="checklist-strikethrough"></div> </div> </div> </div> <!--end of form group--> </div> {% endfor %} -
how to get element by ID on django modelform
** i'm setting up a django modelform that has a addmore button using js i want to be able to get the id of the button to be part of the the modelform since it has an html type.text..so i can see the value in the model admin th form.py from django import forms from django.contrib import admin from .models import FandB from Guest.models import Guest_Profile from .choice import * class FandBForm(forms.ModelForm): food_Items = forms.ChoiceField(choices = FOOD, label="Food", initial='select food', widget=forms.Select(), required=True) drinks_Items = forms.ChoiceField(choices = DRINKS, label="Drinks", initial='', widget=forms.Select(), required=True) payment_type = forms.ChoiceField(choices = PAYMENT_TYPE, label="Payment", initial='', widget=forms.Select(), required=True) amount = forms.DecimalField(max_digits=10, decimal_places=2) class Meta: model = FandB fields = ('guest',) def str(self): return self.food_Items views.py from django.shortcuts import render, get_object_or_404 from django.http import JsonResponse from django.template.loader import render_to_string from Home . utils import render_to_pdf from datetime import datetime from django.http import HttpResponse from django.views.generic import View from Home. utils import * from .models import FandB from Guest.models import Guest_Profile from .forms import FandBForm def order_list(request): orders= FandB.objects.all() context ={ 'orders':orders } return render(request, 'FB/order_list.html', context) def save_order_form(request, form, template_name,*args,**kwargs): data = dict() if request.method == 'POST': form = FandBForm(request.POST) if form.is_valid(): form.save() data['form_is_valid'] = True orders = FandB.objects.all() … -
adding a record to FontawesomeIcons table through Serivces class
i want to add a service to Services section in my website. each service has an icon that comes from Fontawesome website. i have 2 class: class FontawesomeIcons(models.Model): icon_name = models.CharField(max_length=200) icon_fontawesome = models.CharField(max_length=200) class Serivces(models.Model): icon = models.ForeignKey(FontawesomeIcons, on_delete=models.CASCADE, related_name='services') icon_name = models.CharField(max_length=200) icon_fontawesome = models.CharField(max_length=200) icon.icon_name = icon_name icon.icon_fontawesome = icon_fontawesome when i'm going to create a service i want to add an icon for that in the Services page in django admin CMS. i want to fill FontawesomeIcons class values through Services class. thank's for any help. -
Django-Background-Tasks: Initialize Task at midnight and repeat every midnight
Good day SO, I am currently using Django, and the Django-Background-Tasks package. I have a periodic task that I need to run at midnight, and it is to be repeated every midnight. I am a beginner at using the package, and am confused by the following: How do I set the repeat parameter during initialization? Here is my code: from background_task import background from datetime import datetime, date today_date = datetime.datetime.today() today_midnight = today_date.replace(hour=23, minute=59, second=59) @background(schedule=today_midnight) def send_reminders():... send_reminders(repeat=Task.DAILY) I wanted to set the parameter 'repeat' to task.DAILY, as stated in the documentation. However, I have encountered the following: NameError: name 'Task' is not defined I know I have to import something to define Task, but I couldn't find it. Can anyone help me? -
How to return folder name uploaded from <input webkitdirectory mozdirectory> to views.py in django
I have an HTML file in my Django project which has directory selector using <input type="file" name="file" id="uploadFolder" webkitdirectory mozdirectory/> I want to pass the folder path selected to views.py . I tried it using FormData concept but I am getting just file name not the folder path. I did something like below: <form method="POST" enctype="multipart/form-data" id="fileUploadForm"> {% csrf_token %} <input type="file" name="file" id="uploadFolder" webkitdirectory mozdirectory/><br/><br/> <input type="button" value="Submit" id="btnSubmit"/> </form> and on buttton cllick something like this: $.ajax({ type: "POST", enctype: 'multipart/form-data', url: "/upload/", data: data, processData: false, contentType: false, cache: false, timeout: 600000, success: function (data) { $("#result").text(data); console.log("SUCCESS : ", data); $("#btnSubmit").prop("disabled", false); }, error: function (e) { } }); }); How can I get the full path(or folder name)? -
How to get data from select forms using CBV or FBV
I'm having an issue displaying data from a Model that is retrieved from a select form. I prefer to use a CBV, but it doesn't matter at this point as long as it solves the issue. I've tried both ways and encounter a different problem for each way. I'll start with my CBV attempt. views.py class VehicleCompareView(FormView): template_name = "main/vehicle_compare.html" form_class = forms.CompareForm # I added different iterations of this in an attempt # to call the data in the html after previous attempts failed def get_form_data(request): form = forms.CompareForm(request.GET) data = form.cleaned_data['v-selection'] if form.is_valid(): data = form.cleaned_data['value'] return data forms.py class CompareForm(forms.Form): objectlist = forms.queryset = models.Vehicle.objects.all().order_by('make') html <div class="some class"> <form name="vform" method="get"> <select class="form-control" name="v-selection"> <option value="" selected disabled>Select Vehicle 1</option> {% for q in form.objectlist %} {% for b in q.package_set.all %} <option value="{{q}}" name="v-option"> {{ q.v_make }} {{ q.v_model }} {{ b.name }} </option> {% endfor %} {% endfor %} </select> <input value="submit" type="submit"> </form> <div> <p>{{data.v_make}}</p> </div> With this I am able to have a dropdown box that allows a selection in the right format, but nothing gets returned after submitting the selection. The next way I tried was with a FBV. I made … -
How to get the right revcounter through Django Pagnination?
I have a list of users. I list them in page with pagination like the following 113 - User13 112 - User 12 The problem is that each page is initializing with the the quantity set to the pagination. Let's say I have set a pagination with 10 users. each page will be set with the same counter like: 10 - user10 9 - user 8 - user1 I have tried this, but it's not working. {{forloop.revcounter0|all_profiles.end_index}} - {{user.get_full_name}} What I want is, with for instance 6 users divided by 2 pages with a pagination set to 3 users. Note the correct counter Page 1 6.- User 6 5.- User 5 4.- User 4 Page 2 3.- User 3 2.- User 2 1.- User 1 -
How Do I Install a Django Package from Github
I am using Django and Pipenv and have come across a package that I cannot install using "pipenv install [package_name]." The package I am trying to install is django-dynamic-formset. I have tried running this from my pipenv shell: "pipenv install -e git+https://github.com/elo80ka/django-dynamic-formset@v1.1#egg=django-dynamic-formset." I get the error below: https://github.com/elo80ka/django-dynamic-formset (src) (.venv) C:\Users\username\Documents\src>pipenv install -e git+https://github.com/elo80ka/django-dynamic-formset@v1.1#egg=django-dynamic-formset Installing -e git+https://github.com/elo80ka/django-dynamic-formset@v1.1#egg=django-dynamic-formset… Adding django-dynamic-formset to Pipfile's [packages]… Installation Succeeded Pipfile.lock (706c4a) out of date, updating to (0db539)… Locking [dev-packages] dependencies… Success! Locking [packages] dependencies… [= ] Pinning VCS Packages...error: pathspec 'v1.1' did not match any file(s) known to git Traceback (most recent call last): File "c:\users\username\appdata\local\programs\python\python37\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "c:\users\username\appdata\local\programs\python\python37\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\username\AppData\Local\Programs\Python\Python37\Scripts\pipenv.exe\__main__.py", line 9, in <module> File "c:\users\username\appdata\local\programs\python\python37\lib\site-packages\pipenv\vendor\click\core.py", line 764, in __call__ return self.main(*args, **kwargs) File "c:\users\username\appdata\local\programs\python\python37\lib\site-packages\pipenv\vendor\click\core.py", line 717, in main rv = self.invoke(ctx) File "c:\users\username\appdata\local\programs\python\python37\lib\site-packages\pipenv\vendor\click\core.py", line 1137, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "c:\users\username\appdata\local\programs\python\python37\lib\site-packages\pipenv\vendor\click\core.py", line 956, in invoke return ctx.invoke(self.callback, **ctx.params) File "c:\users\username\appdata\local\programs\python\python37\lib\site-packages\pipenv\vendor\click\core.py", line 555, in invoke return callback(*args, **kwargs) File "c:\users\username\appdata\local\programs\python\python37\lib\site-packages\pipenv\vendor\click\decorators.py", line 64, in new_func return ctx.invoke(f, obj, *args, **kwargs) File "c:\users\username\appdata\local\programs\python\python37\lib\site-packages\pipenv\vendor\click\core.py", line 555, in invoke return callback(*args, **kwargs) File "c:\users\username\appdata\local\programs\python\python37\lib\site-packages\pipenv\vendor\click\decorators.py", line 17, in new_func return f(get_current_context(), *args, **kwargs) File "c:\users\username\appdata\local\programs\python\python37\lib\site-packages\pipenv\cli\command.py", line 254, in … -
Get database table data older then 10 days in django
I am trying to retrieve data older then 10 days to update that field data. Currently my model is like class Restaurant(models.Model): is_approved = models.BooleanField(null=False, default=False) timestamp = models.DateTimeField(auto_now_add=True) my database table is Now when I query like dish = Restaurant.objects.filter(timestamp__gt=datetime.now() - timedelta(days=10)) I get whole table data. even I tried to change from day to 1 day . still full database result. -
Merge two user data dictionary data into a single dictionary ,have having same user data in python
Here the Problem is Explained. I ahve Users having multiple skiils . Showing Data like the Problem with seperate skills data Solution I needed for same user's skills will be at same array data. Problem: Data is LIke this Type: { 'group'= 'GR-A', 'users'=[ { 'id' = 1, 'name' = 'A' 'skills' = { 'id' = 1 'name' = 'skill-A' } }, { 'id' = 1, 'name' = 'A' 'skills' = { 'id' = 2 'name' = 'skill-B' } }, { 'id' = 2, 'name' = 'B' 'skills' = { 'id' = 2 'name' = 'skill-B' } }, ] } Data Solution Needed: { 'group'= 'GR-A', 'users'=[ { 'id' = 1, 'name' = 'A' 'skills' = [ { 'id' = 1 'name' = 'skill-A' }, { 'id' = 2 'name' = 'skill-B' } ] }, { 'id' = 2, 'name' = 'B' 'skills' = [ { 'id' = 2 'name' = 'skill-B' } ] }, ] } -
Why docker-compose don't copy files to virtualbox machine when running? "python: can't open file 'manage.py': [Errno 2] No such file or directory."]
I have problem with my dockers and I don't know why it happens. I created docker-machine with this command: docker-machine create --driver virtualbox --virtualbox-share-folder $(pwd) dev Now, I run docker-compose from django-cookiecutter template: docker-compose -f local.yml build and then docker-compose -f local.yml up From this moment I have that error from django: ... django_1 | PostgreSQL is available django_1 | python: can't open file 'manage.py': [Errno 2] No such file or directory project_django_1 exited with code 2 Also when I used docker-compose -f local.yml exec <here_id_container> django sh to check if any files are there, folder app is empty. Any clues?