Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2.2. Instead of my template django uses the standard
I created an authapp application in django. And I registered it in settings and added to the main urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('authapp/', include('authapp.urls', namespace='authapp')), ] In authapp/urls.py I added: from django.contrib.auth import views as auth_views from django.urls import path, reverse_lazy import authapp.views as authapp app_name = 'authapp' urlpatterns = [ path('password_change/', auth_views.PasswordChangeView.as_view(success_url=reverse_lazy('authapp:password_change_done')), name='password_change'), path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), ] I added my templates to authapp/templates/registration: - password_change_form.html - password_change_done.html But when you click on the link http://127.0.0.1:8000/authapp/password_change/ I get to standart form in the django admin, not my form... What am I doing wrong? -
How can I increase the field of my profile model from an updateview that changes a field of a diferent model?
Well, I am trying to gamify my school, and thus I have created three models aside of the User provided by Django. Model Profile, that extends the User through O2O Field, that includes the integer field called experienced that I want to increase. class Profile(models.Model): # EXTENDINNG USER MODEL user = models.OneToOneField(User, on_delete=models.CASCADE,related_name='profile') # PERSONAL DATA pic = models.ImageField(upload_to='accounts/media/profile_pics', blank=True) telefono = models.CharField(max_length=12, blank=True) location = models.CharField(max_length=30, blank=True) born_date = models.DateField(null=True, blank=True) #CADA PUNTUACIÓN SE SUMARA A LA EXPERIENCIA DEL JUGADOR experience = models.PositiveIntegerField(null=True, blank=False, default=0) skills = models.ManyToManyField('Skill', verbose_name = 'skill',blank = True, through='Gamification') Model Skills, that reflects the technics that a pupil must learn. Model Gamification, it is connected to the other two models by a M2M Field inserted in Profile, with the attribute "through" pointing to it and a Foreign Key linking it to Skills, inserted in this model. plus the two FK fields corresponding tu Profile and Skill class Gamification(models.Model): class Meta: ordering = ['trainned'] profile = models.ForeignKey(Profile, on_delete=models.CASCADE,null=True) skill = models.ForeignKey(Skill, on_delete=models.CASCADE,null=True) trainned = models.DateTimeField(auto_now=True) # MARKS poor = '1' slow = '2' enough = '3' fast = '4' pro = '5' # LISTA DE TUPLAS Per_opt = [(poor,'1'),(slow,'2'),(enough,'3'),(fast,'4'),(pro,'5')] #CADA SKILL TENDRA UNA PUNTUACION performance … -
Build web site with Django
I wouldlike to build a new website when you write your name for example in a searchbar (cf pictures) and after submit you have another page with some informations about yourself : Main Page After submit your name What is the best way to start something like this ? Thank you for your help ! -
ModuleNotFoundError: No module named 'onelogin.saml2?
I am trying to run an existing django project on a local server. When I run: python manage.py migrate I get an error of missing a module for example: pil, boto3, request-logging, raven etc. I already installed it with pip install ... But then this error pops up: ModuleNotFoundError: No module named 'onelogin.saml2' I dont know which module to install, I already looked it up online and solutions like 'pip install python3-saml' didnt work? What am I doing wrong -
Django session: disconnect when user is inactive
is there a simple way to disconnect a user that is inactive for 3 minutes for example? I have develop an authentification app following a tutorial (https://simpleisbetterthancomplex.com/) https://www.youtube.com/watch?v=60GTvKCuam8&list=PLLxk3TkuAYnryu1lEcFaBr358IynT7l7H I use 'from django.contrib.auth import views' so I did not have write the login/logout/... views and have the default authentification behavior here I need to customize the behavior so I suppose I need to override the logout view? How can I do that? -
Why won't the image be displayed in Django?
I have a model with an ImageField, and I want to display it on my HTML, but it does not work, it displays only the alt attribute. My model: class HomePage(models.Model): # Fields image = models.ImageField(upload_to='main_image', blank=False) class Meta: pass def __str__(self): return str(self.pk) def get_absolute_url(self): return reverse("PizzaDeliverySystem_HomePage_detail", args=(self.pk,)) def get_update_url(self): return reverse("PizzaDeliverySystem_HomePage_update", args=(self.pk,)) My HTML file: <div class="text-center rounded mb-12"> <img class="img-fluid rounded" src="{{ homepage.image.url }}" alt="Főoldal kép"/> </div> -
Use pandas in a django view function to load data from a csv
I want to display time series data in a django application. The data is currently available in a csv-format. The simplest solution that came to my mind was to load the data using pandas in the view function, then perform my desired processing with it and supply the processed data to the HTML template in the context dictionary: def view_function(request): df = pd.read_csv('data/test.csv') # Any further processing of the loaded Dataframe # that returns df_processed context = { 'data': df_processed} return render(request, 'template.html', context) However, since I am new to web development, I wondered if this would be the way how to do it or if there are actually severe problems attached to this solution? If yes, what would be a better way how to do it? -
Unable to generate id for dynamically added table rows - Django dynamic formset
I am trying to implement Django inline formset (with a parent and child scenario) with an option to add rows for the child fields housed in a table. For the purpose I am using Django dynamic formset which is working in so far as the default form layout is concerned as well as adding new rows at runtime. I am able to save and edit data as well, even with the new rows added. However I find, to my dismay, that the id's of the newly added row elements are not generated (when viewed in "view source") - actually there are no reference to the newly added elements at all. Am I missing something or is this the wrong way to go for what I am trying to do, considering that the plugin is pretty "old" and by the looks of it, there has not been much activity on the source page. (I found one user asking whether the plugin may be used with Django 2.0!) The reason I want the id's of individual field elements is, that I need to carry out calculations involving values contained, using jQuery before I submit the form. Without the id's I can not … -
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