Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot resolve keyword 'is_active' into field?
I have the Django allauth package included into my project. I am trying to create a custom view of the reset password page with also a custom form. Here's what I have: urls.py urlpatterns = [ url(r'^password/reset/$', views.ResetPasswordView.as_view(), name='password-reset'), ] views.py class ResetPasswordView(PasswordResetView): template_name = 'account/password-reset.html' form_class = ResetPasswordForm forms.py class ResetPasswordForm(PasswordResetForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['email'].label = "" self.fields['email'].widget = forms.EmailInput(attrs={"placeholder": "Email Address"}) However, for some reason when I enter an email address to reset a password, I get the following error: FieldError at /password/reset/ Cannot resolve keyword 'is_active' into field. Choices are: Profile, Profile_id, active, admin, date_joined, email, emailaddress, When I remove the form_class from the view and use the default form, it works correctly. Why is it not working when I add the custom form? -
How to manipulate value of one Model Field from another Model?
I have two models class Employee(models.Model): name = models.CharField(max_length=20) ID = models.IntegerField() basic_salary = models.IntegerField() total_leave = models.IntegerField(default = 14) paid_leave = models.IntegerField(default = 0) unpaid_leave = models.IntegerField(default = 0) def __str__(self): return self.name class Leave_management(models.Model): name = models.OnetoOneField(Employee,on_delete= models.CASCADE) reason = models.CharField(max_length=50) from = models.DateTimeField() to = models.DateTimeField() total_days = models.IntegerField() def __str__(self): return self.name So,i want to minus 'total_days' of 'model-Leave_management' from 'total_leave' field of 'model-Employee'. And as per leaves taken i want to update 'paid_leave' and 'unpaid_leave' sections. I can perform so if these two models would be one model, But i dont know how to perform so in different models. def save(self,*args,**kwargs): if self.total_days<=self.total_leave: self.total_leave -= self.total_days self.unpaid_leave = 14 - self.total_leave else: self.total_days -= 14 self.paid_leaves = self.total_days super(Model_name,self).save(*args,**kwargs) ` Please be guiding me. -
How to send selected checkbox values to view
I am storing all the selected checkbox values in a javascript variable. I need to send it back to the view for further processing. $('#source_search_submit').click(function(){ // Create an array for the values var values = []; // Select all checkboxes by class name, and use the jQuery :checked special selector $('.filled-in:checked').each(function() { // Adds the value to the values array values.push($(this).val()); string = string + ($(this).val()) }); // Log all values console.log(values); }) How can send the "values" back to django view for further processing? I tried ajax call and it didn't work. -
django Parent model not picking related child model
I am having trouble understanding how to link models in Django. Here are my models: from django.db import models import datetime # Create your models here. class VirtualCenter(models.Model): name = models.TextField(max_length=60) data_center = models.ManyToManyField('DataCenter', blank=True, through='VirtualCenterDataCenter') class Meta: verbose_name_plural = "Vc's" class DataCenter(models.Model): name = models.TextField() virtual_center = models.ForeignKey(VirtualCenter,null=True) class VirtualCenterDataCenter(models.Model): added = models.DateField(default=datetime.date.today, blank=True, null=True) data_center = models.ForeignKey('DataCenter') status = models.TextField(max_length=12, default='Active') virtual_center = models.ForeignKey('VirtualCenter') class Meta: unique_together = ('virtual_center', 'data_center') and here is a unit test I wrote to verify I can use the above models. class VirtualCenterModelTests(TestCase): def test_insert_into_VCModel(self): # verify there are no VirtualCenter records count = VirtualCenter.objects.count() self.assertEqual(count,0) # add a VirtualCenter record and verify it was added to the DB vc = VirtualCenter.objects.create( name = 'test-vc' ) count = VirtualCenter.objects.count() self.assertEqual(count,1) # verify the virtualcenter does not have any datacenters self.assertEqual(vc.data_center.count(),0) # count = DataCenter.objects.count() self.assertEqual(count,0) # add a DataCenter record and verify it was added to the DB dc = DataCenter.objects.create( name = 'test-dc' ) count = DataCenter.objects.count() self.assertEqual(count,1) # tie the datacenter record to the virtualcenter record vcdc = VirtualCenterDataCenter(virtual_center=vc,data_center=dc) vc.refresh_from_db() self.assertEqual(vc.data_center.count(),1) When I run my test it fails like so: self.assertEqual(vc.data_center.count(),1) AssertionError: 0 != 1 Why doesn't vc.data_center.count() return 1? -
Postgres/Django: ProgrammingError: permission denied for relation auth_user
I'm trying to create a new postgres user so I don't have to give my personal credentials to another developer. I want this new user to have access to only one database (there are db and db_dev databases) The problem is that shell_plus says that he doesn't have permissions for particular relation. What I have done: sudo -u postgres psql CREATE USER guest WITH PASSWORD 'password'; GRANT ALL PRIVILEGES ON DATABASE db_dev TO guest; Which didn't worked, so I tried: GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO guest; But shell keeps raising this error: >>> User.objects.all() >>> ProgrammingError: permission denied for relation auth_user The weird thing is that development server works without problems (accessing db). Do you know what to do to make it work? -
change django language by <a> click
i have next code: <form action="{% url 'set_language' %}" method="post" id="set_lang_form">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"/> <input type="hidden" name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info for LANGUAGE_CODE as lang %} {% get_language_info_list for LANGUAGES as languages %} {% static "" as baseUrl %} <a id="languages" rel="nofollow" class="nav-link language dropdown-toggle" data-toggle="dropdown" href="#"> <img class="flag-lang" src="{{ baseUrl }}img/flags/16/{% if LANGUAGE_CODE == 'en' %}GB{% else %}{{ lang.code }}{% endif %}.png" alt="lang"> {{ lang.name_local }}</a> <ul aria-labelledby="languages"class="dropdown-menu"> {% for language in languages %} {% if LANGUAGE_CODE != language.code%} <li> <a class="dropdown-item" href="#{{ language.code }}" onclick="set_language('{{ language.code }}')"> <img class="mr-2" src="{{ baseUrl }}img/flags/16/{% if language.code == 'en' %}GB{% else %}{{ language.code }}{% endif %}.png" alt="{{ language.name_local }}"> {{ language.name_local }}</a> </li> {% endif %} {% endfor %} </ul></form> How to change language by clicking the link from the li ? Big thx for help -
Configuring Django Database settings when hosting with Heroku
I've been trying to host my Django application using Heroku, however I learned that it uses a Postgres database. How am I supposed to configure my DATABASE settings in settings.py? I am currently running Django 1.11. I have psycopg2 version 2.6.2 but I keep getting the following build error when heroku is attempting to deploy my app: Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-aquz7vec/psycopg2/ ! Push rejected, failed to compile Python app. ! Push failed Any ideas? -
dynamic calculations for fields using form fields in django
When I generate a form in forms.py for my model in models.py and just pass it into a HTML page, how do I get the data back using POST in views.py and do some calculations to get values for some other fields in the same model? The exact scenario is in this question. The code is also there. Django fields in form I'm asking this related to the 2nd and 4th question in the above link. Thank you. -
Correctly rendering a list that's called through view function
I previously asked this question, but it was hijacked by a troll. Here's a new one: I have the following class in views.py. My goal is to click on a list item and see its detailview template, on which should be another list of items, all associated with this particular list item. class Posts(DetailView): model = Book template_name='books/post_create.html' slug_field = 'id' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['post'] = Post.objects.all() return context Right now, with this in the template: <p>{{post}}</p> it's showing (on the website): <QuerySet [<Post: This is post 1>, <Post: This is post 2>, <Post: This is post 4>, <Post: This is post 5>]> How can I make only the post names show? ("This is post 1" and others are the names I inputted). Also on the template is: <ul> {% for post in object_list %} <div class='ui card'> <a class="content"> <div class="header">{{ post }}</div> </a> </div> {% empty %} <h5>You don't have any posts!</h5> {% endfor %} </ul> This output on the website says only "You don't have any posts!" What's wrong, and how can I make it work? I think object_list does not belong here; what should I put here instead? Thank you so much for … -
Django wraps cookie in quotes
I'm trying to set a cookie on a response in Django. When I do the following: response.set_cookie('test', 'http://www.google.com') The cookie that being set on the browser is actually "http://www.google.com" instead of the desired http://www.google.com Why is django or perhaps Morsel wraps the cookie in quotes only because of having / in the cookie? Is there a way to not make this happen? Thanks! -
Travis ci encode env variables failing for other github users on project
I cannot seem to find anywhere that talks about how to allow travis ci encode env variables to work for other users on github. I am using travis ci with a django project. Current .travis.yml file: language: python python: - 3.6 env: global: - secure: # encrypted string for SECRET_KEY - secure: # encrypted string for another settings KEY - secure: # encrypted string for another settings KEY install: - pip install -r requirements/requirements.txt script: - flake8 --count --quiet - python manage.py migrate --run-syncdb - python manage.py test This works fine for me when I push a patch up, travisci runs the checks fine. But when anyone else does (or even me using another github account) travis ci fails saying it cannot find SECRET_KEY which is one of the secure encoded env variables I have in .travis file. -
uwsgi + nginx vs apache + mod-wsgi differences at long-pooling implementation
I've implemented a django application that among other things also implements a long-pooling request for retrieving new system events to the client. To be more specific: the request waits (in django code) up to 30 seconds for new events before returning a response back to the client. This system worked perfectly under apache + mod-wsgi without any special settings. mod-wsgi was set to 2 processes and 12 threads and this worked just fine. However, changing the server to nginx + uwsgi introduced a problem for me: I start getting 502 errors when I have more than processes * threads requests pending to the server. As you can imagine, this started happening immediately after deploy as I set uwsgi to only spawn core_count processes. I'd attach the configs, but don't believe they would help: I just followed the tutorials. There's no special stuff in there. And I imagine uwsgi has a mechanism for handling this properly. Is there any prescribed way of doing long-pooling on uwsgi? -
Django not filtering by date
I have an Appointment model as follows: class Appointment(models.Model): start_date = models.DateTimeField(null=True) I have 3 entries for testing purposes: Appointment.objects.all() returns <QuerySet [<Appointment: 2018-06-13 14:00:00-04:00>, <Appointment: 2018-06-13 12:00:00-04:00>, <Appointment: 2018-06-14 14:30:00-04:00>]> today is: today = timezone.now() 2018-06-13 18:59:09.884977+00:00 I want to get tomorrow appointments, so I do: tomorrow = today.date()+datetime.timedelta(days=1) appointments = Appointment.objects.filter(start_date__date=tomorrow) or appointments = Appointment.objects.filter(start_date__date=datetime.date(tomorrow.year, tomorrow.month, tomorrow.day)) or appointments = Appointment.objects.filter(start_date__year=tomorrow.year, start_date__month=tomorrow.month, start_date__day=tomorrow.day) In any case it should return a Queryset with one entry, but returns an empty one. Anyone? -
Django structure... with form action and views.py
So I am creating a simple app that has two html pages. first function on view is addDatabase where I can display the design of form using modelform. def addDatabase(request): if request.method == 'POST': form = YamlForm(request.POST) if form.is_valid(): form.save() # return HttpResponseRedirect('niro/output.html', {'form': form}) return HttpResponseRedirect(reversed('niro:output'), {'form': form}) else: form = YamlForm() return render(request, 'niro/addDatabase.html', {'form': form}) second function on view is output where I display output of userinput from the first page. def output(request): Form_info.objects.all() name = request.POST.get("name") type = request.POST.get("type") vlan_id = request.POST.get("vlan_id") rdp = request.POST.get("rdp") ip_master = request.POST.get("ip_master") ip_backup = request.POST.get("ip_backup") vip = request.POST.get("vip") nat_ip = request.POST.get("nat_ip") cidr = request.POST.get("cidr") dns = request.POST.get("dns") dhcp = request.POST.get("dhcp") dhcp_pool_start = request.POST.get("dhcp_pool_start") dhcp_pool_end = request.POST.get("dhcp_pool_end") form = Form_info(name=name, type=type, vlan_id=vlan_id, rdp=rdp, ip_master=ip_master, ip_backup=ip_backup, vip=vip, nat_ip=nat_ip, cidr=cidr, dns=dns, dhcp=dhcp, dhcp_pool_start=dhcp_pool_start, dhcp_pool_end=dhcp_pool_end) context = { 'form': form } return render(request, 'niro/output.html', context) In my adDatabase.html file, I have form action and poast method that is pointing my second function of html file. <form action="{% url "output" %}" method="post"> {% csrf_token %} I keep getting an error because once I set form action="{% url "output" %}", my validation that I worked on forms.py won't work. if I delete form action="{% url "output" … -
uwsgi + nginx: status 502 on heavy load
I have this nginx + uwsgi + django application which works pretty well. But when load on server gets a bit heavier, I start getting these 502 errors on random requests. Here's the relevant section of uwsgi.ini: master = true #more processes, more computing power processes = 32 threads = 3 post-buffering = 1 # this one must match net.core.somaxconn listen = 8000 I have this huge number of processes to handle larger numbers of simultaneous requests - and I even added some threads on top of that - but I must admit I expected the listen directive should handle that. In reality it seems 502 errors start happening the moment I exceed 32 * 3 simultaneous requests. The way I understood it, listen should allow up to 8000 (in this case) of active connections, waiting to be served by the server, but it doesn't seem to have any serious effect. uwsgi log clearly says this is active: your server socket listen backlog is limited to 8000 connections But I seem to be misunderstanding the effect of the setting. Anyway, I'd just like to solve the 502, so I'm open for suggestions in any direction. -
How add auto SlugField for inline model in Wagtail>=2.x
Search true Wagtail way for add Slug autofill field functional for sting fields, how this do standart Django admin backend. Please help -
Tango With Django - Django 2.0
Im practicing Tango With Django but having this unexpected error, which i am unable to debug. views.py def index(request): category_list=Category.objects.order_by('-likes') context_dict = {'categories':category_list} return render(request,'index.html',context_dict) def show_category(request, category_name_slug): # Create a context dictionary which we can pass # to the template rendering engine. context_dict = {} try: category = Category.objects.get(slug=category_name_slug) pages = Page.objects.filter(category=category) context_dict['pages'] = pages context_dict['category'] = category except Category.DoesNotExist: context_dict['category'] = None context_dict['pages'] = None return render(request, 'category.html', context_dict) url.py urlpatterns =[ path('',views.index, name = 'index'), path('category/<slug:category_name_slug>/',views.show_category,name = 'category_view') models.py class Category(models.Model): name = models.CharField(max_length= 200, unique=True) likes= models.IntegerField(default=0) views = models.IntegerField(default=0) slug = models.SlugField() class Meta: verbose_name_plural = 'Categories' def save(self,*args,**kwargs): self.slug = slugify(self.name) super(Category,self).save(*args,**kwargs) def __str__(self): return self.name class Page(models.Model): category = models.ForeignKey(Category,on_delete=models.CASCADE) title = models.CharField(max_length=200) URL = models.URLField() views = models.IntegerField(default=0) def __str__(self): return self.title First part of views.py is over,im able to show list views of categories, but when i click any one of them then it gives error in traceback given below category = Category.objects.get(slug=category_name_slug) I have added picture of that error, please be seeing it -
Uploading on Django with Boto3
So I've been working on a Django site and I'm rather stuck. I can't seem to figure out how to properly use Boto3 to upload files to a Digital Ocean Space. I have a python script that does what I want, but I can't figure out how to make it work with Django on a web page. I've read through a lot of documentation but I can't seem to find a clear answer. Also all the examples are using AWS. Here is the code that I have so far: Python Upload Script: from boto3 import session from botocore.client import Config ACCESS_ID = '-----' SECRET_KEY = '-----' # Initiate session session = session.Session() client = session.client('s3', region_name='nyc3', endpoint_url='https://nyc3.digitaloceanspaces.com', aws_access_key_id=ACCESS_ID, aws_secret_access_key=SECRET_KEY) # Upload file to Space 'from folder/file','space to put','name it will become' def run(upfile): client.upload_file(upfile, 'yl2-test', 'test/storage-test') views.py: from django.shortcuts import render from django.shortcuts import redirect from django.contrib.auth import authenticate, login from django.http import HttpResponseRedirect from .forms import CharacterForm, SignUpForm from scripts.test_upload import run def index(request): return render(request, 'YL2/index.html') def new_char(request): # return render(request, 'YL2/new_char.html') # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it … -
Django spacing between fields in form
I am a beginner in Django, hence this might be a simple issue. But I'm not able to get past this successfully. This is my models.py class Category(models.Model): name = models.CharField(max_length=128) abbr = models.CharField(max_length=5) def __unicode__(self): return self.name class Fabric(models.Model): name = models.CharField(max_length=128) abbr = models.CharField(max_length=5) def __unicode__(self): return self.name class Manufacturer(models.Model): name = models.CharField(max_length=128) location = models.CharField(max_length=128) name_abbr = models.CharField(max_length=5, default=None) loc_abbr = models.CharField(max_length=5, default=None) def __unicode__(self): return self.name class Images(models.Model): design_id = models.CharField(max_length=128) file = models.ImageField(upload_to='images') cost_price = models.FloatField() category = models.ForeignKey(Category, on_delete=models.CASCADE) fabric = models.ForeignKey(Fabric, on_delete=models.CASCADE) manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE) selling_price = models.FloatField() aliveness = models.IntegerField() date_added = models.DateTimeField(default=datetime.datetime.now) set_cat = models.IntegerField() set_cat_no = models.IntegerField() set_cat_name = models.CharField(max_length=50, blank=True) I'm building an apparel management database system which contains cloth designs. My forms.py is class ImagesForm(forms.ModelForm): class Meta: model = Images fields = ('file','cost_price','set_cat_no','set_cat_name',) My views.py @login_required def uploadphoto(request): context = RequestContext(request) context_dict = {} if request.method == 'POST': form = ImagesForm(request.POST,request.FILES) if form.is_valid(): image = form.save(commit=False) image.save() return render_to_response(request,'cms/upload-photo.html', {'upload_image': form}) else: print form.errors else: form = ImagesForm() context_dict = {'upload_image': form} return render_to_response('cms/upload-photo.html',context_dict, context) My upload-photo.html is {% block main %} <form id="upload_form" method="post" action="/zoomtail/upload-photo/" enctype="multipart/form-data"> {% csrf_token %} {{ upload_image }} </form> {% endblock %} … -
Django - Set header for redirect
Django 2.0 I need to set a header when redirecting a user to an external url. Is this at all possible? I've tried response = HttpResponseRedirect(url) response['custom'] = 'custom_header' return response -
filter model using manytomanyfield
I've got these models : work.py class Work(models.Model): ... network = models.ManyToManyField(Network,related_name='network') network.py class Network(models.Model): ... users = models.ManyToManyField(User, related_name="users") In my view.py I got this class-based generic ListView class WorkList(PermsMixin, ListContextMixin, ListView): model = Work # Here I want to filter queryset What I want to do is to filter the queryset such that the logged in user is in the network users. I tried many things, for example queryset = Work.objects.all() queryset.filter('self.request.user__in=network_users') But I got this error: ValueError : too many values to unpack (expected 2) Can anyone help me please? -
Configuring Python Virtual Environment to use Python 3
I am learning the Python Django framework. I installed two different versions of python on my laptop, 2 and 3. I configured my Laptop to use python 3. So when I check version using the command line, I got this output. Then I installed the Django and Python Virtual Environment following this link, https://djangobook.com/installing-django/. I could install the Django and Virtual Environment successfully. But my virtual environment is using the python 2. When I check the version in the virtual environment, I got this output. So, how can I configure that virtual environment to use python 3 instead of 2? Or how can I set the Python version to be used when I set up the Environment for the Django? -
Google App engine flexible deploy
I am trying to deploy a Django app in App Engine Flexible. After the deploy, the /_ah/health returns always 499 status code (the client has closed the connection before the server answered the request). If I deploy the app with App Engine Standard the server is reachable and works fine. Did anyone have this problem? What exactly is the cause? For what I have understood it seems that server is not working properly and drop the connection made by the /_ah/health/ This is my app.yaml deploy config: runtime: python env: flex service: <service_name> entrypoint: gunicorn -b :$PORT <app>.wsgi builtins: - deferred: on manual_scaling: instances: 1 beta_settings: cloud_sql_instances: <project_id>:<zone>:<db_name> env_variables: DEBUG: True DB_NAME: **** DB_USER: **** DB_PASS: **** CLOUD_PROXY: /cloudsql/<project_id>:<zone>:<db_name> STATIC_URL: https://storage.googleapis.com/<bucket_name>/static/ DJANGO_SECRET_KEY: ********************************************** -
Django ajax image upload and cropped image saving
I want to upload image with ajax, crop the uploaded image and save the image. I uses pillow 5.1.0., django 2.0.5. models.py: class TestPhoto(models.Model): file = models.ImageField() forms.py: class TestPhotoFrom(forms.ModelForm): # this is not necessary part, you can ignore it. x = forms.FloatField(widget=forms.HiddenInput()) y = forms.FloatField(widget=forms.HiddenInput()) class Meta: model = TestPhoto fields = ('file', 'x', 'y',) template.html: <form method="post" enctype="multipart/form-data" id="formUpload"> {% csrf_token %} {{ form }} </form> <button class="js-crop-and-upload">button</button> <script> $(function () { $(".js-crop-and-upload").click(function () { //Get file from form. var form_upload = $("#formUpload")[0]; var form_data = new FormData(form_upload); //Send file with ajax. $.ajax({ url:'/crop/', type:'post', dataType:'json', cache:false, processData: false, contentType: false, data:{ 'file': form_data, 'value': 'test_value', }, success:function (data) { console.log(data) } }); }); }); </script> views.py: def crop(request): if request.method == "GET": form = TestPhotoFrom() return render(request, 'authapp/crop.html', {'form': form}) else: if request.is_ajax(): # get file from request. file = request.FILES image = Image.open(file) # cropping image cropped_image = image.crop((0, 0, 200, 200)) resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS) # save cropped image resized_image.save() return JsonResponse({'success': 'file_uploaded'}) I read this: https://simpleisbetterthancomplex.com/tutorial/2017/03/02/how-to-crop-images-in-a-django-application.html And now I need to do that with jquery-ajax. But when I click button to do ajax request, server console is printing this error: 'MultiValueDict' object has … -
List on a DetailView template not rendering as intended
I have the following class in views.py. My goal is to click on a list item and see its detailview template, on which should be another list of items, all associated with this particular list item. class Posts(DetailView): model = Book template_name='books/post_create.html' slug_field = 'id' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['post'] = Post.objects.all() return context Right now, with this in the template: <p>{{post}}</p> it's showing (on the website): <QuerySet [<Post: This is post 1>, <Post: This is post 2>, <Post: This is post 4>, <Post: This is post 5>]> How can I make only the post names show? ("This is post 1" and others are the names I inputted). Also on the template is: <ul> {% for post in object_list %} <div class='ui card'> <a class="content"> <div class="header">{{ post }}</div> </a> </div> {% empty %} <h5>You don't have any posts!</h5> {% endfor %} </ul> This output on the website says only "You don't have any posts!" What's wrong, and how can I make it work? Thank you so much for your help.