Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
see the view part i can get it to save the form it always seems to go to the else part ot is_valid()
view def createitem(request): if request.method == "POST": form= itemform(request.POST, request.FILES); if form.is_valid(): form.save(); return Redirect('/items') ; else: return render(request, 'app/create.html', {'form':form}); else: form = itemform(); return render(request, 'app/create.html', {'form':form}); here's the models if you see something wrong with it class items(models.Model): name = models.CharField(max_length = 30); description = models.TextField(); image = models.FileField(upload_to='documents/'); class itemform(ModelForm): class Meta: model = items; fields = ['name','description','image']; I have already added this to settings MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' and these lines to urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to add an ArrayField to a SearchVector in Django?
I'm trying to use an ArrayField in a SearchVector but it is returning django.db.utils.DataError: malformed array literal: "" LINE 1: ... = to_tsvector(COALESCE("example_model"."example_arrayfield", '')) ^ DETAIL: Array value must start with "{" or dimension information. When I query for the ArrayField it returns a list e.g. ["a","b","c"] whereas in the database it is shown in curley brackets instead e.g.{a,b,c} Does anyone know how to get the SearchVector to accept an ArrayField as just a plain list? OR somehow convert the normal list to curley brackets? -
How to configure Apache/mod_wsgi for Django
OS: Ubuntu 16.04 Apache version 2.4.18 I've created my first Django app, 'stats', and I can successfully access it whilst I'm on my Ubuntu machine by visiting http://127.0.0.1:8000/stats/ I've installed Apache and mod_wsgi and I can successfully access the Default Apache Page, hosted on my Ubuntu machine, from anywhere on the web. My problem is:- I don't know what/how to configure Apache and/or mod_wsgi so that I can access my Django app from anywhere on the web. I've run through about six or seven online guides, all of them advise different things, none of them work. Thanks in advance for any help! -
Django Channels Temporary Data
I'm currently making an simple multiplayer PONG game, that runs on browser. There is no problem in javascript part, but I think, I don't understand the concept of Django Channels. I want to store some temporary data, but I can't figure how can I do it. For example, if every user (I planned that the game can be played up to 4 people) click the 'Start' button, the game should start. So, I think that I can store this temporary data (Which users clicked the 'Start' button) in Redis(I'm use Redis for message delivery, too). Is this the right solution or is there any better solution? Thanks in advance. -
Django CircularDependencyError on migrations
I cloned a git repository with a Django app and opened it on Pycharm and made some changes to it. Among these changes I did add_to_class on the Group class from django, to add a field named modulo. I closed this project and cloned the repository again, and made all the initial migrations and all. The problem is, when I try to migrate I get this error django.db.migrations.exceptions.CircularDependencyError: BOXCFG.0001_initial, auth.0010_remove_group_modulo, auth.0009_group_modulo Seems like the changes I did on the Django native model are still somehow getting in the way of my migrations. I tried deleting everything, migratin history, the table migration field, the folders the database... And I still get this error when trying to make my migrations. How do I solve this? Where can I clear the Django migrations so that I start all over again without the changes I did in another project? -
how to save image to a folder using forms in django
model is like this class items(models.Model): name = models.CharField(max_length = 30); description = models.TextField(); image = models.ImageField(); class itemform(ModelForm): class Meta: model = items; fields = ['name','description','image']; view is like this def createitem(request): if request.method == "GET": form = itemform(); return render(request, 'app/create.html', {'form':form}); elif request.method == "POST": form= itemform(request.POST, request.FILES); if form.is_valid(): form.save(); result = {'success': True} return HttpResponse(simplejson.dumps(result), mimetype='application/json') else: return HttpResponseBadRequest() it cannot save the image to directory what am I doing wrong the form is showing up but cannot save the image return HttpResponseRedirect('/items') -
How to make a Django server portable?
My web server depends on nginx, django, and a lot of python dependencies. I'm wondering if there is a way to create a portable image/script that I can run in a new server and quickly get it up and running. Is Docker relevant to this? -
Sending JSON data from view in Django
I have to store some data in the window object to use it un the frontend rendering. I have a model: from django.db import models from tools.various.db import Base from tools.files.fields import CustomImgField, IMAGES_DIRECTORY_ORIGINAL from django.conf import settings class myModel(Base): myName = models.CharField(max_length=100, verbose_name='myName') mySurname = models.CharField(max_length=100, verbose_name='mySurname') I have a view: from django.http import Http404 from django.views.generic import TemplateView from django.http import JsonResponse from json import dumps from front.models import Language from front.models import myModel class BaseView(TemplateView): def get_context_data(self, **kwargs): context = super(BaseView, self).get_context_data(**kwargs) context['myData'] = myModel.objects.value() return context And I want to retrieve myData as a JSON object and store it in window object: window.app = { data: {}, settings: { staticUrl: '{{ STATIC_URL }}', urls: {}, storedData: {{ myData|jsonify|safe }} } }; But I get this response: [{'myName': u'foo', 'mySurname': u'bar', u'id': 1L, 'order': 0L}] is not JSON serializable Does anyone knows what I'm doing wrong? Thanks! -
How can I use jQuery Mobile with Django?
I've been working on a Django site for a while now and I have finished all of the backend and main frontend styling. Now I would like to make my site suitable for mobile devices. I was planning on using jQuery Mobile for this purpose but I can't seem to find anything online about how to make it work with Django. Is it possible to use jQuery Mobile with Django? If so, how can I accomplish this? -
Unable to display photo in django
I am trying to create the web app in django in which the photo list will be displayed with the help of AJAX but I am not getting an image instead getting image url. I am unable to solve this problem. I will really appreciate your help. enter image description here -
Django Admin :: set multiselect filter to autocomplete=Off
I tried to set attribute autocomplete = Off on the textBox Filter (see screenshot below), I found no solution. But in admin.py, I'am able to set autocomplete=Off on CharField, DateTimeField, etc. with "models.CharField: { 'widget': TextInput(attrs={'autocomplete': 'off'})}," Details : in my model, this field is a type ManyToManyField it is in the add view page in django admin site Someone is better than me to find a solution for this? Thanks -
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???