Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get only one field by comparing other field of same model in view file of Django
I want to run this query: "SELECT pname FROM PaientSignup WHERE email=p_email" I used filter method that gives me all other data that match with email given. p= PatientSignup.objects.filter(email=p_email) From that output I could not able to fetch on name of patient. models.py class PatientSignup(models.Model): pid = models.AutoField(verbose_name='Patient Id', primary_key=True, auto_created=True) pname = models.CharField(verbose_name='Enter Name', max_length=50, default=NameError) email = models.CharField(verbose_name='Enter Email', max_length=100,unique=True) age = models.PositiveIntegerField(verbose_name='Enter age',default=5, null=True) password = models.CharField(verbose_name='Enter Password',max_length=12) views.py def pFeedback(request): #feedback = textarea input p_email = request.session['pusername'] #here, I want only patient name->pname to store in database saveFeedback = patientFeedback() saveFeedback.feedback = feedback saveFeedback.patientName = patient saveFeedback.save() -
Aldryn article meta options not appearing in webpage page source
I am using Aldryn Newsblog for article management on a website built on Django CMS. Aldryn allows us to add meta options to each article, please refer to picture. My inputs for meta title and meta description are not showing in the webpage page source. Will like to seek help for this please, thank you. -
Edit password of user in admin panel
I've overwrite "save_model" method to manage user's password in my admin's panel application. What I want is: Create a new random password when I create new user (if password field is empty) Encrypt the password (if I set it) Use user's password (if I change user but not set the password) How can I define the last condition? def save_model(self, request, obj, form, change): if not change and (not form.cleaned_data['password']) : password = User.objects.make_random_password() obj.set_password(password) elif form.cleaned_data['password'] : obj.set_password(form.cleaned_data['password']) else ? super(UserAdmin, self).save_model(request, obj, form, change) -
How to save multiple selections
My question is how can I save Tags on admin and localhost. Currently, my admin can only add new tags but can't save any options I selected. Admin | Localhost-edit_page Also, I don't know how to make the format of ModelMultipleChoiceField look like a normal text field, but once the field has focus I can select any option and it will be added into the field, click again and I can select another option, building up any number of options. example models.py class Tag(models.Model): -
Django on Nginx connection refused
I want to run my django app on nginx webserver + gunicorn. I have setup most of the stuff already following tutorials and got to the point where I need to setup Nginx. I have my app in: /home/ec2-user/davidbien That's also where my virtualenv is installed. Inside davidbien folder I have the below script guni.sh: #!/bin/bash set -e LOGFILE=/home/ec2-user/davidbien/logs/guni.log LOGDIR=$(dirname $LOGFILE) NUM_WORKERS=3 # user/group to run as USER=ec2-user GROUP=ec2-user ADDRESS=0.0.0.0:8000 cd /home/ec2-user/davidbien source /home/ec2-user/virtual/bin/activate test -d $LOGDIR || mkdir -p $LOGDIR exec gunicorn_django -w $NUM_WORKERS --bind=$ADDRESS \ --user=$USER --group=$GROUP --log-level=debug \ --log-file=$LOGFILE 2>>$LOGFILE This seems to be running fine as I don't get anything when running it. I can also run the app using gunicorn davidbien.wsgi:application --bind 0.0.0.0:8000 This works fine. Now, I get to nginx setup. I installed it and created two folders - sites-available and sites-enabled inside /etc/nginx/. I then created a file test.conf inside sites-available and inserted the below code inside: upstream app_server_djangoapp { server 35.177.26.219:8000 fail_timeout=0; } server { listen 80; server_name 35.177.26.219; access_log /var/log/nginx/guni-access.log; error_log /var/log/nginx/guni-error.log info; keepalive_timeout 5; # path for static files root /home/ec2-user/davidbien/davidbien/static; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://app_server_djangoapp; break; } … -
admin não esta logando django
Boa tarde meus caros. Estou implementando um projeto utilizando django + postgresSQL. Neste projeto estou usando email como USERNAME_FIELD.Executei o comnado python manage.py createsuperuser e ao tentar logar com o usuário criado no admin do django não funciona. Alguém já passou por situação parecida? Quando utilizava o sqlite3 como base padrão não dava problema. Preciso usar o postgreSQL pois estou utilizando o postgis. Vide model de usuário: class EmailUserManager(BaseUserManager): def create_user(self, *args, **kwargs): email = kwargs["email"] email = self.normalize_email(email) password = kwargs["password"] kwargs.pop("password") if not email: raise ValueError(_('Favor inserir seu e-mail')) user = self.model(**kwargs) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, *args, **kwargs): user = self.create_user(**kwargs) user.is_superuser = True user.is_admin = True user.save(using=self._db) return user class User(PermissionsMixin, AbstractBaseUser): name = models.CharField( 'Nome', max_length=100, blank=True ) surname = models.CharField( 'Nome', max_length=100, blank=True ) email = models.EmailField( verbose_name=_('E-mail'), max_length=255, unique=True ) #user_type = models.IntegerField("Sou Cliente/Empresa", choices = USER_TYPE_CHOICES, default="1", null=True, blank=True) avatar = models.ImageField("Avatar") is_active = models.BooleanField('Está ativo?', blank=True, default=True) is_staff = models.BooleanField('É da equipe?', blank=True, default=False) is_admin = models.BooleanField(default=False) date_joined = models.DateTimeField('Data de Entrada', auto_now_add=True) USERNAME_FIELD = 'email' objects = EmailUserManager() def __str__(self): return self.name or self.email def get_short_name(self): return self.email def get_full_name(self): return str(self) class Meta: verbose_name = 'Usuário' verbose_name_plural = … -
To use Turbolinks 5 with Django, how can I automate the inclusion of Turbolinks-Location when using redirect()?
According to the Turbolinks 5 documentation for "Following Redirects" (https://github.com/turbolinks/turbolinks#following-redirects): When you visit location /one and the server redirects you to location /two, you expect the browser’s address bar to display the redirected URL. However, Turbolinks makes requests using XMLHttpRequest, which transparently follows redirects. There’s no way for Turbolinks to tell whether a request resulted in a redirect without additional cooperation from the server. And the solution for this is to: send the Turbolinks-Location header in response to a visit that was redirected, and Turbolinks will replace the browser’s topmost history entry with the value you provide. The Turbolinks Rails engine performs this optimization automatically for non-GET XHR requests that redirect with the redirect_to helper. I have a great interest in using Turbolinks on my Django (1.11) project and I'm wondering if anyone could point me in the right direction of how to create a new Django redirect() function or modify the existing one to always include the Turbolinks-Location header that is needed for redirects to function as expected. I definitely do not want to be manually setting this header every time I do a redirect. There is a similar entry in the 'Redirecting After a Form Submission' section (https://github.com/turbolinks/turbolinks#redirecting-after-a-form-submission) … -
Using Django and Ajax to dynamically update information not working
When I have a many-to-many field that I want to change dynamically (ie, from the view to update the database without refreshing the entire page), such as when a user clicks a 'Follow' button for an object (as many different users can follow many different objects) then Ajax will make the request and the database will be updated. However, this Ajax call does not seem to work for dynamically changing a boolean property (changing something to True or False) for any given object. This class-based view works to dynamically add or remove a user: if user.userprofile in obj.followers.all(): following = False obj.followers.remove(user.userprofile) else: following = True obj.followers.add(user.userprofile) updated = True However, this code does not work to change an attribute to True or False: if user.is_authenticated(): if user.userprofile.content_pref == True: display = False user.userprofile.content_pref = False else: display = True user.userprofile.content_pref = True updated = True How might I achieve this effect? Through clicking on a button, I want a user to toggle their model object attribute from False to True or vice-versa...Thanks -
Getting related objects via tags in Django
My goal is to build a "Recommended Products" section in my e-commerce website when accessing an individual product page. I have a sereis of products which have several user-defined tags in the admin. The tagging system is a combination of django-taggit and modelcluster, as detailed in the Wagtail-CMS docs. I am trying to make it so that when a product page is accessed, Django looks at all other products with the same/similar tags and lists them in the "Recommended Products" section, based on the number of identical tags. The django-taggit docs seem to address this need in their API with the get_related() function, as per their docs. I am struggling to get this working however as I keep on encountering errors, the latest being Exception Type: KeyError at /categories/test-category/test-product/ Exception Value: (15,). Here's my code so far: class ProductTag(TaggedItemBase): content_object = ParentalKey('Product', related_name='tagged_items') class Product(Page): ... tags = ClusterTaggableManager(through=ProductTag, blank=True) def get_context(self, request): context = super(Product, self).get_context(request) current_tags = self.tags related_products = Product.objects.filter(current_tags.similar_objects()) context['related_products'] = related_products return context -
Extending the Django 1.11 User Model
I am attempting to work out how to extend the Django user model to add information to a user. I can't seem to get it to work. What am I doing wrong? Is it okay to have foreignkeys within the same model I am extending in to? How do you create a superuser, or do you have to do it manually through the python manage.py shell? Here's my code so far: class PersonModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) firstName = models.CharField(max_length=50) lastName = models.CharField(max_length=50) company = models.ForeignKey(CompanyModel, on_delete=models.CASCADE, null=True) phone = models.ForeignKey(PhoneModel, on_delete=models.CASCADE, null=True) email = models.EmailField(blank=True) def __str__(self): return '%s %s - %s - %s, %s' % (self.firstName, self.lastName, self.company, self.phone, self.email ) class Meta: ordering = ['firstName'] verbose_name = "Customer Contact Information" #verbose_name_plural = "Contacts" @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: PersonModel.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() -
From JWT - ImportError: cannot import name 'InvalidTokenError'
I am trying to run an application that uses the JSON Web Token python package, JWT. Whenever I try to run the app, it gives me an error of cannot import name 'InvalidTokenError' Which is imported from JWT. I am in a virtual environment, that has JWT==0.5.2 . The last time I was running this application I was in another environment that used python 3.5, and now I'm using python 3.6. I'm not sure if I'm using the wrong version of JWT, or if its the minor version of Python that I'm working on. Here is my pip freeze asn1crypto==0.23.0 certifi==2017.11.5 cffi==1.11.2 chardet==3.0.4 cryptography==2.1.3 Django==1.9.9 httplib2==0.10.3 idna==2.6 jwt==0.5.2 oauth2client==1.5.2 olefile==0.44 Pillow==4.3.0 pyasn1==0.3.7 pyasn1-modules==0.1.5 pycparser==2.18 pyOpenSSL==17.3.0 requests==2.18.4 rsa==3.4.2 six==1.11.0 urllib3==1.22 Traceback: Traceback (most recent call last): File "/Users/tim/Timothy/virt_envs/social_auto/lib/python3.6/site-packages/django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "/Users/tim/Timothy/virt_envs/social_auto/lib/python3.6/site-packages/django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/tim/Timothy/virt_envs/social_auto/lib/python3.6/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/tim/Timothy/virt_envs/social_auto/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 398, in login context = dict(self.each_context(request), File "/Users/tim/Timothy/virt_envs/social_auto/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 315, in each_context 'available_apps': self.get_app_list(request), File "/Users/tim/Timothy/virt_envs/social_auto/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 488, in get_app_list app_dict = self._build_app_dict(request) File "/Users/tim/Timothy/virt_envs/social_auto/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 434, in _build_app_dict has_module_perms = model_admin.has_module_permission(request) File "/Users/tim/Timothy/virt_envs/social_auto/lib/python3.6/site-packages/django/contrib/admin/options.py", line 474, in has_module_permission return request.user.has_module_perms(self.opts.app_label) … -
How to serve static img in separate js module in django project
There is a notifications module in JS+JQuery which is duplicated on every page. I want to bring all duplicated to one single js source file. The only problem is that there are using some static files like that, using append function: {% static "img/man.svg" %} And while JS code is in the file with html, it's rendered by django, but if we bring the logic to separate js file, it won't render. How to solve this problem? -
Django template IF condition with logical breckets and precedence order
In my django template I have {% if object_not_readonly and user_is_worker or user_is_admin %} Django doc tell me Use of both and and or clauses within the same tag is allowed, with and having higher precedence than or I think this is not obvious way to declare logical precedence in IF clause. Question is: Is it something like {% if object_not_readonly and ( user_is_worker or user_is_admin ) %} condition in django template language? -
Is there a way to upload a file to the database after changing it to a suitable model in django?
I want to make admin page if admin user upload file (like csv file format and so on), it save in database after changing suitable model. For example, suppose a user uploads the following file. year month survived ticket 2002 08 1 cn-101 2001 09 0 cn-102 2002 11 1 cn-103 What I want to make is when user upload this file in admin page, it change file to model like below and save in database. class SampleModel(models.Model): year = models.IntegerField() month = models.IntegerField() survived = models.booleanField() ticket = models.CharField() It there any way to do this in Django??? -
How can we deploy a django app onn google cloud?
I am having trouble deploying a developed django app on google console. Firstly it renames all the files of the app to some random name. Also when I try to hit the website .appspot.com I get an internal error. Have created app.yaml file: # [START runtime] runtime: python27 entrypoint: gunicorn -b :$PORT mysite.wsgi threadsafe: true # [END runtime] handlers: - url: /static static_dir: website/static - url: /.* script: main.application libraries: - name: django version: 1.11 Also have created appengine_cofig.py file: # Copyright 2015 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # [START vendor] from google.appengine.ext import vendor vendor.add('lib') # [END vendor] Thanks for the help in advance.... -
Django admin CSRF 403 error
I have multiple django servers (API backend for mobile clients) running behind a load balancer. But when accessing django admin some times I'm getting 403 forbidden error. Is it related to csrf cookie ? My load balancer setting is, Session Stickiness - None Algorithm - Roundrobin -
Whitenoise giving errors on jquery-ui.css when doing collectstatic
I'm trying to install the jquery-ui-dist package, and when I run collectstatic, whitenoise seems to have trouble when a url is inside quotations in a stylesheet. The error I get is: MissingFileError: The file 'jquery-ui-dist/"images/ui-icons_555555_256x240.png"' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x7fb16b7000b8>. The CSS file 'jquery-ui-dist/jquery-ui.css' references a file which could not be found: jquery-ui-dist/"images/ui-icons_555555_256x240.png" Please check the URL references in this CSS file, particularly any relative paths which might be pointing to the wrong location. I see that it seems to think it's looking for a bad filename, as it keeps the quotations around it, and I assumed that the reason was because the source file has url("images/ui-icons_555555_256x240.png") when the quotations are unnecessary, so I ran sed -i 's/\"images\/ui-icons_555555_256x240.png\"/images\/ui-icons_555555_256x240.png/g' jquery-ui.css on the source file, which removed the quotation marks, but I still get the error. I'm assuming there is a problem with either whitenoise or the jquery-ui-dist package, but until the problem is fixed on their end, I at least need a temporary solution, and I'm not even sure where the actual problem lies. -
django model relation does not exist
I am trying to add an Image to a Product model but I am getting this error DoesNotExist at /admin/startupconfort/startupproductimage/add/ StartupProductImage matching query does not exist. error models from stdimage.models import StdImageField class StartupProductImage(TimeStampedModel): product = models.OneToOneField(StartupProduct, related_name='image', on_delete=models.CASCADE, primary_key=True, ) picture = StdImageField(upload_to='startup-product/%Y/%m/%d', verbose_name="pics", blank=True, variations={ 'large': (600, 400), 'thumbnail': (250, 250, True), 'medium': (300, 200), }) product class StartupProduct(TimeStampedModel, VoteModel): startup = models.ForeignKey( Startup, null=False, blank=False , related_name='brand_product') category = models.ForeignKey( Category, null=False, blank=False , related_name='product_category') title = models.CharField(verbose_name=_(u"Title"), max_length=32) shortdesc = models.CharField(max_length=80, null=False, blank=False, verbose_name='shortdesc') slug = AutoSlugField( unique_with=('created', 'startup'), ) price = models.IntegerField(default=28) quantity = models.PositiveIntegerField(verbose_name=_(u"Qty"), default=1, validators=[MaxValueValidator(10),MinValueValidator(1),] ) -
Django datetime/timedelta incompatible type
I'm trying to subtract 2 datetimes from my csv file. Purchase Is a column in csv file. orders["Closed"] = pd.to_datetime(orders["Purchase"]).dt.minute.apply(lambda x: x + 15) first = orders.loc[x]["Check Closed"] second = pd.to_timedelta(orders[(orders["ID"] == x)]["Purchase"]) duration_time = (first - second).time() return duration_time x - is client's ID from another csv file. When I'm trying to run this code, I have: incompatible type for a datetime/timedelta operation [__rsub__]. Is it problem, that "Closed" is a timedelta, so I couldn't subtract datetime and timedelta, and how can I solve this. Thanks. -
How can I use the values_list in Wagtail (django)?
hi sorry for my poor English Why wagtail search return PostgresSearchResult after search ? i want PageQuerySet like Django postgres search backend because I can not use values_list after search i want to get list of page path ( because i want to find pages parents(Category Page) by path ) and i can't use values_list before search because it does not work i know, i can use Forloop but this takes about 5 seconds for each run My code is very simple : Django Way : #Work ProductPage.objects.filter(title__search="phone").values_list('path') Wagtail Way : #NotWork :( ProductPage.objects.search(query).values_list('path') -
django: RelatedManager for chained relations objects
So I've got models: class Parent(models.Model): name = models.CharField(max_length=100) class Child(models.Model): parent = models.ForeignKey('Parent', on_delete=models.CASCADE) name = models.CharField(max_length=100) class Grandchild(models.Model): parent = models.ForeignKey('Child', on_delete=models.CASCADE) name = models.CharField(max_length=100) class ParentPhoto(models.Model): person = models.ForeignKey('Parent', on_delete=models.CASCADE) image = models.ImageField() class ChildPhoto(models.Model): person = models.ForeignKey('Child', on_delete=models.CASCADE) image = models.ImageField() class GrandchildPhoto(models.Model): person = models.ForeignKey('Grandchild', on_delete=models.CASCADE) image = models.ImageField() Please ignore the bad database/models design (it's just an analogy to my complex real-life application). I want to add a RelatedManager for Parent named maybe family_photo_set that would return a Queryset containing all Photos for himself, his Children and all Children' Grandchildren. How do I achieve that? A simple RelatedManager allows me to only filter somehow a Parents' parentphoto_set, not really adding the rest of family members. -
Account Kit web login error
I set up AccountKit login page according to the Facebook documentation here. The problem is when I try to login using an email, on the last step after clicking 'Log in' it gives me an error which isn't very descriptive: signin.html: {% extends 'web/landing_base.html' %} {% load staticfiles %} {% block main_content %} <p>Sign in</p> <button onclick="emailLogin()">Email</button> <script src="https://sdk.accountkit.com/en_US/sdk.js"></script> <script> // initialize Account Kit with CSRF protection AccountKit_OnInteractive = function () { AccountKit.init( { appId: "{{ facebook_app_id }}", state: "{{ csrf_token }}", version: "{{ account_kit_api_version }}", redirect: "{{ redirect_url }}", debug: true } ); }; // login callback function loginCallback(response) { if (response.status === "PARTIALLY_AUTHENTICATED") { var code = response.code; var csrf = response.state; // Send code to server to exchange for access token } else if (response.status === "NOT_AUTHENTICATED") { // handle authentication failure } else if (response.status === "BAD_PARAMS") { // handle bad parameters } } // email form submission handler function emailLogin() { AccountKit.login('EMAIL', {}, loginCallback); } </script> {% endblock %} views.py: def signin(request): template = loader.get_template('web/signin.html') context = { 'facebook_app_id': <facebook_app_id>, 'account_kit_api_version': 'v1.1', 'redirect_url': 'http://127.0.0.1:8000/web/products/', } return HttpResponse(template.render(context, request)) AccountKit app configuration: Any advice what could cause the issue? -
python how to create errors manually and handle network errors
I'm using the requests library (within a django app) to consume an api. (eg to validate some data, payment details, address details etc....) However I'm working with an api that doesn't use http status codes (eg if it is a failed response I don't get a http 500 but a 200 instead and the details that it failed are in the response. It also uses custom internal status codes.). I've created a handler to handle the exceptions for the various endpoints I need to interact in this api. However I'm not clear on a couple of things: 1) how to manually create an error and log it (with traceback etc..) and raise it when the api (eg below when status returns false), how can I include the full traceback and the status, status_code, message, and data? Is it best to pass these into the custom error and raise this. (not sure how to get traceback too)? 2) What's the best way to test the below code, (ie that I get the right error raised, when api is down, returns 500, or doesn't return a json response, or if a json response but returns status as false etc...? (In a manual … -
Show more function when display object in django template
I want to display multiple images (from a table in my database) in my django template via model object. However, the number of images could be thousands. I wonder if there exists a way to add "show more" function that allows my template to display images batch by batch without having reload the entire page? (like when you use google image search) -
form is failing to submit the data in django
I created one form to sign up the patient. All the data are correct but it fails to submit the data It works successfully without any error. When submit button is clicked, page is redirected to "Invalid data" which is else statement in views.py file. I checked all of the data of models.py and forms.py,but could not able to find what is going wrong. I tried the solution by adding {{ psform.errors }} in template file. But it didn't work. models.py class PatientSignup(models.Model): GENDER = [ ('Male', 'male'), ('Female', 'female'), ] STATE = [ ('Gujrat', 'Gujrat'), ('Maharastra', 'Maharastra'), ] CITY = [ ('Valsad', 'Valsad'), ('Surat', 'Surat'), ('Rajkot', 'Rajkot'), ] pid = models.AutoField(verbose_name='Patient Id', primary_key=True, auto_created=True) pname = models.CharField(verbose_name='Enter Name', max_length=50, default=NameError) email = models.CharField(verbose_name='Enter Email', max_length=100,unique=True) gender = models.CharField(verbose_name='Select gender',max_length=6, choices=GENDER) age = models.PositiveIntegerField(verbose_name='Enter age',default=5, null=True) state = models.CharField(verbose_name='Select State',max_length=20, choices=STATE) city = models.CharField(verbose_name='Select City',max_length=30, choices=CITY) password = models.CharField(verbose_name='Enter Password',max_length=12) confirmPassword = models.CharField(verbose_name='Confirm Password',max_length=12) date = models.DateTimeField(auto_now_add=True) view.py class signup(TemplateView): template_name = 'personal/signup.html' temp = 'personal/log.html' def get(self, request): #this works successfully def post(self, request): psform = PatientSignupForm(request.POST) if psform.is_valid() and psform.cleaned_data['password'] == psform.cleaned_data['confirmPassword']: psform.save() args = {'psform': psform} return render(request, self.temp, args) elif psform.cleaned_data['password'] != psform.cleaned_data['confirmPassword']: return HttpResponse("Password and …