Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send data to view from form after asking for confirmation?
I created a simple form where I'm asking for user input and then posting that to the database. Now I would like the user to confirm the data in form is correct, and for that I'm using a Bootstrap modal. How can I send the data from the form to the view when pressing the 'OK' button on the modal. I'm new to the Django framework, and maybe there is another better way without using bootstrap modals. -
how to display errors of signup (or any) form and presenting same form to users?
I have a form called SignupForm for the users signup. I want to display the errors generated by the Django to the users if there is some introduced like password!=password2. I have tried everything but there are different types of errors. my template signup.html is {% extends 'blog/base.html' %} {% block content %} <h2>Sign up</h2> <form method="post" > {% csrf_token %} {% if form.errors %} <!-- Error messaging --> <div id="errors"> <div class="inner"> <p>There were some errors in the information you entered. Please correct the following:</p> <ul> {% for field in form %} {% if field.errors %}<li>{{ field.label }}: {{ field.errors|striptags }}</li>{% endif %} {% endfor %} </ul> </div> </div> <!-- /Error messaging --> {% endif %} {{ form.as_p }} <button type="submit">Sign up</button> </form> {% endblock %} and views.py is def signup(request): if request.method=='POST': form =SignupForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: err=form.errors return HttpResponseRedirect('/') else: form = SignupForm() #form=UserCreationForm() return render(request,'registration/signup.html',{'form':form}) There are different errors. For example, if I use else: err=form.errors return HttpResponseRedirect('/') it shows The current path, signup/signup, didn't match any of these and when I use return redirect('signup') it shows - 'str' object has no attribute 'get' and when I use a errors dictonary ``err=form.errors return … -
How to count records of each 12 months in django?
Here i am trying to count the students record that are added in the particular year's every month.I tried like this but didn't worked.I also got the database error.I am using mysql for the database. Exception Type: ValueError Exception Value: Database returned an invalid datetime value. Are time zone definitions for your database installed? models.py class Student(models.Model): name = models.CharField(max_length=100) courses = models.ManyToManyField(Course) joined_date = models.DateField(auto_now_add=True) views.py from django.db.models import Count from django.db.models.functions import TruncMonth students_according_to_month = Student.objects.annotate(month=TruncMonth('joined_date')).values('month').annotate(total=Count('pk')) print('students',students_according_to_month) -
Exclude constraint with partial index - Postgresql
I have the following tables: class Slot(models.Model): time_range = models.DateTimeRangeField() calendar = models.ForeignKey('Calendar') campaign = models.ForeignKey('Campaign', null=True) class Appointment(models.Model): calendar = models.ForeignKey('Calendar') campaign = models.ForeignKey('Campaign', null=True) slot = models.ForeignKey('Slot', models.DO_NOTHING, unique=True, null=True) timezone = models.CharField(max_length=120) I want to make Slot.time_range unique so not other slot overlap with it but just is that slot have an appointment. I have the following SQL so far ALTER TABLE appointments_slot ADD CONSTRAINT time_range_unique EXCLUDE USING gist (time_range WITH &&) WHERE (MISSING PART); Is there any way to join or something here, I have tried many ways without success. Maybe I will finish adding an appointment_id column to Slot table. -
Check Json data is none in python
this is my json may be thousands of record data we request in django rest framework. { "a":1, "b":2, "c":3, ..... } if request.data['a'] == '': return JsonResponse({'error':1}) elif request.data['b'] == '': return JsonResponse({'error':1}) elif ..... ....... else: ...... I want to check data is not blank like above if... else. we can add if else condition but this is not possible to check all data from if else Please suggest me what is the best way to check this line of code in python. -
Return data to ajax wihout invoking
I use one ajax to pass data, execute some code and finally return a populated list via second ajax. The problem is when the second ajax returns data, Javascript does not realise some data is returned. Even though Django has already processed and returned successfully. I get the poulated list when I call the ajax second time not the first and sometimes the list is not updated. My question is: Why Ajax does not get data each time Django returns? Is not possible to return data to ajax without invoking? Is there any other way to solve the problem? This is what I am trying: views.py data_list = [] def invoke_ajax(request): if request.method == 'POST': try: # call is made to 'process_data' function # this return is always successful return JsonResponse('invoked successfully', safe=False) except Exception as e: return JsonResponse("failed", safe=False) else: return JsonResponse("failed", safe=False) def process_data(request): # populates 'data_list' return get_data(request) def get_data(request): # sends data back to ajax # fails sometimes or list is not updated return JsonResponse(data_list, safe=False) Ajax // first ajax document.addEventListener('DOMContentLoaded', function(){ $.ajax({ url: '/invoke_ajax/', dataType: 'json', type: 'POST', data:{ 'movie': 'pets' }, success: function (response) { console.log("response= ",response); }, error: (error) => { console.log(error); } … -
How can I use objects ( not string ) in django email module
I'm developing some alert system. I want to use objects with django Email. as the code below; 'sshFailResult' is the object from some tasks. but that email send 'sshFailResult' of string type. how can I use objects with Email module ? thanks in advance. sshFailResult=[] for i in range(0,sizeOfList): sshFailResult=sshFailResult +[preSshFailResult[i].split("=>")[0] i +=1 sshFailEmail = EmailMessage('[SOC SYSTEM]','sshFailResult',to=['myEmailAddr']) if sshFailResult: sshFailEmail.send() else: pass -
Python basics for before starting learning Django
I want to learn Django and I need some suggestions on how to start learning Django and what python basics should I need to learn before starting learning Django. -
Do I need to commit .env files into the repository?
I have just started learning backend dev using django. This is a very basic question. I have done the following : 1. I have created virtual environment and I have also installed django in venv. 2. I have setup a django server and super admin. 3. I have setup the config.json to protect my API key. 4. Included the same in .gitignore. My question is do I just commit the project files in the server folder alone? or should I also commit the .env folder to the repository? What happens if I do commit or do not? Please advice -
Single Code Base for Cross Platform and Mobile Django Project
My goal is to eventually learn to create cross platform mobile apps using Django as the backend, and react native. I currently only have experience using Django, and Flask for web development on the backend, and html, css, and JavaScript for the front end. I currently have no experience with react native but will begin learning it soon My first cross platform app I want to create will be a web app, and cross platform marketplace app similar to Craigslist or Letgo. If I use Django and react, will I be able to have only one code base that is shared for the web, IOS, and Android? Also, is a market place app with Django and react-native realistic? -
How to properly install Python and Django
I'm trying to set up a Python/Django dev environment on my LinuxMint 19.1 machine. I installed the newest version of Python 3.7.3, Pip and Django. It seemed to be working until I figured out it was not using the correct version of Python. All attempts to correct this have been difficult. When I typed python -V it would display Python 2.x. When I typed python3 -V it would display Python 3.6.8. So I updated the alternatives and configured python so now when I type python -V I get Python 3.7.3 and when I type python3 -V I still get Python 3.6.8. I saw that I had to reinstall Django for it to be associated with the new version of Python so I tried to install again using Pip but got an error (the same ModuleNotFoundError: No module named 'pip' error as below). So I uninstalled Pip and reinstall it. I went ahead and installed Pip. sudo apt install python-pip This reported that it worked fine. I then tried to install Django and got the same error again. pip install django Traceback (most recent call last): File "/usr/bin/pip", line 9, in <module> from pip import main ModuleNotFoundError: No module named 'pip' … -
Saving many-to-many relationship through intermediate model
I have a model that looks like this: class Post(models.Model): title = models.CharField(max_length=100, null=False) content = HTMLField() created_at = models.DateField(auto_now_add=True) authors = models.ManyToManyField(User) When I create a post like this: x = Post(title="blah", content="blah) How can I add multiple authors to this Post? The authors model is created as an intermediate model and I have not defined it. -
How to redirect to profile page with id user paramater?
I want redirect to user profile after click "Profile" dropdown. But profile need id user, I don't know to link views.py def profile(request, user_id): #Something.... return render(request, 'profile.html') urls.py path('profile/<int:user_id>/', views.profile, name='profile'), profile.html <a class="dropdown-item" href="{% url ???? %}">Profile</a> -
How to read csv file in html?
I have a code and the thing I am not understanding is why a function of some_view in views.py is not fetching files from CSV. Is there something wrong? There is also html file by the name of index.html. I want it to fetch the first column of CSV and make a loop in html so that I don't have to repeat it every time. views.py def some_view(request): reader = csv.DictReader(open('file.csv','r')) csv_output = [] data = csv.reader(reader) for row in data: csv_output.append(row) return render(request, 'index.html', context={'csv_content': csv_output}) index.html {% for content in csv_content %} <div class="row"> {% for k in content.items %} <div class="column"> <p> value is {{v}} </p> </div> {% endfor %} </div> {%endfor%} -
How to save a new column in User's model
I added a new column to my register form and admin page in Django. I'm able to register using that column, but after registration the User doesnt have that column applied when I look at admin page. It should be grade*choicefield in register form and Employee class with department var inside to save a grade from register page to department column to my database. What I'm doing wrong?? models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='media') def __str__(self): return f'{self.user.username} - プロファイル' # recreate save function of django for specified save- resized def save(self, *args, **kawrgs): super().save(*args, **kawrgs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) # resize img.save(self.image.path) # save img class Employee(models.Model): #HERE user = models.OneToOneField(User, on_delete=models.CASCADE) #HERE department = models.CharField(max_length=100)#HERE def __str__(self):#HERE return f'{self.user.username} - プロファイル' #HERE def save(self, *args, **kawrgs): #HERE super().save(*args, **kawrgs) #HERE admin.py from django.contrib import admin from .models import Profile from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from .models import Employee from django.contrib.auth.models import User admin.site.register(Profile) # Define an inline admin descriptor for Employee model # which acts a bit like … -
while trying to use celery with django on ElasticBeantalk with Amazon -SQS and running, I am getting [Errno 13] Permission denied?
I am trying to use celery with django. I have deployed my site on eleasticBeanStalk. I am also using AMAZON-SQS. On running the command celery worker --app=prisons --loglevel == INFO [prisons is the name of my django app & I have ran this command from eb ssh] I get the following error Traceback (most recent call last): File "/opt/python/run/venv/local/lib/python3.6/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'db' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/python/run/venv/bin/celery", line 11, in <module> sys.exit(main()) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/__main__.py", line 16, in main _main() File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/celery.py", line 322, in main cmd.execute_from_commandline(argv) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/celery.py", line 496, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/base.py", line 298, in execute_from_commandline return self.handle_argv(self.prog_name, argv[1:]) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/celery.py", line 488, in handle_argv return self.execute(command, argv) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/celery.py", line 420, in execute ).run_from_argv(self.prog_name, argv[1:], command=argv[0]) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/worker.py", line 223, in run_from_argv return self(*args, **options) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/base.py", line 252, in __call__ ret = self.run(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bin/worker.py", line 257, in run **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/worker/worker.py", line 101, in __init__ self.setup_instance(**self.prepare_args(**kwargs)) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/worker/worker.py", line 141, in setup_instance self.blueprint.apply(self, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bootsteps.py", line 214, in apply step.include(parent) File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bootsteps.py", line 343, in include return self._should_include(parent)[0] File "/opt/python/run/venv/local/lib/python3.6/site-packages/celery/bootsteps.py", line 339, in _should_include return … -
Django Model DateField with only year as CharField?
In my Model I need to have Date field but with only year, standard DateField want from me also month and day, so I downloaded python package named partial_date_field, which adding Date type field but month and day are optional and everything was fine until I started creating view with filter, and unfortunatelly filter dont recognize PartialDateField type. So I'm wondering if it's ok to create Year field as CharField, is this a good solution? or maybe I can help my filter to recognize this custom type field "PartialDateField"? My Model: from django.db import models from partial_date import PartialDateField class Book(models.Model): title = models.CharField(max_length=75, verbose_name='Book title') authors = models.CharField(max_length=150, verbose_name='Authors') published_date = PartialDateField(verbose_name='Publishing date') pages = models.CharField(max_length=4, verbose_name='Number of pages') language = models.CharField(max_length=2, verbose_name='Language') image = models.URLField(verbose_name='Image', default=None, blank=True) my filter: class BookFilter(FilterSet): class Meta: model = Book fields = ['title', 'authors', 'language', 'published_date'] -
Get context from QuerySet in Django
I would like to filter a QuerySet depending on User's attributes. I have a QuerySet which looks like this {'paginator': None, 'page_obj': None, 'is_paginated': False, 'object_list': <QuerySet [<Event: Event object (1)>, <Event: Event object (2)>, <Event: Event object (3)>, <Event: Event object (4)>]>, 'event_list': <QuerySet [<Event: Event object (1)>, <Event: Event object (2)>, <Event: Event object (3)>, <Event: Event object (4)>]>, 'view': <cal.views.CalendarView object at 0x7fc7b0e062b0>} And I would like to be able to access a one value from all QuerySets. Name is a Choise*(column name in form) I'm using this code in views.py to get context(QuerySet) class CalendarView(LoginRequiredMixin, generic.ListView): model = Event template_name = 'cal/calendar.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) print(context) d = get_date(self.request.GET.get('month', None)) cal = Calendar(d.year, d.month) html_cal = cal.formatmonth(withyear=True) context['calendar'] = mark_safe(html_cal) context['prev_month'] = prev_month(d) context['next_month'] = next_month(d) return context -
Is there a way to authenticate a user over multiple WSGIDaemonProcesses?
I have two WSGIDaemonProcesses running on my apache server and I need users to be able to switch between them without logging in again on my Django app. One is for the HTTP server, the other for the HTTPS server. WSGIScriptAlias / /home/me/myproject/app/wsgi.py WSGIDaemonProcess https-www-my-app python-path=/home/me/myproject python-home=/home/me/myproject/venv WSGIProcessGroup www-my-app WSGIScriptAlias / /home/me/myproject/app/wsgi.py WSGIDaemonProcess www-my-app python-path=/home/me/myproject python-home=/home/me/myproject/venv WSGIProcessGroup www-my-app Is there a way that I can authenticate a user for both WSGIDaemonProcesses so that when a user goes from http://www.example.com to https://example.com they will remain logged in? Thanks for your help -
How can I store values in filtering fields in Django?
I'm trying to apply a filtering function in my website. After choosing options in the filtering fields, if you hit "Apply Filters" button, it submits the form tag and refreshes the page to bring an updated queryset. But, the fields get empy after submitting the form. The only way I think of here is use localStorage, but I was wondering if this can be done with Django. What can be the best practice to do that? -
string with negative value converted to float
I have django/python project, and a user enters a negative value as a string. But when I try to convert the string to a float I get an error. I understand that I am not using the hyphen or negative symbol but can not figure out how to replace the dash with a negative symbol. import os, sys from moneyed import Money from moneyed.localization import format_money moneystring = str('-$180.00') print Money(float(moneystring.strip("$").replace(',', '')), 'USD') Traceback (most recent call last): File "./moneytest.py", line 31, in print Money(float(moneystring.strip("$").replace(',', '')), 'USD') ValueError: could not convert string to float: -$180.00 Any Ideas? Thanks -
Cron job (using django_cron) not updating objects
I'm attempting to use a Cron Job to update the number of days each record in my database has been "open" for(ie. the number of days between today and the created date). The logic I'm using is for the cron job to run every night at 23:00 and to update the days_open field (IntegerField) by F('days_open') + 1 each time the job runs. I've set the run-time to once a minute for testing purposes. I've run "python manage.py runcrons "request_form_app.cron.DaysOpenCronJob" and " python manage.py runcrons --force" to force the jobs, and I receive no errors but the field is not updating on any of the records. settings.py 'request_form_app.cron.DaysOpenCronJob', ]``` cron.py ```from django_cron import CronJobBase, Schedule from django.db.models import F class DaysOpenCronJob(CronJobBase): RUN_EVERY_MINS = 1 # RUN_AT_TIMES = ['23:00'] schedule = Schedule(run_at_times=RUN_EVERY_MINS) code = 'request_form_app.cron.DaysOpenCronJob' def update_days(self,*args,**kwargs): data_request = Request.objects.all() for record in data_request: record.days_open = F('days_open') + 1 record.save(update_field=['days_open'])``` -
Problems with adding social_django to wagtail
I added this url in /projectname/urls.py: url(r'social-auth/', include('social_django.urls', namespace='social')), And then I added this in my wagtail homepage template (as shown in docs example): {% for name in social_auth.backends.oauth %} <li><a rel="nofollow" href="{% url "socialauth_begin" %}">{{ name|title }}</a></li> {% endfor %} But i saw nothing in template, but I have added AUTHENTICATION_BACKENDS = ( 'social_core.backends.open_id.OpenIdAuth', # for Google authentication 'social_core.backends.google.GoogleOpenId', # for Google authentication 'social_core.backends.google.GoogleOAuth2', # for Google authentication 'django.contrib.auth.backends.ModelBackend', ) in settings/base.py. So how can I implement authentication in wagtail CMS, so users can add comments to blog? -
Why the form return 'Method not allowed' while extending CreateView CBV in DJANGO
I am not sure what is not working correctly here. I have extended the CreateView to include a form. when I try to click on submit I receive the 'error' Method Not Allowed (POST) forms.py class DateInput(forms.DateInput): input_type = 'date' class BookingForm(forms.ModelForm): class Meta: model = Booking fields = ('check_in', 'check_out') widgets = { 'check_in': DateInput(), 'check_out': DateInput() } class PropertyDetailView(DetailView): model = PropertyListing context_object_name = 'name' template_name = 'core/property-detail.html' def get_context_data(self, *args, **kwargs): context = super(PropertyDetailView, self).get_context_data(**kwargs) context['property_details'] = PropertyListing.objects.filter(pk=self.kwargs.get('pk')) # Form context['form'] = BookingForm() return context just the form HTML <form class="col-sm-3" role="form" action="" method="POST"> {% csrf_token %} {{ form|crispy }} <input class="btn btn-primary" type="submit" value="Create" /> </form> Does anybody have an idea why? -
How to make a login view for django custom user?
I have made a custom user model using the AbstractUser , removed the username and replaced it with email and extended the model, tried creating superuser and it worked and also created some users by a signup form , logged in the admin interface and it worked however when tried to create a login form for the users it fails I tried this but it didn't work def LoginView(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request,user) return redirect('accounts:login') else: form = AuthenticationForm() return render(request,'accounts/login.html', {'form':form}) then i tried this class LoginView(FormView): form_class = AuthenticationForm template_name = 'login.html' def form_valid(self, form): email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = authenticate(email=email, password=password) # Check here if the user is an admin if user is not None and user.is_active: login(self.request, user) return HttpResponseRedirect(self.success_url) else: return self.form_invalid(form) Obviously i expect the user to be logged in i think the code in this post is badly formatted. mainly it's my fault as i'm new to this platform