Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Simple guide or documentation to deploy a simple local web page using Python to be acessed by other devices on the network
I've searched through similar questions but couldn't find an answer to this particular problem. Here's my goal: Make a web page that's available through the network e.g. http://192.168.1.20:8080 I'll use a Raspberry Pi as server, and it will refresh the page at each 60 seconds My goal is to refresh 4 variables using some input(don't worry about how) and display their values I have some experience with tkinter if it's of any use in this application.I want to do this in Python because it's a language I already use for various uses. Hope you can help me. Thanks in advance. -
Django CSRF token is missing from signup form
I have another problem caused by the major upgrades I've done to a Django app (from 1.7 to 1.10 and Django Rest Framework to 3.5.4). I managed to fix some other errors that were causing a 500 error on the signup page, but still I have a problem with the CSRF token. This functionality was working before the upgrades. I have checked all the things mentioned in the error paged (I have DEBUG=True), but all of them seem ok, as to follow: In the class "CompanyAdmin" I have the signup method: def signup(self, request): if request.method == "GET": form = SignupForm() else: form = SignupForm(request.POST) if form.is_valid(): company = form.save() user = company.managers.all()[0] user = authenticate( email=user.email, password=request.POST["password1"]) if user is not None: login(request, user) return HttpResponseRedirect(reverse("bagdisken:index")) return shortcuts.render_to_response("bagdisken/signup.html", context=RequestContext(request, { 'form': form, })) I had problems with the context, causgin a 500 error, which I fixed by adding the request in the context. Previous it was like this: return shortcuts.render_to_response("bagdisken/signup.html", {'form': form}) The CSRF token is present in the view: {% extends "admin/base_site.html"%} {% load form_utils %} {% block content_title%}{% endblock %} {% block breadcrumbs %}{% endblock %} {% block nav-global %}{% endblock %} {% block coltype %}twelve columns … -
Sort and mix with different attributes
I have a list of products, each have a price, a discount and categories. I need to sort this list starting with the first product with a price less than a certain target and descending in price. The complication is that I also need to mix categories and discounts. That is, consecutive products must have different categories. Also there should be two products with discount, then two without discount and so on. Something like: product_a, 9000, 10%, category_x product_b, 8000, 10%, category_z product_c, 7000, 0%, category_y product_d, 6000, 0%, category_w product_d, 5000, 10%, category_x Any ideas how to do this without having to do many queries. This is for a site made with Django and using Postgresql -
Cannot convert dictionary update sequence element #0 to a sequence
I'm trying to store form field variable with Django cache and I add Django form in my view. I'm getting this error and I don't see what will be wrong in my script : Cannot convert dictionary update sequence element #0 to a sequence Do you have any idea ? All seems right from my point of view. The error comes from this line : return render(request, 'form.html', {'form' : form}) This is my script function : def Function_Form(request) : query_lastname = request.GET.get('lastname') cache.set('query_lastname', query_lastname, 300) print cache.get('query_lastname') if request.method == 'POST': form = Formulary(request.POST or None) if form.is_valid() : if '_save' in request.POST : post = form.save() return HttpResponseRedirect(reverse('treated', kwargs={'id': post.id})) else: form = Formulary() return render(request, 'form.html', {'form' : form}) -
Update two elements with two jquery .post responses
There are two lists on the page: 'To buy' and 'Recently bought'. Each list can contain items. After clicking on an item the item is supposed to be removed from the original list and inserted into the other list. It works for some items but sometimes I have to click twice to move the item. I assume there is something wrong with my makeactive and makeinactive functions but what and how would you recommend fixing it? home.html <h3>To buy:</h3> {% csrf_token %} <ul id="only_active"> {% for item in active %} <li id='{{ item.id }}' class="active">{{ item.name }}, id: {{ item.id }}</li> {% endfor %} </ul> <h3>Recently bought:</h3> <ul id='recently_bought'> {% for item in inactive %} <li id='{{ item.id }}' class="inactive">{{ item.name }}, id: {{ item.id }}</li> {% endfor %} </ul> js function makeinactive(){ // changes item from active to inactive (item.active=True into False) id = this.id; console.log(id); var data = {'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()}; URL = id + '/switch/' $.post(URL, data, function(response){ $('#recently_bought').html(response); }); // updates the list of active items URL = '/only_active/' $.post(URL, data, function(response){ $('#only_active').html(response); }); } function makeactive(){ // changes item from inactive to active (item.active=False into True) id = this.id; console.log(id); var data = {'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()}; URL … -
Where does Django logout user on expired/invalid session
I do some stuff on user logout, so I want to extend the method where Django does the logout on expired/invalid session but I don't find where it does it. Can you help me to point where the logout happens? -
Adding automatically the current user to saved objects on Wagtail ModelAdmin inline
This is something I'd accomplish by modifying the save_related on a standard Django ModelAdmin, and adding the user from the request to each saved form in the inline formset. I've been looking at the edit_handlers and ModelAdmin code but couldn't figure out how to do it on Wagtail's ModelAdmin. Any clues?? Thanks a lot!! -
Model Mixin for object history
I am trying to create a Mixin that will keep track of the history of an object/instance. The idea seems simple enough: override the models.Model's save method to grab the object before the change, save the change, and then compare to see which fields have changed and save the changes to another table: class ObjectHistoryMixin(object): def save(self, *args, **kwargs): previous_state = self.__class__.objects.get(pk=self.pk) super(ObjectHistoryMixin, self).save(*args, **kwargs) new_state = self fields = self.__class__._meta.get_fields(include_parents=False) for field in fields: if getattr(previous_state, field.name) != getattr(new_state, field.name): print('field {} changed'.format(field)) I tried it on this model: class Insurer(ObjectHistoryMixin, models.Model): created_date = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey('users.User', on_delete=models.PROTECT) name = models.CharField('naam', max_length=100) But this doesn't work: AttributeError at /portal/beheer/verzekeraars/9/bewerken/ 'Insurer' object has no attribute 'submittedprescription' Request Method: POST Request URL: http://127.0.0.1:8000/portal/beheer/verzekeraars/9/bewerken/ Django Version: 1.11b1 Exception Type: AttributeError Exception Value: 'Insurer' object has no attribute 'submittedprescription' Exception Location: C:/Users/Administrator/SVN/doras_val\portal\models.py in save, line 20 Python Executable: C:\Users\Administrator\SVN\venvs\venv_doras_val\Scripts\python.exe Python Version: 3.6.0 Python Path: ['C:/Users/Administrator/SVN/doras_val', 'C:\\Program Files (x86)\\JetBrains\\PyCharm 2016.3.2\\helpers\\pydev', 'C:\\Users\\Administrator\\SVN\\doras_val', 'C:\\Program Files (x86)\\JetBrains\\PyCharm 2016.3.2\\helpers\\pydev', 'C:\\Users\\Administrator\\SVN\\venvs\\venv_doras_val\\Scripts\\python36.zip', 'C:\\Users\\Administrator\\SVN\\venvs\\venv_doras_val\\DLLs', 'C:\\Users\\Administrator\\SVN\\venvs\\venv_doras_val\\lib', 'C:\\Users\\Administrator\\SVN\\venvs\\venv_doras_val\\Scripts', 'c:\\python36-32\\Lib', 'c:\\python36-32\\DLLs', 'C:\\Users\\Administrator\\SVN\\venvs\\venv_doras_val', 'C:\\Users\\Administrator\\SVN\\venvs\\venv_doras_val\\lib\\site-packages'] Server time: di, 7 Mrt 2017 13:15:38 +0100 Environment: Request Method: POST Request URL: http://127.0.0.1:8000/portal/beheer/verzekeraars/9/bewerken/ Django Version: 1.11b1 Python Version: 3.6.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', … -
enum value fetch by key in django
I have implemented the choices in Subcategory Size filed, SIZE = [['EXSMALL','Extra Small'],['SMALL','Small'],['MEDIUM','Medium'],['LARGE','Large'],['XTRALARGE','Extra Large']] class Sub_Category(models.Model): subcategory_size = MultiSelectField(choices=SIZE, max_length=50, default="", null=True, blank=True) I have size value 2, and i want to fetch the 'Medium'. I want to know how to fetch value by index value of enum ? -
Can't update data using class based view and django form
I can't update userprofile instance using django form and a class based view. POST request is send with proper parameters, template is redirecting properly, but unfortunately userprofile is not updating. Please notice that I'm new to Django, so every tips are welcome. models.py: class UserProfile(models.Model): objects = models.Manager() user = models.OneToOneField(User) search_range = models.IntegerField(default=150) def __str__(self): return self.user.username forms.py: class HomeForm(forms.ModelForm): class Meta: model = UserProfile fields = ('search_range',) views.py: class HomeView(TemplateView): template_name = 'home/home.html' def get(self, request): form = HomeForm() args = {'form': form} return render(request, self.template_name, args) def post(self, request): form = HomeForm(request.POST, instance=request.user.userprofile) if form.is_valid(): form.save() return redirect('home:home') args = {'form': form} return render(request, self.template_name, args) urls.py: urlpatterns = [ url(r'^$', HomeView.as_view(), name='home') ] home.html: <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> -
Django cms show next slider as thumbnail
I have build a plugin which results all my slider, that i put in my admin. The Result is simple a slider with plain text. Now i show my sliders with an if so {% if sliders %} {% for slider in sliders %} <li data-thumb="{% static 'img/slider/rev/main/s1-thumb.jpg' %}" > <img src="{{ slider.image.url }}"> {% endfor %} {% else %} in the li, with the "data-thumb" where i have my thumb chosen, i need to show the NEXT slider. is there any function in Django cms do get the next ? -
The image in django doesn't work
I want to show an image in my template how can give to my page address of image ? can i say to my image src like this : <img src="example.jpg" /> and i put my image in my page folder? -
Django form with Custom ForeignKey Field
I'm trying to improve some elements from Django forms in my website and I need your help in order to handle 2 fields : fk_parent1 and fk_parent2 from BirthCertificate form. Both fields corresponds to a ForeignKey from Identity Form. Let me explain : Step 1 : Users create some Identity acts about town population Step 2 : When users have to create BirthCertificate act, they fill a Django form with some informations (lastname, firstname, ...) and select parents from a people list. For me, this list is not a good idea because I could have 100.000 entries at the end. So I would like to replace this list by (several ideas) : A list which only displays people with the same lastname than child Birthcertificate act (I prefer this option - it's fluider). Search fields according to parents with 3 entries : lastname, firstname, birthday I don't know which option will be better ? My Birthcertificate models.py file looks like : #-*- coding: utf-8 -*- from django.db import models from Identity.models import Identity from django.utils.encoding import force_text from django_countries.fields import CountryField SEX_CHOICES = ( ('Masculin', 'Masculin'), ('Feminin', 'Feminin') ) class BirthCertificate(models.Model): lastname = models.CharField(max_length=30, null=False, verbose_name='Nom de famille') firstname = … -
Value error invalid literal for int() with base 10: when trying to use generic relations on DRF
I am trying to create a news feed and I am using django activity stream and django rest framework. I keep getting this error: ValueError at /api/activities/ invalid literal for int() with base 10: '' Here is the traceback Traceback: File "/home/zack/venv/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/home/zack/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/zack/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/zack/venv/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/home/zack/venv/local/lib/python2.7/site-packages/rest_framework/viewsets.py" in view 83. return self.dispatch(request, *args, **kwargs) File "/home/zack/venv/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 477. response = self.handle_exception(exc) File "/home/zack/venv/local/lib/python2.7/site-packages/rest_framework/views.py" in handle_exception 437. self.raise_uncaught_exception(exc) File "/home/zack/venv/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 474. response = handler(request, *args, **kwargs) File "/home/zack/venv/local/lib/python2.7/site-packages/rest_framework/mixins.py" in list 48. return Response(serializer.data) File "/home/zack/venv/local/lib/python2.7/site-packages/rest_framework/serializers.py" in data 725. ret = super(ListSerializer, self).data File "/home/zack/venv/local/lib/python2.7/site-packages/rest_framework/serializers.py" in data 262. self._data = self.to_representation(self.instance) File "/home/zack/venv/local/lib/python2.7/site-packages/rest_framework/serializers.py" in to_representation 643. self.child.to_representation(item) for item in iterable File "/home/zack/venv/local/lib/python2.7/site-packages/rest_framework/serializers.py" in to_representation 483. attribute = field.get_attribute(instance) File "/home/zack/venv/local/lib/python2.7/site-packages/rest_framework/relations.py" in get_attribute 174. return get_attribute(instance, self.source_attrs) File "/home/zack/venv/local/lib/python2.7/site-packages/rest_framework/fields.py" in get_attribute 102. instance = getattr(instance, attr) File "/home/zack/venv/local/lib/python2.7/site-packages/django/contrib/contenttypes/fields.py" in __get__ 243. rel_obj = ct.get_object_for_this_type(pk=pk_val) File "/home/zack/venv/local/lib/python2.7/site-packages/django/contrib/contenttypes/models.py" in get_object_for_this_type 173. return self.model_class()._base_manager.using(self._state.db).get(**kwargs) File "/home/zack/venv/local/lib/python2.7/site-packages/django/db/models/query.py" in get 376. clone = self.filter(*args, **kwargs) File "/home/zack/venv/local/lib/python2.7/site-packages/django/db/models/query.py" in filter 796. return self._filter_or_exclude(False, *args, **kwargs) … -
Djanto RemoteUser via basic file auth vs ldap (apache2)
i' ve a django application where i' d like to use remote user authentication with apache2. On Django side i' ve added these important lines to the settings.py: 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', #also tried with PersistentRemoteUserMiddleware AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.RemoteUserBackend'] . On apache2 side django is binded to the webserver via mod_wsgi, and in the configuration file i' ve these for authentication: #file1 - for basic file auth <Location /> AuthName "Add your login message here." AuthType "Basic" AuthBasicProvider file require user somebasicuser AuthUserFile /path/to/.htpasswd </Location> and #file2 - for ldap auth <Location /> AuthName "Add your login message here." AuthType Basic AuthBasicProvider ldap AuthLDAPURL ldap://localhost/dc=somesite,dc=hu?uid?sub AuthLDAPBindDN "cn=admin,dc=somesite,dc=hu" AuthLDAPBindPassword ldappassword require ldap-user someldapuser </Location> In the first case i can log in with somebasicuser, and in the second case i can log in with someldapuser . In both cases - after logging in - i can reach both the request.META['REMOTE_USER'] and the request.user variables. The only one difference comes (and this is my problem) when i' ve a view, which requires authentication (with @login_required decorator). In the basic file auth case, it works well, however in ldap case it redirects me to the default django login page (For instance: http://127.0.0.104/accounts/login/?next=/order/ ). Could anybody … -
Python __repr__ and __str__ [duplicate]
This question already has an answer here: Difference between __str__ and __repr__ in Python 14 answers i know the str__operator in python for make my data viewable, but now in django i view the use of __repr operator. What is the main difference about? Thanks in advance -
why is Django MultipleObjectsReturned Error hogging memory?
I am using Django 1.9.10: I have a model called Details has a unique_id column which is indexed: try: detail = Detail.objects.get(unique_id=UUID) except MultipleObjectsReturned as m: logger.error("uuid {} returned multiple objects - {}".format(UUID, str(m))) Due to some error in code UUID=None this resulted in MultipleObjectsReturned error getting raised. but we noticed that almost 2-GB of memory is getting used up and it is slowing the system down a lot. On printing str(m) in the error logs we found following error MultipleObjectsReturned: get() returned more than one Details -- it returned 451424! My Question is why is Django fetching so much data in memory just to raise an error? Django can just fetch the count? I know I can use filter() to over come this issue but I am just surprised by this and want to understand why django is doing this? -
Django is_valid() missing 1 required positional argument: 'self'
I'm trying to build a website using Django 1.10.5. At the moment I'm working on a way to edit the database objects in the frontend. My plan was to define a form 'EditForm', where the user enters the ID of the object he wants to edit. When I'm testing only that form on the real site to see if I can submit something, I'm getting the following error: 'is_valid() missing 1 required positional argument: 'self''. I can't find my error in the code so thanks in advance for any help or ideas. from my views.py: def mymodel_test(request,): form = EditForm if request.method == 'POST': if form.is_valid(): temp_id = form(request.POST) return render(request, 'mymodel_test.html', { "Title": "Test", "form": form }) EditForm in the forms.py: class EditForm(forms.Form): id = forms.IntegerField(label='Edit object with following ID') mymodel_test.html: {% extends "base.html" %} {% block content %} <form method="post" action=""> {% csrf_token %} <table> {{ form }} </table> <input type="submit" value="Edit"/> </form> {% endblock %} -
Querying related fields from Django Tables with One to Many Relationship
I am just exploring how to get around with Django, and i created two models in my Django app. from django.db import models #first model class Person(models.Model): name = models.CharField(max_length=40) email = models.CharField(max_length=100) title = models.CharField(max_length=100) image = models.CharField(max_length=200) def __str__(self): return self.name #second model class Skill(models.Model): person = models.ForeignKey(Person) skill = models.CharField(max_length=60) years = models.CharField(max_length=40) def __str__(self): return self.skill The first model is Person and the second model is Skill. Now how the relation goes is that each Person will have many skills. Now I can update the database with the data, the admin section of the site also works fine. On the Django Shell, I try to run the command: Skill.object.all() and what i get is the following error: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\models\query.py", line 235, in __repr__ return '<QuerySet %r>' % data File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\models\base.py", line 572, in __repr__ u = six.text_type(self) TypeError: __str__ returned non-string (type tuple) or if i try the command: Skill.objects.get(pk=1) i get: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\models\base.py", line 572, in __repr__ u = six.text_type(self) TypeError: __str__ returned non-string (type tuple) However … -
How to raise an exception in pytest?
I have written a code in views.py def fun(): try: --Do some operation-- except OSError: --Do something else-- And I have written a test case to cover total functionality of the code. To test the "except" part I have written the following code where it will raise "OSError", with pytest.raises(OSError): response = client.post(reverse('my_views_funurl'), follow=True) But, I am getting this error response = client.post(reverse('my_views_funurl'), follow=True) E Failed: DID NOT RAISE How to raise "OSError" to cover the except part in test cases. By the way I am using django-framework -
Django call_command() parameter type issue
When I try to call my custom django command with a id as a string it works without a problem. call_command(COMMAND, '-i', '23') But when I try to cast the id of a object to a string, then it will not work. call_command(COMMAND, '-i', str(product.id)) It become this error: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/kombu/utils/__init__.py", line 423, in __call__ return self.__value__ AttributeError: 'ChannelPromise' object has no attribute '__value__' Any idea why this is happening? -
Like functionality in
I'm developing a social platform and currently coding the like functionality for user posts. However, I can't seem to make it work. These are my Models.py: class Post(models.Model): user = models.ForeignKey(User) posted = models.DateTimeField(auto_now_add=True) content = models.CharField(max_length=150) picturefile = models.ImageField(upload_to="post_content", blank=True) class Like(models.Model): user = models.ForeignKey(User, null=True) post = models.ForeignKey(Post, null=True) I pass the post ID through my url as 'post_id', and then in my views: def liking(request, post_id): newlike = Like.objects.create() newlike.post = post_id newlike.user = request.user newlike.save() return redirect(reverse('dashboard')) However, it returns the following error: Cannot assign "'47'": "Like.post" must be a "Post" instance. Does anyone knows what I'm missing or doing wrong? -
how to create popup window in Django?
I would like to know how to create a popup window in Django when user click on specific button and ask the user if he/she sure want to go for that please any help -
Cannot access to port 80 on Google Cloud VM instance
I have setup Django in Linux Ubunut on GCE and run using : sudo -E home/us1/python/bin/python /home/us1/project/manage.py runserver 0.0.0.0:80 Server is started but when using my browser on ip_adress:80, I got an error message that : This site can’t be reached, Too long to respond. 1) I checked the firewall set, open 80 is open... Am not sure how I can get access to this website ? -
UWSGI https configuration for ubuntu
I have django app that is running using the following uwsgi configuration in redhat 7.3: [uwsgi] project = helloworld base = %d chdir=%(base) module=helloworld.wsgi:application plugins = router_redirect route-if = equal:${HTTPS};on addheader:Strict-Transport-Security: max-age=31536000 master = true processes = 1 enable-threads = true threads = 1 max-requests = 2000 shared-socket = 0.0.0.0:443 https = =0,cert/hello.crt,cert/hello.key,HIGH pidfile = hello_uwsgi.pid vacuum = true die-on-term = true However, when I run it on Ubuntu 16.04.1 LTS, I got the following error: your processes number limit is 31283 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) Python version: 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] Python main interpreter initialized at 0x1dfabe0 python threads support enabled The -s/--socket option is missing and stdin is not a socket. VACUUM: pidfile removed. Does the error means that uwsgi fail to bind the port? Is there a special way of using "shared-socket" in ubuntu? I need to have this running on both port 443 and 8443. I have tried the above configuration for both port 443 and 8443 without success. Thanks in advance.