Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: set the `backend` attribute on the user
I have added python-social-auth in my project for social logins. I also have a signup form of my own for new users. For social logins, I added some authentication backends. Now, the social logins are working fine, but the signup form causes some problems. After I enter the details, and click signup, this error comes up. I see in the admin panel, the user was added even after this error. ValueError: You have multiple authentication backends configured and therefore must provide the `backend` argument or set the `backend` attribute on the user. Now, it is asking me to set the backend attribute of the user. How to set that ? Here is the view for signup, def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_pass = form.cleaned_data.get('password') user = authenticate(username=username,password=raw_pass) login(request,user) return redirect('location:get_location') else: form = SignupForm() return render(request, 'signup.html', {'form':form}) -
Issue with online logged users in my Django application
As always, I'm trying to improve my Django application and I would like to create a Django module which could display all logged users. This is my model class LoggedUser : class LoggedUser(models.Model): user = models.OneToOneField(User, primary_key=True) def __unicode__(self): return self.user.username def login_user(sender, request, user, **kwargs): LoggedUser(user=user).save() def logout_user(sender, request, user, **kwargs): try: u = LoggedUser.objects.get(user=user) u.delete() except LoggedUser.DoesNotExist: pass user_logged_in.connect(login_user) user_logged_out.connect(logout_user) Then, I have in my view : def ConnectedUsers(request) : logged_users=[user.user for user in LoggedUser.objects.all()] print logged_users context = { "logged_users":logged_users, } return render(request, "UtilisateursConnectes.html", context) The print query returns : [] And a very simple template just in order to display logged users : {% block content %} List of logged users : {% for users in logged_users %} <li>{{ users }}</li> {% endfor %} {% endblock %} The problem is : When I try to connect different account on my software, the table LoggedUser is still empty. Do I make a mistake in my script ? -
Best way to keep web application data sync with elasticsearh
I'm developing a web application in Python with Django for scheduling medical services. The database using is Mysql. The system has several complex searches. For good performance, I'm using elasticsearch. The idea is to index only searchable data. The document created in the ES is not exactly the same as modeling in the database, for example, the Patient entity has relationships in the DB that are mapped as attributes in the ES. I am in doubt at what time to update the record in the ES when some relationship is updated. I am currently updating the registry in ES whenever an object is created, changed or deleted in the DB. In the case of relationships, I need to fetch the parent entity to update the record. Another strategy would be to do the full index periodically. The problem with this strategy is the delay between a change and it's available for search. What would be the best strategy in this case? -
How to implement MQTT in Django.?
I already have a system where cc3200 IoT devices communicate to Django server via REST APIs. I am planning to change the communication protocol to MQTT as I've heard that it is the best-suited protocol for IoT devices.I have no idea how to implement MQTT in Django and how to replace all Django REST APIs that are currently used for data transfer. How can I receive messages from IoT devices and process it in Django and also how can I send data from Django to IoT devices using MQTT. -
Why can't I put value to db?
I made composite id of trunsaction_id&user_id.I wanted to assign trunsaction_id each user_id.Now User model is class User(models.Model): trunsaction_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) regist_date = models.DateTimeField(auto_now=True) user_id = models.CharField(max_length=200,null=True) name = models.CharField(max_length=200,null=True) age = models.CharField(max_length=200,null=True) user_trunsaction_id = ''.join([str(trunsaction_id), '_', str(user_id)] But when I run file of putting data to User model, all column excepting for user_trunsaction_id has its data, but no user_trunsaction_id's column is db.Of course I run makemigration&migration command,so I really cannot understand why this error happens.What is wrong?How can I fix this? -
Django - Extending Global Static HTML Template
Description How could I extend base.html in my apps using following folder structure Folder Structure └───project ├───plots # <-- app ├───project ├───projects # <-- app ├───static # <-- project static files │ ├───css │ ├───html │ └───img └───users # <-- app Settings File STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] and I do use static files via {% load static %} - {% static '/css/base.css' %} I also know how to use {% extends file %} - {% extends users/html/base.html %} I would like to extend from static folder like such {% extends 'html/base.html' %}, however I can't find a way how to achieve this relation. Alternative Solution I found an alternative way to get it to work modifying templates entry in projects settings file. It works but, if possible, I would like to keep all static files in one place. Folder Structure └───project ├───plots # <-- app ├───project ├───projects # <-- app ├───static # <-- project static files │ ├───css │ └───img ├───templates #<-- !now `base.html` is here! └───users # <-- app Settings TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, … -
Pull down menu with crispy-forms
I am a new programmer with Django/Python, and I need a bit of help with crispy-forms to create a pull down menu. Some people add formlayout.py and forms.py to their app, but I don't know if it is related? The following images represent what I want to do now, but with 'Type' instead of 'Gender' and How could create a pull down menu with crispy-forms? What files do I have to add to my Django app? What library do I have to use in python? I'd appreciate to have some guidelines. -
Django Rest Framework Serializers: exclude from validation related entity
I have m2m related entities: class Tag(models.Model): name = models.CharField( max_length=80, blank=False, unique=True ) class File(models.Model): tags = models.ManyToManyField(Tag) uploader = models.ForeignKey(User, on_delete=models.DO_NOTHING) name = models.CharField( max_length=255, blank=False, unique=True, ) and serializers for them: class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('id', 'name') extra_kwargs = { 'name': { 'validators': [], }, } class FileSerializer(serializers.ModelSerializer): tags = TagSerializer(many=True, read_only=False) class Meta: model = File fields = ('id', 'name', 'tags') def update(self, instance, validated_data): tags_data = validated_data.pop('tags') if 'name' in validated_data: instance.name = validated_data['name'] instance_tags = instance.tags.all() new_tag_list = [] # add new tags for tag in tags_data: tag, created = Tag.objects.get_or_create(name=tag['name']) new_tag_list.append(tag) if tag not in instance_tags: instance.tags.add(tag) # remove old tags for instance_tag in instance_tags: if instance_tag not in new_tag_list: instance.tags.remove(instance_tag) return instance as you can see I turned off all validation for Tag.name field in TagSerializer by this code setting: extra_kwargs = {'name': {'validators': []}} . This is because of validation errors during saving updated File: serializer = FileSerializer(file, data=request.data, partial=True) if serializer.is_valid(): ... If you have File with list of tags and just want to add or remove some tags, you'll have error 'tag with such name already exists'. So this spike is working, but for … -
Django taggable field displaying id of field values
I have one field that is custom tag When I get that particular field from model and try to print all stored values in that field, It will displays as Id's of each value How can I get that values which I had stored as string -
Cannot see the Edit Profile, Change Password, and Reset Password forms for my Django project.
I am learning how to use the Django framwork to allow the user to do the following : Create an account Edit the account information using custom forms. Change password when the current password is known Reset password when the current password is not known. The problem is that the forms are disfigured when shown. The input fields are squeezed to the point that I cannot enter anything. The forms are still functional it seems because when I click the buttons the field requirements prompt me with the field is required message. This is the Edit profile page : This is the code for the Edit profile Html : {% extends 'base.html' %} {% block head %} <title>Edit profile</title> {% endblock %} {% block body %} <form method="post"> {% csrf_token %} {{ form.as_p}} <button class="ui primary button"> Submit Change </button> </form> {% endblock %} This is the Change password page : This is the HTML code : {% extends 'base.html' %} {% block head %} <title>Edit profile</title> {% endblock %} {% block body %} <form method="post"> {% csrf_token %} {{ form.as_p}} <button class="ui primary button"> Submit Change </button> </form> {% endblock %} This is the Create New Password: This is … -
Django returns algorithm result different to python interpreter
I have some Algorithms Bubble, insertion, sort, merge etc. I have coded them into a Django website so you can input an array of numbers and it will sort them into order. To test i passed in this list of numbers: [3, 12, 5, 4, 8, 5, 1] When I run the function in a shell the algorithm returns what I want: [1, 3, 4, 5, 5, 8, 12] When I run it through Django the output is not what I want: [1, 12, 3, 4, 5, 5, 8] I have tried both POST and GET methods. I have tried with and without for loops. I have tried with and without CSRF_TOKENS. views.py from django.shortcuts import render from django.conf import settings from custom.bubble import maf_bubble def algo(request): if request.GET: nums_list = maf_bubble(list(request.GET['numbers'].split(','))) rtn_res = render(request, 'algorithms/sort.html', {'results' : nums_list}) return rtn_res else: return render(request, 'algorithms/sort.html', {}) sort.html <div class="wrapper"> <div class="search"> <form class="navbar-form navbar-left" method="GET" action=" " style="margin:2%" > <select name="algo_type" style="padding:5%; border-radius:5px; border: 2px solid #ccc;" placeholder="Type" > <option value="bubble">Bubble Sort</option> <option value="insertion"> Insertion Sort</option> <option value="merge" selected>Merge Sort</option> <option value="quick">Quick Sort</option> <option value="selection">Selection Sort</option> <option value="shell">Shell Sort</option> </select> <br><br> <form class="navbar-form navbar-left" method="GET">{% csrf_token %} <div> <input type="text" … -
@csrf_protect in django services
I'm trying to use @csrf_protect in my services by following Cross Site Request Forgery protection article but it is not working for me. This is my settings file MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'CB_Core_App.customMiddleWare.middleWare.IPValidationMiddleWare', ] and this is how I'm Acquiring the token var csrftoken = Cookies.get('csrftoken'); And this is how I'm configuring the $http provider with the cookie and header names: $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; But when I call any service, it returns 403 forbidden error. Any Idea what I'm missing or doing wrong? Any kind of help will be appreciated. -
How to add description to Django command?
In argparse, the description is passed into the ArgumentParser ctor like so: import argparse parser = argparse.ArgumentParser(description="Print a number") parser.add_argument('-n', dest='number', action='store', type=str, help="The number to be printed") args = parser.parse_args() When doing a similar thing using a Django command, how does one add the description="Print a number" given that the ArgumentParser has already been constructed? from django.core.management.base import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('-n', dest='number', action='store', type=str, help="The number to be printed") -
Django reserve foreign key in views
I have a reverse query in a template that working on two tables connected together with Foreign Key. That query is giving result what I want for now but in the future, it is clear will cause me serious problems about query optimization. I am sending the query to the database for all pictures related with the table that I am working with than I am showing only one of them. I cannot adapt to the view function the reverse query that I wrote in HTML template. Here are my working codes: in models.py class EtkinlikModel(models.Model): ... class FotografModel(models.Model): etkinlik = models.ForeignKey(EtkinlikModel, on_delete=models.CASCADE) in views.py def EtkinlikView(request): etkinlikler = EtkinlikModel.objects.all().order_by("-olusturulma_tarihi")[:4] template = “…” context = { "pageName": title, "etkinlikler" : etkinlikler } return render(request,template,context) in template.html {% for etkinlik in etkinlikler %} {{ etkinlik.etkinlik_adi }} {% for foto in etkinlik.fotografmodel_set.all|slice:":1" %} {{ foto.foto }} {% endfor %} {% endfor %} codes for decreasing query loads views.py def EtkinlikView(request): etkinlikler = EtkinlikModel.objects.all().order_by("-olusturulma_tarihi")[:4] for etkinlik in etkinlikler: foto = etkinlik.fotografmodel_set.all() template = “…” context = { "pageName": title, "etkinlikler" : etkinlikler, "foto":foto } return render(request,template,context) in template.html {% for etkinlik in etkinlikler %} {{ etkinlik.etkinlik_adi }} {{ etkinlik.id }} {% for f … -
How to hide admin users from django admin site
By default django admin shows all users on the admin site. I am working on a app where client wants to show only that users which are registered from mobile or web, not admin users. How to apply query on django admin site for this? Please help. Thanks in advance. def queryset(self, request): if not request.user.is_superuser: return User.objects.all() return User.objects.filter(is_superuser=False) -
Check if an object is a QuerySet
I have an object variable obj. Is it possible to check whether its a Queryset or not? (Couldn't find any posts on this on searching) -
How can logger.removeHandler(logger.handlers[0]) throw ValueError: list.remove(x): x not in list?
I'm trying to debug an exception in someone else's Python code, and I am not an expert in Python. The code tries to flush and remove all handlers on a standard Python Logger: def restart_logging(logger_id): logger = logging.getLogger(logger_id) while logger.handlers: handler = logger.handlers[0] handler.flush() logger.removeHandler(handler) init_logging(logger_id) This raises an exception: File "/usr/lib64/python2.6/logging/__init__.py", line 1208, in removeHandler self.handlers.remove(hdlr) ValueError: list.remove(x): x not in list I've reviewed StackOverflow's other "x not in list" questions, and they all fit in these two categories: removing the same item more than once (usually because of doing for x in list: list.remove(x) rather than while list: list.remove(list[0])) remove an item that was never in the list I don't see how either applies here. Firstly, a while loop is used: while there are still handlers, take the first one (which succeeds or there'd be an IndexError), flush it, remove it. Even if that removed more than one entry in the list, it's a while loop testing if the list still has entries, not a for loop iterating over (potentially removed) objects. Looking at the logging module source, it only calls remove() once, and it even checks the handler is in the list immediately before calling remove(): def … -
Reorder Django QuerySet by dynamically added field
A have piece of code, which fetches some QuerySet from DB and then appends new calculated field to every object in the Query Set. It's not an option to add this field via annotation (because it's legacy and because this calculation based on another already pre-fetched data). Like this: from django.db import models class Human(models.Model): name = models.CharField() surname = models.CharField() def calculate_new_field(s): return len(s.name)*42 people = Human.objects.filter(id__in=[1,2,3,4,5]) for s in people: s.new_column = calculate_new_field(s) # people.somehow_reorder(new_order_by=new_column) So now all people in QuerySet have a new column. And I want order these objects by new_column field. order_by() will not work obviously, since it is a database option. I understand thatI can pass them as a sorted list, but there is a lot of templates and other logic, which expect from this object QuerySet-like inteface with it's methods and so on. So question is: is there some not very bad and dirty way to reorder existing QuerySet by dinamically added field or create new QuerySet-like object with this data? I believe I'm not the only one who faced this problem and it's already solved with django. But I can't find anything (except for adding third-party libs, and this is not an … -
msi creation needs using cx_freeze in python
Suppose, I have written a code in python 2.7 . let's say i am using vlc player in my script and now i have created a msi file for my code so how to install "vlc player" in user's system during installation of msi file of my python code. Please give the example of setup file of cx_freeze package which installs all the dependent softweare (like VLC) in the user's system during installation of msi of python code. I just want to know where to add these dependencies (for installation) in setup file of cx_freeze. -
How to remove an object from another object in django? - python
I have a queryset that created by Profile.objects.all(). I want to print it in template except just one of its rows. How can I do it in template? or if it's not possible in template, how can I do it in view? -
Django: How to show user owned data in Admin forms
Following are the models of my app: class Store(models.Model): store_owner = models.ForeignKey(User, null=False, verbose_name='User') store_name = models.CharField(max_length=200, null=False, verbose_name='Store name') store_address_line_1 = models.CharField(max_length=200, null=False, verbose_name='Address line 1') store_address_line_2 = models.CharField(max_length=200, null=False, verbose_name='Address line 2') store_city = models.CharField(max_length=200, null=False, verbose_name='City') store_state = models.CharField(max_length=200, null=False, verbose_name='State') store_zip_code = models.CharField(max_length=200, null=False, verbose_name='Zip/Pin Code') store_country = models.CharField(max_length=200, null=False, verbose_name='Country') store_phone = models.CharField(max_length=12, verbose_name='Phone') store_email = models.EmailField(verbose_name='Email') store_website = models.URLField(verbose_name='Website') class StoreDepartment(models.Model): store = models.ForeignKey(Store, verbose_name='Store') department_name = models.CharField(max_length=200, null=False, verbose_name='Department name') department_description = models.TextField(max_length=250, null=False, verbose_name='Description') +++++++++ I am using only the dfault Admin provided by django framwork. I have 2 users, For both users I have created Stores. But when I try to create StoreDepartment, I see the list of all the stores in the Select box created for "Store" foreign-key field in StoreDepartment model. How to customize the default form so that user can see only the Stores created by them in the selectbox. -
Why I can't get the custom header from Django request.META
When use .\curl.exe -v -H 'HTTP_TEST:A17041708' http://127.0.0.1:8000/api/test open the url. I print the request.META,but i can't find my custom header in it -
Can we use Django signals on cassandra models
Please someone help me on how to use Django-signals on Cassandra models? I want to migrate my table(A) to table(B),so best solution i came up is to write django signals on old table and update new one.As old tables are being updated from multiple servers. -
Basic Django form response
I am new to Django and looking to build a quick form with a response. I am trying to build a form which would ask the user to input his name when the user clicks submit the page should reload and just say "Hello . urls.py class Question1Form(forms.Form): n = forms.CharField(max_length=100, widget=forms.TextInput( attrs={'placeholder': 'Number', 'class': 'form-control'})) views.py def home(request): if request.method == 'POST': form = Question1Form(request.POST) if form.is_valid(): result = [Question1Form.ans()] return HttpResponse(Question1Form.n) else: form = Question1Form() return render(request, 'index.html', {'form': form}) index.html <form action="" method="post" class="form"> {% csrf_token %} {{ form.non_field_errors }} <div class="form-row form"> <div class="col-sm-4"> {{ form.n.errors }} {{ form.n }} </div> <input class="btn btn-primary" type="submit" value="Submit" /> </div> </form> So how the code s -
How can I check model's data is connected accurately?
I wanna check whether model's data is connected accurately or not. models.py is class User(models.Model): trunsaction_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) regist_date = models.DateTimeField(auto_now=True) user_id = models.CharField(max_length=200,null=True) name = models.CharField(max_length=200,null=True) age = models.CharField(max_length=200,null=True) area = models.ForeignKey('Area',null=True, blank=True) class Area(models.Model): name = models.CharField(max_length=20, verbose_name='Area', null=True) class Prefecture(models.Model): name = models.CharField(max_length=20, verbose_name='Prefecture') area = models.ForeignKey('Area', null=True, blank=True) class City(models.Model): name = models.CharField(max_length=20, verbose_name='City') prefecture = models.ForeignKey('Prefecture', null=True, blank=True) class Price(models.Model): upper1000 = models.CharField(max_length=20, verbose_name='u1000', null=True) from500to1000 = models.CharField(max_length=20, verbose_name='500~1000', null=True) under500 = models.CharField(max_length=20, verbose_name='d500', null=True) city = models.ForeignKey('City', null=True, blank=True) Model's data means Area&Prefecture&City&Price,so I wanna know these data is connected accurately with User.How can I check this?I cannot find it to see db.sqlite3 by using DB Browser for SQLite .How can I print the answer in terminal?