Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue with multiple API hits with each action in react-admin
In my react-admin application, I'm sending two api hits for each create action and I'm not sure why. Network Tab Data I have the django REST framework backend running as well, could this be the issue? -
Any way to verify access token generated from ga_view_id in google analytics api?
I have ga_view_id and authentication file but i want to check the generated access token is generated from true value or not? If any way to check validate that token so i need to raise error without calling another api.(for better user experience) -
Django: permission_required
I an newbie n Django (3 months) I have a Django solution with different apps (each app can be access with a link in the nav bar) I would like to limit access to one of these app to some users: if a user do not have right access, the module link is not available I was thinking using Django admin permission and permission_required decorator but not sure it will fit my needs an option would be to have a Profile model link OneToOne to user model with an attribute app_authorization (False/True) and use this attribute in my template nav bar to display link to this app only if user.app_authorization=True but I sure there is a etter way to do it in Django -
I am trying to create a webapp using django framework
I have installed django and then tried using the command line to make a virtual environment then oops it gives me this error "'"virtualenv"' is not recognized as an internal or external command, operable program or batch file." what should I do to correct this -
Can anyone suggest a database schema for my django project?
I'm currently working on a student management web application built using Django framework. I have confusions while designing the database schema. There are currently 2 different regulations, which has 8 semesters each and each semester have subject name, subject code and subject credit. I wonder how to assign database schema for this tree and assign it to a student. So that each student have only one regulations, many semesters and related attributes. Can anyone suggest the database schema and Django ORM? Thanks in advance! -
Django model filter targeting JSONField where the keys contain hyphen / dash
I am trying to apply a model filter on a JSONField BUT the keys in the JSON are UUIDs. So when is do something like... MyModel.objects.filter(data__xxxx-xxx-xxx-xxx=‘bob’) ... I get a compile error. The hyphens in the UUID are the issue. Any clues if there is an escape char or another behaviour to use? My database is PostgreSQL. -
how to pass a Page to a routablepageurl outside of Wagtail
I am new to Wagtail and I am trying to figure out how can I pass the page parameter the routablepageurl requires. Currently I have in my models.py the following class BlogIndexPage(RoutablePageMixin, Page): max_count = 1 subpage_types = ['blog.BlogPage'] intro = RichTextField(blank=True) ..... ..... @route(r'^tag/(?P<tag>[-\w]+)/$', name="tag_view") def post_by_tag(self, request, tag): context = self.get_context(request, ) # TODO check if it exists context['blogpages'] = BlogPage.objects.live().public().filter(tags__slug=tag) return render(request, "blog/blog_index_page.html", context) class BlogPage(Page): parent_page_types = ['blog.BlogIndexPage'] date = models.DateField("Post date creation", default=datetime.date.today) intro = models.CharField(max_length=250) tags = ClusterTaggableManager(through=BlogPageTag, blank=True) .... .... I have made a seperate application called search where I define there a views.py and a templatetag to be used in different parts of the project. This is the views.py def post_search(request): if request.method == "POST": form = SearchForm(request.POST) if form.is_valid(): search_query = form.cleaned_data["searchquery"] search_results = BlogPage.objects.live().search(search_query, fields=["title", "intro", "body"]) context = { 'search_query': search_query, 'blogpages': search_results_pag, 'form': form, 'blog_index': BlogIndexPage, } return render(request, 'search/search_results.html', context=context) else: context = { 'form': form, } return render(request, 'search/search_results.html', context=context) elif request.method == 'GET': return render(request, 'search/search_results.html', {}) class SearchForm(forms.Form): searchquery = forms.CharField(max_length=100, label='', widget=forms.TextInput( attrs={'placeholder': 'search...', 'class': 'form-control search-menu'})) The search results appear correctly. The issue is that I am unable to use the routablepageurl … -
Connect to google sheets API using localhost
I'm using Django. I'm trying to use google sheets API. Well, I'm working on a local environment now and google acceptance OAuth needs to have a certain domain given and localhost doesn't work so I use ngrok. So I filled all those fields with domain and URL that ngrok gave me. I also used my ngrok URL to fill those credential fields. I've downloaded client_secret.json file and I set up all connection and stuff as google recommends on their sheets API docs. But still when I go to my ngrok URL and google connects I see such message that I cannot get rid of: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=...&redirect_uri=http%3A%2F%2Flocalhost%3A35701%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fspreadsheets&state=...&access_type=offline The message under that link is: Error: redirect_uri_mismatch The redirect URI in the request, http://localhost:39515/, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs, visit: link to my profile But in my client_secret the redirect_uris is set to: "redirect_uris":["http://something.ngrok.io/plan/create"] At this piot I have absolutely no idea what's going on. -
How can I take input from a text field in a Django page then update a SQL table with the response?
I am working on a site that will be used to clean up inactive Tableau workbooks. Logging into this site will allow my users to see their old workbooks and decide which ones to keep. This is going to be accomplished by taking some simple text input from an HTML page, K for keep | D for delete. The response from the user will then be stored as a Python variable that will go into an if then statement. The if then statement will basically update each row in SQL, adding either K or D to a column called "Marked_for_Deletion". From there, a stored procedure will run, check that column, and delete all things marked with a D. Is this feasible? If so, how would I go about pulling that input and making sure it gets added to the right column/row? If not, can you offer any suggestions on a substitute method I can use? Thanks! -
function inside the python class is not called while running the server
i am trying to validate unique user name in the registration form. while i click the submit button after entering the details in the register form, instead of raising a validation error with the given message, it fails and errors out Validationerror at /register/. i am also trying to print the string inside the function. but it doesnt print that too. is it actually calling the clean function. i am using self to achieve this. it should be called !. am i misiing something? class Register_Form(forms.Form): user_id = forms.CharField(label="User Name",widget = forms.TextInput( attrs = {"class":"form-control"} )) email_id = forms.CharField(label = "Email",widget = forms.EmailInput( attrs = {"class":"form-control"} )) password = forms.CharField(label = "Password",widget = forms.PasswordInput( attrs = {"class":"form-control"} )) confirm_pass = forms.CharField(label = "Confirm Password",widget = forms.PasswordInput( attrs = {"class":"form-control"} )) def clean_username(self): user_id = self.cleaned_data["user_id"] print("Entered") ue = User.objects.filter(username=user_id) if ue.exists(): raise forms.ValidationError("User name not available") return user_id -
Executing JavaScript functions in Django Templates
I have a Django App that, from a template feed.html calls different templates for different elements in the data base. The idea is to use a JavaScript script to visualize each one of these elements, the problem is that it just show the last one of them (the last element in this page). The script is this one: function showPiece(targ, piece){ window.onload = function(){ Lily.ready({ target: targ, // target div id file: 'files', // file input id path: '../../static/js/src', // path to source directory from current html file }); }; window.onload = function(){ var madeleine = new Madeleine({ target: targ, // target div id data: piece, path: '../../static/js/src', // path to source directory from current html file }); }; }; I am calling the script from the feed.html file. <script type="text/javascript" charset="utf-8"> var url_objetivo = '{{ piece.file.url }}' var id_objetivo = "id-" + {{ piece.id}} showPiece(id_objetivo, url_objetivo) </script> How can I force it to display the information for every element? -
Database table for custom categories that extends basic categories
I want to make Django app that helps user track his income/expenses. I'd like to store categories in a database, and I'd like to have a table with some basic categories like 'shopping', 'eating out', 'sport' and so one, but I also want to give a user a change to add his own, custom categories. I am wondering what the best approach for this case would be. I was thinking of creating a 'BASIC CATEGORIES' table, and then 'USER CATEGORIES' with user_id, and a name of category. And then in for example 'EXPENSES' table I would have: user_id, amount, basic_category_id, user_category_id, where one of 'category_id' would have to be null. Is my approach correct? -
Django: Display count of child in HTML template when querying Parent
I have to objects named Service with a child Requirements. What im trying to achieve is, First Filtering the service object and and displaying it and below of it display count of requirements. something like in below image. which shows the Service and count of Requirement associated to the Services, and also displaying Total count of requirements with status = 'Verified' Models.py class Service(models.Model): service = models.CharField(null=False, max_length=254) company = models.ForeignKey(Company_Data, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Requirements(models.Model): Requirements= models.CharField(null=False, max_length=254) file= models.CharField(null=False, max_length=254) service= models.ForeignKey(Service, on_delete=models.CASCADE) status = models.CharField(null=False, max_length=254) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Views.py def test_one(request): comp_id = request.session['comp_id'] service = service.objects.filter(company_id=comp_id) for services in service: list = services.req_document_set.all() print(req_info) for i in req_info: total_checklist = len(Req_Document.objects.filter(requirements_id=i.id)) total_verified = len(Req_Document.objects.filter(requirements_id=i.id, reqdoc_status='Verified')) print(total_checklist) print(total_verified) context = {'req_info': req_info, 'total_checklist': total_checklist, 'total_verified ': total_verified } return render(request, 'test1.html', context) test1.html <table> {% for services in service %} <tr> <td>{{services.services}} <ul> <li>Total Requirements Count = {{total_checklist}}</li> <li>Total Verified Count = {{total_verified }}</li> </ul> </td> </tr> {% endfor %} </table> on the terminal, i was able to print a loop of the count 3 1 0 0 which means i have 2 Services, in 1st service i have … -
Django DateInput() widget not working in ModelForm
I'm making a user login form with a CustomUser model derived from AbstractUser, with one extra field: date_of_birth. I use CreateView to generate the form. All fields show up, the password field uses the password widget as expected (showing dots instead of characters), but the date field does not (plain character field with no formatting or calendar). What am I overlooking? models.py: from django.urls import reverse from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): date_of_birth = models.DateField(verbose_name="Date of Birth", blank=True, null=True) def get_absolute_url(self): return reverse('index') def __str__(self): return self.username forms.py: from .models import CustomUser class CustomUserForm(forms.ModelForm): class Meta: model = CustomUser fields = ["username", "password", "first_name", "last_name", "email", "date_of_birth"] widgets = { "password": forms.PasswordInput(), "date_of_birth": forms.DateInput() } views.py: from django.views.generic.edit import CreateView from .models import CustomUser from .forms import CustomUserForm # Create your views here. def index(request): return HttpResponse("Hello, world") class CustomUserCreate(CreateView): model = CustomUser form_class = CustomUserForm -
Django. Password authentication failed for user via docker-compose up on AWS EC2
folks! I have faced very strange issue that I cannot resolve only by my own So, what's happening. I have docekrized Django + Postgresql + celery + redis image that runs on my AWS EC2. Sometimes django container randomly raises an error: django.db.utils.OperationalError: FATAL: password authentication failed for user xxx Postgres user password, name and postgres database name stored in the env file. I've looked up at database container shell to check if user is created and it's there. Also have tried to alter role password manually from shell. And yes container have data stored in environment variables Looking forward for any help! P.S. If you need any additional information (logs, etc.) - just ask, I'll update my post -
Linking to AWS S3 direct image uploads in Django templates
I'm using AWS S3 buckets for my images in my Django project through django-storages. It's pretty clear how to show an image in a template that has been uploaded through a model ImageField. Just do e.g. <img src="{{ model.image.url }}"> What if, however, I upload an image on S3 directly (e.g. for the website logo) and want to show it in a template? Any better way to just hardcoding the absolute Amazon S3 path: <img src="https://myapp.s3.amazonaws.com/home/logo.png"> ? Some way I can use just the relative "/home/logo.png" without hardcoding the amazonaws subdomain? -
save some information from form with image like state,city,image
def seller(request): if request.method == 'POST': state = request.POST['state'] city = request.POST['city'] full_address = request.POST['fulladdress'] out = request.POST['out'] each = seller(state=state,city=city,full_address=full_address,out=out) each.save() return redirect('home') else: return render(request,'all/seller_input.html') i am tried already this code but a problem is shown seller() got an unexpected keyword argument 'state' seller is my table where the all the data store -
Django Login does not work after Deploy (pythonanywhere.com)
I'm trying to deploy my Django App for a few days. I got the Index Page Working after a lot of guessing. Finally, I found the error. But now it is still not working correctly. I've tried to follow this How To this time: https://tutorial.djangogirls.org/de/django_installation/ and https://tutorial.djangogirls.org/de/deploy/#registriere-dich-f%C3%BCr-ein-pythonanywhere-konto So I Uploaded my Code to Github and made it Publicly available and I created a pythonanywhere project at this URL: http://mvanthiel.pythonanywhere.com/catalog/ui/ I also created a virtual environment and created the .gitignore file. On my Windows (Dev) Host the Website does work as expected. On pythonanywhere.com it does not. Windows Dev On Windows Dev, I pushed the Projekt content to git like explained in the how-to. After that I tried two different ways: pythonanywhere.com On pythonanywhere.com I installed the pip module. pip3.6 install --user pythonanywhere And then I tried to autoconfigure the rest on pythonanywhere.com with: pa_autoconfigure_django.py --python=3.6 https://github.com/HigeMynx/onboarding.git The Website is now Online available and I create a Django Superuser in the shell. But when I try to log in (on the website oder the admin panel) or register, I constantly get this Error Page: SelfHosted Linux VM I added a Service Account and removed and installed some packages. After that, I … -
DHTMLXGantt + Django
Im using a DHTMLX Gantt to plot data from the database via an api, like this: var endpoint = '/api/chart/data/' var label = [] var start = [] var end = [] var duration = [] $.ajax({ method: 'GET', url: endpoint, success: function(data){ labels = data.label start = data.start end = data.end duration = data.duration const input = start; // 2019-02-01 const output = input.map((str) => { const [year, month, date] = str.split("-"); return `${date}-${month}-${year}`; // 01-02-2019 }); var n = 0; var arr=[]; for ( var i=0; i<labels.length; i++){ newlab = labels[i]; newid = "id" + labels[i]; newstart = output[i]; newdur = duration[i]; arr.push({ id:newid, text:newlab, start_date:newstart, duration:newdur, progress:0.6}) }; var tasks = {data:arr}; gantt.attachEvent("onBeforeTaskChanged", function(id, mode, task){ console.log("onBeforeTaskChanged"); console.log(task); return true; }); gantt.attachEvent("onAfterTaskDrag", function(id, mode, e){ console.log("onAfterTaskDrag"); var task = gantt.getTask(id); console.log(task); }); gantt.init("gantt_here"); gantt.parse (tasks); }, error:function(error_data){ console.log("error") console.log(error_data) }}); Now I want to store the new data I get from onAfterTaskDrag to the Database with an ajax call. How would I go about doing this? Thank you for any help -
How to install older Django
I am using Pycharm and want to install an older version of Django. However, PC only seems to install V2. How can I configure Pycharm to install an older version? -
Django filters, creating date range filter forms for table
I am new in Django, have problem with creating date range filter forms and search form for table, table I make by django_tables2, here code: models.py from django.db import models class Person(models.Model): name = models.CharField('full name', max_length=50) fname = models.CharField('family name', max_length=50) birthdate = models.DateField(null=True) tables.py import django_tables2 as tables from .models import Person class PersonTable(tables.Table): class Meta: model = Person attrs = {'class': 'paleblue'} views.py from django.shortcuts import render from django.views.generic import ListView from django_tables2 import RequestConfig, SingleTableMixin from .models import Person from .tables import PersonTable def people_listing(request): table = PersonTable(Person.objects.all()) RequestConfig(request).configure(table) table.paginate(page=request.GET.get("page", 1), per_page=1) return render(request, "tutorial/index.html", {"table": table}) index.html {% load render_table from django_tables2 %} {% load static %} <!doctype html> <html> <head> <link rel="stylesheet" href="{% static 'css/screen.css' %}" /> </head> <body> {% render_table table %} </body> </html> after this I install django_filters here code: filters.py import django_filters from .models import Person class ClientFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Person fields = ['id','name','fname','birthdate'] now don't know how to make search form for my table and make form date range filtering "date from and date to? -
Related Model Column Names in django-datatables-view
I'm trying to work with django-datatables-view to add some basic filtering and sorting to my ListView. I have a Result model, which has a FK relationship to a Test model. The Result model has fields status and when, and the Test has fields 'name', 'pass_percentage', and 'maintained' (these are the only fields I'm interested in displaying, both models have additional fields. I have the following code: class TestListJson(BaseDatatableView): model = Result columns = ['test__name', 'test__pass_percentage', 'test__maintained', 'status', 'when'] order_columns = ['test__name', 'test__pass_percentage', 'test__maintained', 'status', 'when'] def get_initial_queryset(self): results = ( Result.objects.filter( canonical=True, environment__config__in=['staging', 'production'] ) .select_related('test', 'environment') .order_by('test__name', '-created_at') .distinct('test__name') .exclude(test__name__startswith='e2e') ) #print (results.first()._meta.local_fields) return results But when I view the JSON endpoint, only the status and when fields have values. How should I be passing related model field names to columns? -
pyodbc.ProgrammingError: ("A TVP's rows must be Sequence objects.", 'HY000') Django ERROR
I am trying to execute a POST request in Django to execute a stored procedure which will insert values in tables. When I am running a POST request in POSTMAN, I can see the data which I am copying using: data = request.POST.copy() as: <QueryDict: {'{\r\n\t"ID":"00000000-0000-4343-89D1-000000000000",\r\n\t"key2": "0",\r\n\t"key3": "3",\r\n\t"key4": "2000-05-01 00:00:00.000",\r\n "key5": "2017-06-08 00:00:00.000",\r\n "key6":"1",\r\n "key7":"3",\r\n "key8":"99.98",\r\n "key9":"560602",\r\n "key10":"EG2-val",\r\n "key11":"7.69999980926514",\r\n "key12":"2017-06-08 00:00:00.000"\r\n}': ['']}> when I run the same request through CURL, I can see the output of data = request.POST.copy() as: <QueryDict: {'ID': ['00000000-0000-4343-89D1-000000000000'], 'key1': ['0'], 'key2': ['3'], 'key3': etc}> From POSTMAN sent request if I copy the data into variables as: ID= data.get('ID') I am seeing none in ID after printing it while with CURL command I can see the id as 00000000-0000-4343-89D1-000000000000. The final error with both the way of sending POST request I am getting error: django.db.utils.ProgrammingError: ("A TVP's rows must be Sequence objects.", 'HY000') Internal Server Error: /setMethod/ What is this error? How to resolve it? In POSTMAN I am using raw JSON data in body and Content-type=application/x-www-form-urlencoded, charset=UTF-8 in headers. -
Django redirect URL into another URL with form
I wouldlike to redirect in another URL when I submit my form. After submit, I wouldike to have another page with something like "Hello (SummonerName) and Welcome" with URL like this : interface/main/SummonerName=(SummonerName) Here my code : forms.py from django import forms class SummonerForm(forms.Form): summoner_name = form.CharField(label='SummonerName:', max_length=100) views.py from django.http import HttpresponseRedirect from django.shortcuts import render from .forms import NameForm def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/interface/name.html') # if a GET (or any other method) we'll create a blank form else: form = NameForm() return render(request, 'interface/main.html', {'form': form}) and my main.html <form action="/SummonerName={{ current_name }}" method="post"> <label for="summoner_name">SummonerName: </label> <input id="summoner_name" type="text" name="summoner_name" value="{{ current_name }}"> <input type="submit" value="Rechercher"> </form> Thank you ! -
how to access to choices in SimpleArrayFiled with a multiple choice filed using django forms
from model.blah import Ghosts I have a model has a with a filed looks like this scary_boos = ArrayField( choice_char_field(Ghosts.TYPE_SELECTION), blank=True, null=True ) and in the admin panel, I am trying to add a form to show that field with pre-determined choices. class GhostBoosForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) print(self.fields["mortgage_type"]) self.fields["scary_boos"].widget = CheckboxSelectMultiple( choices=self.fields["scary_boos"].choices ) class Meta: model = GhostBoos fields = "__all__" however choices=self.fields["scary_boos"].choices doesn't work is there any other way to access those choices of the filed?