Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change page title of password reset form?
I am using the default password reset form, that comes with django..I have changed the title of Admin Site by adding the following line of code in urls.py admin.site.site_header = 'My Site Name' But, the password rest form still says "Django Administration" in place of the site title, as show in the image attached. How do I change it? Password Reset Form -
django celery cannot start worker
I am having an issue with starting up my celery worker for my django project. Thank you for giving any help here. I think I shut down the celery process inappropriately (ctrl+c first, and ran the "celery -A proj worker " command again before it was shut down completely). Since then I have never been able to start up my celery worker. It basically gives no response from the command line, not moving forward, no error, and nothing happens literally. It is just stuck there. I also tried to reinstall my celery and rabbitmq, but this doesn't help either. Does anyone know what could be wrong here? Thank you very much for your help. sen -
Unknown user named demo on my ubuntu server. server hacked
Please read full details before answer. I am develover working on a client's server machine on a site. Site went down sudden. So i checked the dashboard i got error server ip is reported as abused on abuseipdb.com for hacking attempts 126 times. I spockwith support they put site back live. Then i checked the server for issue. I am not system admin person. I am web developer still with help of google i checked the logs and found out that a user named demo entered in the server. When i try to delete it it said it have associated process with him. So i checked there we rsync process. I checked google find out that these are file synchronisation process. I have deleted process and deleted user too. There are still rsync process suspisious to me. How to check what files these process are using and what they are doing. How to identify any other suspisious process. Please help me out. Me and client only both persion have the access to site. So if something happen i will be blamed. one more thing i think it is somehow related with apache because demo user have directory assigned /var/www/html -
normal distribution from django model
How can one build the distribution graph from the model data on the client side: class Parameters(models.Model): par_time = models.DateTimeField('date') par_recipe = models.CharField(max_length=200) par_machine = models.CharField(max_length=200) par_fa = models.CharField(max_length=200) par_ag_typ = models.CharField(max_length=200) par_rollennr = models.IntegerField(default=0) par_definition_id = models.IntegerField(default=0) par_name = models.CharField(max_length=200) par_value = models.IntegerField(default=0) By value, if I use html and Data is already loaded in the database -
Django Form based on Form
I am writing my code based on the principle don't repeat yourself. I keep violating that rule because I am new to Django but this one should be straight forward. The code below is no problem for ModelAForm: model.py class ModelA(models.Model): id = model.AutoField(primary_key=True) name1 = models.CharField(max_length=100) name2 = models.CharField(max_length=100) ... right = models.BooleanField(default=True) class ModelB(models.Model): id = model.AutoField(primary_key=True) mod = model.ForeignKey(ModelA, on_delete=models.CASCADE) above30 = models.BooleanField(default=True) forms.py class ModelAForm(forms.ModelForm): class Meta: model = ModelA exclude = ['id'] class ModelBForm(forms.ModelForm): class Meta: model = ModelB exclude = ['id'] But this way I don't see the other fields of modelA in the ModelBForm. How can I do this? Thanks! -
Link JavaScript Button to Django Form
I have a JavaScript Function for showing fullcalendar. There I added a custom button (addEventButton) for adding new events: $('#calendar').fullCalendar({ header: { center: 'addEventButton', }, events: '/schedule/api/occurrences?calendar_slug=calendar', customButtons: { addEventButton: { text: '+', click: function() { var dateStr = prompt('Enter a date in YYYY-MM-DD format'); var date = moment(dateStr); if (date.isValid()) { $('#calendar').fullCalendar('renderEvent', { title: 'dynamic event', start: date, allDay: true }); } } } }); To get this new events into my django-model, where all events are stored, I've made a forms.py: class create_calendar_event(forms.Form): Title = ModelChoiceField(label='Title', queryset=Title.objects.all()) INPUT_FORMATS = ['%Y-%m-%d %H:%M'] start = forms.DateTimeField(input_formats=INPUT_FORMATS, widget=forms.DateTimeInput()) end = get_end_time(start) calendar = ModelChoiceField(label='Calendar', queryset=Calendar.objects.all()) How can I link this create_calendar_event form into the JavaScript addEventButton? -
How to query the number unique relations in Django
I have difficulties to create a more complex model query in Django. My model structure looks like this: date 1 - n cases case n - 1 employee employee n - 1 company What I want is to query the number of unique 'companies' used in all 'cases' at a specific 'date' (for other reasons 'date' is its own model in this case) in a method of the date model. -
Combining Ember REST Adapter with Django rest_framework ModelViewSet
I am creating an application that uses Ember and Django. For the backend of Django do I use rest_framework with the ModelViewSet as my view class. In the frontend with Ember do I use the RESTAdapter. My backend sends data back like this: { "id": 22, "name": "test", "startdate": "2019-01-01", "enddate": "2018-12-26" } while my frontend expects it like this: { "appointment": { "id": 1, "name": "test", "startdate": "2019-01-01", "enddate": "2018-12-26" } } I can't figure out how to make either end conform the other end in a nice and clean way. In the Django view class could I do this: def list(self, request): """Send all appointments.""" serializer = AppointmentSerializer(self.queryset, many=True) return Response({'appointment': serializer.data}) and it would work to get the appointments, but then I would have to alter all the functions like create, update, delete etc. I feel like there has to be a clean and better maintainable way to fix this issue. -
Multiple forms on django page
Below is the view def TestPageView(request): if request.method == 'POST': contactform = ContactForm(request.POST,prefix="contact") subscriptionform = SubscriptionForm(request.POST,prefix="subscription") suggestionform = SuggestionForm(request.POST,prefix="suggestion") globalmessageform = GlobalMessageForm(request.POST,prefix="globalmessage") if contactform.is_valid() and subscriptionform.is_valid() and suggestionform.is_valid() and globalmessageform.is_valid(): contact = contactform.save() subscription = subscriptionform.save() suggestion = suggestionform.save() globalmessage = globalmessageform.save() else: print(form.errors) else: contactform = ContactForm(prefix="contact") subscriptionform = SubscriptionForm(prefix="subscription") suggestionform = SuggestionForm(prefix="suggestion") globalmessageform = GlobalMessageForm(prefix="globalmessage") return render(request,'dashboard/test_page.html',{'contactform':contactform,'subscriptionform':subscriptionform,'suggestionform':suggestionform,'globalmessageform':globalmessageform}) How to write html code to show and save these forms on test_page.html.I know how to show one form but there are 4 forms in this case. -
[DJANGO][GUNICORN] Operation not permitted
I followed this tutorial : http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/ My directory structure is quite the same: -rw-r--r-- 1 django webapps 0 Nov 30 15:58 access.log drwxr-xr-x 3 django webapps 4096 Nov 30 17:27 bin -rw-r--r-- 1 django webapps 6450 Nov 30 15:58 error.log drwxr-xr-x 2 django webapps 4096 Nov 30 15:58 gunicorn drwxr-xr-x 2 django webapps 4096 Nov 30 16:10 include drwxr-xr-x 3 django webapps 4096 Nov 30 16:10 lib lrwxrwxrwx 1 django webapps 3 Nov 30 16:10 lib64 -> lib drwxr-xr-x 2 django webapps 4096 Nov 30 17:12 logs drwxr-xr-x 5 django webapps 4096 Nov 30 13:36 narcisse -rw-r--r-- 1 django webapps 59 Nov 30 16:11 pip-selfcheck.json -rw-r--r-- 1 django webapps 75 Nov 30 16:10 pyvenv.cfg -rw-r--r-- 1 django webapps 85 Nov 30 15:50 README.md drwxrwxrwx 2 django webapps 4096 Nov 30 17:51 run I have a /etc/supervisor/conf.d/filename that looks like this: [program:site] command = /var/www/site/bin/gunicorn_start -user=django user = django stdout_logfile = /var/www/site/logs/gunicorn_supervisor.log redirect_stderr = true My gunicorn_start is located inside /var/www/site/bin ()and looks like this: NAME="api" DJANGODIR=/var/www/site/site SOCKFILE=/var/www/site/run/gunicorn.sock USER=django GROUP=webapps NUM_WORKERS=3 DJANGO_SETTINGS_MODULE=api.settings DJANGO_WSGI_MODULE=api.wsgi echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname … -
data acquisition optimization
There are a lot of records in the table(450k records), how can I get them faster than in this way? def index(request): params = Parameters.objects.all() return render(request, "core/data_table.html", {"params": params}) I bring in the table on html {% extends 'base.html' %} {% block content %} <html> <body> {% if params.count > 0 %} <h2>Data</h2> <table> <tr><th>Id</th><th>par_time</th><th>par_recipe</th><th>par_machine</th><th>par_fa</th><th>par_ag_typ</th><th>par_rollennr</th> <th>par_def_id</th><th>par_name</th><th>par_value</th></tr> {% for person in params %} <tr><td>{{ params.id }}</td><td>{{ params.par_time }}</td><td>{{ params.par_recipe }}</td><td>{{ params.par_machine }}</td> <td>{{ params.par_fa }}</td><td>{{ params.par_ag_typ }}</td><td>{{ params.par_rollennr }}</td><td>{{ params.par_def_id }}</td> <td>{{ params.par_name }}</td><td>{{ params.par_value }}</td></tr> {% endfor %} </table> {% endif %} </body> </html> <p><a href="{% url 'home' %}">Return to home</a></p> {% endblock %} -
Django: Validate GET request
I have written a few simple API endpoints (without Django REST). I have problems figuring out how to validate the input data. class CarTypeForm(forms.Form): car_type= forms.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(6)], required=False ) def car_data_as_json(request): """ API Endpoint """ # Receive and validate variables from get request car_type= request.GET.get("car_type", 0) car_type_form = CarTypeForm() car_type_form.car_type = int(car_type) if car_type_form.is_valid(): do something return JsonResponse(something) else: return JsonResponse({'err': 'invalid car_type'}, status=400) I don't understand why if car_type_form.is_valid(): is not True despite the value being 5 for example. I'm using Django 2.1 -
Django TypeError at /signup/ create_user() missing 1 required positional argument: 'username'
I am doing according to the django's docs which say if you are using a custom models which defines username, email, is_staff, is_active, is_superuser, last_login, and date_joined fields the same as Django’s default user, you can just install Django’s UserManager, My intentions are i do not want to use username for creating a user, i want to use but an email so when i do that i keep getting this error "TypeError at /signup/ create_user() missing 1 required positional argument: 'username'". here is my code models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, UserManager class User(AbstractBaseUser): email = models.EmailField(unique=True, blank=False) date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' objects = UserManager() views.py def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): if form.cleaned_data['password'] != form.cleaned_data['repeat_password']: context['form'] = SignUpForm(request.POST) context['error'] = 'Passwords did not match' return render(request, 'shopapp/signup.html', context) else: # Creating the user here email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = User.objects.create_user(email=email) user.set_password(password) return HttpResponse('{} {}'.format('User created succesfully', User.objects.all())) return HttpResponse('Form is not ok') else: form = SignUpForm() context['title'] = 'Signup' context['form'] = form return render(request, 'shopapp/signup.html', context) -
Django doesn't recongnize Gensim
I'm using Python, Django, IDE PyCharm. I imported Gensim for my project, however, seems like Django does not recognize it. Here are my versions: gensim-3.6.0 numpy-1.15.4 scipy-1.1.0 The following error is: Traceback (most recent call last): File "C:/Users/Me/PycharmProjects/sma-capstone-2018/sma_core/brinfluence/lib/doc2vec.py", line 4, in <module> import gensim File "C:\Users\Me\venv\lib\site-packages\gensim\__init__.py", line 5, in <module> from gensim import parsing, corpora, matutils, interfaces, models, similarities, summarization, utils # noqa:F401 File "C:\Users\Me\venv\lib\site-packages\gensim\parsing\__init__.py", line 4, in <module> from .preprocessing import (remove_stopwords, strip_punctuation, strip_punctuation2, # noqa:F401 File "C:\Users\Me\venv\lib\site-packages\gensim\parsing\preprocessing.py", line 40, in <module> from gensim import utils File "C:\Users\Me\venv\lib\site-packages\gensim\utils.py", line 40, in <module> import scipy.sparse File "C:\Users\Me\venv\lib\site-packages\scipy\sparse\__init__.py", line 229, in <module> from .csr import * File "C:\Users\Me\venv\lib\site-packages\scipy\sparse\csr.py", line 15, in <module> from ._sparsetools import csr_tocsc, csr_tobsr, csr_count_blocks, \ ImportError: DLL load failed: The specified module could not be found. -
save extra field values into the database from django signup page
I manage to get a extra field (state name) on Sign-Up page (using forms.ModelForm) but I am struggling to save it in the database. I have 2 database connections, the default database is to keep Django tables and project_db to keep program tables wondering if this is causing the issues? or with forms.py file. below is forms.py file. class UsersRegisterForm(forms.ModelForm): class Meta: model = User fields = [ "username", "state_name", "email", "confirm_email", "password", ] username = forms.CharField() state_name = forms.ModelChoiceField(queryset=SchPartneredStates.objects.all(),empty_label=None) email = forms.EmailField(label="Email") confirm_email = forms.EmailField(label="Confirm Email") password = forms.CharField(widget=forms.PasswordInput) def __init__(self, *args, **kwargs): super(UsersRegisterForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({ 'class': 'form-control', "name": "username"}) self.fields['state_name'].widget.attrs.update({ 'class': 'form-control', "name": "state_name"}) self.fields['email'].widget.attrs.update({ 'class': 'form-control', "name": "email"}) self.fields['confirm_email'].widget.attrs.update({ 'class': 'form-control', "name": "confirm_email"}) self.fields['password'].widget.attrs.update({ 'class': 'form-control', "name": "password"}) def clean(self, *args, **keyargs): email = self.cleaned_data.get("email") confirm_email = self.cleaned_data.get("confirm_email") username = self.cleaned_data.get("username") state_name = self.cleaned_data.get("state_name") password = self.cleaned_data.get("password") if email != confirm_email: raise forms.ValidationError("Email must match") email_qs = User.objects.filter(email=email) if email_qs.exists(): raise forms.ValidationError("Email is already registered") username_qs = User.objects.filter(username=username) if username_qs.exists(): raise forms.ValidationError("User with this username already registered") if len(password) < 8: # you can add more validations for password raise forms.ValidationError("Password must be greater than 8 characters") return super(UsersRegisterForm, self).clean(*args, **keyargs) -
Validating reCAPTCHA v3 in Django
In reCAPTCHA V2, I could verify in the views.py itself. However in V3 I don't know how to proceed. Now I'm using it in development with 127.0.0.1. First I have generated the site key and the secret key. In settings.py I have added secret key, GOOGLE_RECAPTCHA_SECRET_KEY = 'my_secret_key_here' Then in my signup.html I have, <script src='https://www.google.com/recaptcha/api.js?render=my_site_key_here'></script> Unlike previous there is no < div > tag to add the checkbox. The script itself is rendering the recaptcha symbol in the side of my browser. My question is, How can I validate using grecaptcha.execute. Do I have to add the script with my site key to every page I want to protect from spam or is there any simple way -
AssertionError: URL name is needed to resolve correct wizard URLs django 2,1
class ListingWizard(LoginRequiredMixin , StaffuserRequiredMixin,NamedUrlSessionWizardView): # class attribute named : form_list form_list = ( ('listing_data',ListingForm), ('images',ListingImageForm), ('attributes',AttributeListingForm), ) TEMPLATES = { 'listing_data':'admins/step1.html', 'images':'admins/step2.html', 'attributes':'admins/step3.html' } please some one can help me , i'm try to add wizard for to my django project , i dont know how define its url in new version of django 2.1 , thanks for advice -
override UserCreationForm in django
I want to create users (up to 1000) with default password. so how can i override django base UserCreationForm ? I tried this (for possibility) in base django UserCreationForm but passwords get erased when form tries to cleaned_data... self.base_fields['password1'].default = "Xyz@1234" self.base_fields['password2'].default = "Xyz@1234" -
Why the safe filter is affected by the bootstrap design (rich text)!
I use ckeditor as a text editor in the Django application along with Bootstrap The problem is that the design of the bootstrap before the filter safe {{td.snippet1 }} is working normally, but when the filter is added {{td.snippet1|safe }}, the design is affected terribly and badly, i don't know why <!-- container --> {% for td in three %} {{td.title}} {{td.snippet1|safe }} {{ td.article_author }} {{ td.posted_on}} {% endfor %} -
How to make cron time editable for django admin
I have to allow the admin the set the cron time from admin view in django. Like i have an configuration model , where admin can put the time as record 2 am (record 1) 4 pm (record 2) So on each record i have to run the cron. But cron time is in setting.py CRONJOBS = [ ('*/5 * * * *', 'myapp.cron.my_scheduled_job') ] https://pypi.org/project/django-crontab/ How to make this setting available for admin. -
Loading and parse xlsx file
How can I continue working with the downloaded file? parse it into the model views.py def model_form_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = DocumentForm() return render(request, 'core/model_form_upload.html', { 'form': form }) my model.py class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) class Parameters(models.Model): par_time = models.DateTimeField('date') par_recipe = models.CharField(max_length=200) par_machine = models.CharField(max_length=200) par_fa = models.CharField(max_length=200) par_ag_typ = models.CharField(max_length=200) par_rollennr = models.IntegerField(default=0) par_definition_id = models.IntegerField(default=0) par_name = models.CharField(max_length=200) par_value = models.IntegerField(default=0) Used for download Excel files (xlsx). Fields in xlsx are represented as described in the model. As soon as I didn’t try, I’m new to Django and I’ve got nothing -
how to add path in div/style using jinja
I have this code. <div class="g-fullheight--xs g-bg-position--center swiper-slide" style="background:{% static'/img/1920x1080/02.jpg' %}"> but it's doesn't work. how to add path in style. As correct using Jinja The origin code is <div class="g-fullheight--xs g-bg-position--center swiper-slide" style="background: url('img/1920x1080/01.jpg');"> -
Django: Accessing value of a field of one form into another form
Following are my django models:- class VisitorInfo(models.Model): username = models.CharField(max_length=120,null=True,blank=False) items_searched = models.ManyToManyField(ItemsSearched,blank=True) pages_visited = models.ManyToManyField(Page,blank=True) class Page(models.Model): page = models.CharField(max_length=120) def __str__(self): return self.page class ItemsSearched(models.Model): visitor = models.ForeignKey('VisitorInfo',on_delete=models.CASCADE,null=True,blank=True) itemssearched = models.CharField(max_length=120) def __str__(self): return self.itemssearched class TestPersona(models.Model): name = models.CharField(max_length=120,primary_key=True,default='Persona1') def __str__(self): return self.name class TestPersonaKey(models.Model): key_label = models.CharField(max_length=100,null=True,blank=True) persona = models.ForeignKey('TestPersona',on_delete=models.CASCADE) persona_key = models.CharField(max_length=120,primary_key=True,default='Key1') def __str__(self): return self.persona_key class KeyValue(models.Model): persona_key = models.ForeignKey('TestPersonaKey',on_delete=models.CASCADE) keyvalue = models.CharField(max_length=120,null=True) def __str__(self): return self.keyvalue Following are django forms. class PersonaNameForm(forms.ModelForm): name = forms.CharField(label='Person Name',max_length=100) class Meta: model = TestPersona fields = ["name",] class KeyForm(forms.ModelForm): key_label = forms.CharField(label='Give Label',max_length=100) persona_key = forms.ChoiceField(label='KEY',choices=(('itemssearched','ITEMS SEARCHED'),('username','USERNAME'),('pages','PAGES VISITED'))) class Meta: model = TestPersonaKey fields = ['key_label','persona_key',] I want your help here class KeyValueForm(forms.ModelForm): #if persona_key selected in KeyForm is ITEMS SEARCHED: #value = forms.MultipleChoiceField(label='Value', choices= all the items in ItemsSearchedModel) #if persona_key selected in KeyForm is USERNAME: #value = forms.ChoiceField(label='Value',choices= all the usernames in VisiterInfo model) #if persona_key selected in Key Form is PAGES VISITED: #value = forms.MultipleChoiceField(label='Value',choices= all the pages in Page model) I learnt the way to write views and template in this type of situation from this answer Get Django form field from model field . Please let me know whether view and … -
Javascript: Print on HTML browser the updated GPS value on a new line after 1 second interval
How do I print on HTML browser the updated value of the watchPosition() or getAccurateCurrentPosition() method on a new line after every 1 second interval? The updated value consists of Time | Latitude | Longitude | Accuracy to be shown on the HTML browser. Below is my code which only prints the location to the browser only once. How could I modify this code? I used a variation of getCurrentPosition(), the getAccurateCurrentPosition() to return a better result below. Would it be possible to insert a timer and loop the code through? How could I prevent the HTML page from erasing the previous lines of GPS result and only add new lines to the browser? Thank you for any assistance, I sincerely appreciate it. location.html <p>Click the button to add coordinates.</p> <button onclick="getLocation()" class="btn btn-primary">Get Your Location</button> <p id="result"></p> <form method='POST' action="" enctype="multipart/form-data"> <p>{{ form | crispy }}</p> {% csrf_token %} <button type="submit" id="btn_submit" class="btn btn-primary form-control" disabled>Submit</button> </form> script.js function progress(position) { $("#result").text(`In progress. Please wait for 15 seconds.`); } function error(err) { console.warn(`ERROR(${err.code}): ${err.message}`); } function showPosition(position) { console.log(position); var latitude = position.coords.latitude; var longitude = position.coords.longitude; var accuracy = position.coords.accuracy; $('#id_latitude').val(latitude); $('#id_longitude').val(longitude); $('#id_accuracy').val(accuracy); $("#result").html(`Latitude: ${latitude}<br>Longitude: ${longitude}<br>Accuracy: ${accuracy}`); $("#btn_submit").attr("disabled", … -
hello_world() missing 1 required positional argument: 'request'
Please assist figuring out solution to this error. courses/ views.py from django.http import HttpResponse from django.shortcuts import render from .models import Course def course_list(request): courses = Course.objects.all() return render(request, 'courses/course_list.html',{'courses':courses}) admin/ views.py from django.shortcuts import render def hello_world(request): return render(request, 'home.html') admin urls.py from django.contrib import admin from django.urls import path from courses import views from django.conf.urls import include from . import views urlpatterns = [ path('admin/', admin.site.urls), path('admin/', views.hello_world()), path('courses/', include('courses.urls')), path('courses/', views.course_list(), name='listofcourses'), ] courses/ urls.py from django.urls import path from . import views urlpatterns=[ path('',views.course_list, name="listofcourses"), ] Now on running server, i am getting this error hello_world() missing 1 required positional argument: 'request' I wish to publish homepage on running server at 127.0.0.1:8000 and courses page on 127.0.0.1:8000/courses Thank you in advance