Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
custom model/view logic for a page in django mezzanine?
I am wondering whether it would have been easier (and quicker) to "roll my own" blog instead of using Django Mezzanine as at the moment, the learning curve seems to be quite steep and almost counter-intuitive. I have a page (my homepage) that I want to implement the following logic (pseudocode for a "normal" django application is shown below). # ignore possible out of bounds errors etc. just an example def index(request, products_category_id=0): first_50_prods = Products.objects.filter(prod__category = products_category_id)[:50] return render(request, 'index.html' {'prods': first_50_prods}) I have no idea (and can't seem to find from the mezzanine documentation), how to add custom logic such as the one shown above, in my view. Can this be done or not? -
Include only field in Django model.
I have a Django read-only model, it has one column with geojson data, this field can easily be 500mb. Most of the times I don't have to work with this field, so I would like it to exclude from standard select queries. Is there some way to exclude it? I know I can exclude it with values_list but I am more interested in default behaviour? -
Django-admin, SELECT by fields
There is a UserTask module in which there are very heavy fields and they brake the request, how can I remove them from the query for Django Admin. They do not appear on the page, but Django uses something like this: SELECT * FROM UserTask; And you need: SELECT id, name, is_user FROM UserTask; It is necessary to remove them in the admin area, here is the registration of the model: class UserTaskAdmin(admin.ModelAdmin): list_filter = ('id', 'name') list_display = ('id', 'name') admin.site.register(UserTask, UserTaskAdmin) original version is russion. -
2 apps in one view Posts and Comments in Django
I have 2 apps Posts and comments. I'm trying to see the form on the posts but I can't seem to be able to display the form. Here is my code: Model - Post from django.db import models from django.utils import timezone from django.conf import settings from comments.models import Comment from django.contrib.contenttypes.models import ContentType from django.urls import reverse class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) @property def comment_list(self): instance = self return Comment.object.filter_by_Post(instance) def get_absolute_url(self): return reverse("post_list") @property def get_content_type(self): instance = self content_type = ContentType.objects.get_for_model(instance.__class__) return content_type Models for Comment from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.utils import timezone from django.conf import settings from django.db import models #from blog.models import Post class CommentManager(models.Manager): def filter_by_Post(self, instance): content_type = ContentType.objects.get_for_model(instance.__class__) qs = super(CommentManager, self).filter(content_type=content_type, object_id = instance.id) return qs class Comment(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) object=CommentManager() def __str__(self): return str(self.user.username) Forms for Comments from django import forms from datetime import datetime from comments.models import Comment from django.utils import timezone class CommentForm(forms.Form): content_type = forms.CharField(widget=forms.HiddenInput) object_id = forms.IntegerField(widget=forms.HiddenInput) … -
Can't access Post request data from request.data in Django
I'm having a lot difficulty accessing the post request data sent from my Angular server. Somehow Response(data) still returns the body of my post request accurately, however I can't access the content inside to create instance of my model. Below is my code Angular end: let header = new HttpHeaders({ 'Authorization': ' JWT ' + this.authToken, 'Content-Type': 'application/json', }); let body = { "var1": var1, "var2": var2, }; return new Promise(resolve => { this.http.post(this.server, body, {headers: header, withCredentials: true}).subscribe(data => { console.log(data); resolve(data); }, err => { console.log(err); }); }); Django @api_view(['POST']) @parser_classes((JSONParser,)) def order_processing(request): permission_classes = (permissions.IsAuthenticated,) data = request.data item = Item.create(data["var1"]) item.save() return Response(data) and I always end up getting the error: TypeError at /post/↵create() missing 1 required positional argument: which I think is due to data["var1"] being unavailable. But then Response(data) is still able to return the correct body so I don't know what exactly is the problem with it. Any help would be appreciated. -
I can't change IP:8000 to mysite.com:8000 using gunicorn
I have a problem with gunicorn, I can't up my host in my setting.py file like this: ALLOWED_HOSTS = ['http://api.colonybit.com', 'api.colonybit.com', 'http://colonybit.com:8000', '.colonybit.com:8000'] and when up to my server with gunicorn --bind colonybit.com:800 colonybitbasics.wsgi:application not working, show me this error [2018-07-24 11:31:04 -0200] [16840] [ERROR] Invalid address: ('colonybit.com', 800) [2018-07-24 11:31:04 -0200] [16840] [ERROR] Retrying in 1 second. [2018-07-24 11:31:05 -0200] [16840] [ERROR] Invalid address: ('colonybit.com', 800) [2018-07-24 11:31:05 -0200] [16840] [ERROR] Retrying in 1 second. [2018-07-24 11:31:06 -0200] [16840] [ERROR] Invalid address: ('colonybit.com', 800) [2018-07-24 11:31:06 -0200] [16840] [ERROR] Retrying in 1 second. [2018-07-24 11:31:07 -0200] [16840] [ERROR] Invalid address: ('colonybit.com', 800) [2018-07-24 11:31:07 -0200] [16840] [ERROR] Retrying in 1 second. [2018-07-24 11:31:08 -0200] [16840] [ERROR] Invalid address: ('colonybit.com', 800) [2018-07-24 11:31:08 -0200] [16840] [ERROR] Retrying in 1 second. [2018-07-24 11:31:09 -0200] [16840] [ERROR] Can't connect to ('colonybit.com', 800) I followed the next link: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 in this tutorial, I can't build a file .sock and the another link: http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/ not working well please help me, tell me how to replace IP:8000 with mysite.com:8000 -
Query params on detail view return a list instead of json nested serializers Django Rest Framework
I'm rather new to Django Rest Framework and I'm having a problem I don't quite understand. If I setup a APIView to return all the objects in a particular model I get an array of data as expected class ProcedureListView(APIView): def get(self, request, format=None): procedures = AutomationProcedure.objects.all() serializer = AutomationProcedureSerializer(procedures, many=True) return Response(serializer.data) My api call to this endpoint looks like $ http --json GET http://localhost:8000/api/procedures/ And the response [ { ... ... } ] But if I write a detail view that takes query parameters the single object still returns as a list class ProcedureDetail(generics.ListAPIView): def get_queryset(self): queryset = AutomationProcedure.objects.all() display_name = self.request.query_params.get('display_name', None) if display_name is not None: queryset = queryset.filter(display_name=display_name) return queryset And then if I make an API call in this manner: $ http --json GET http://localhost:8000/api/procedures/ display_name="jenkins" The response still comes back as a list. [ { ... ... } ] Now I know that Detailview is inheiriting from ListAPIView which it would make sense that it would come back as a List. But what am I supposed to do here? Override the serializer method to represent it as json or something? Thanks for your help in advance this has been a tough one The … -
Python Django+Nginx+uwsgi 502 Bad Gateway
Centos7,when I connect to my website, shows 502 Bad Gateway, I test my website with command uwsgi --ini systemctl start nginx And I cant figure out what's happened,please help me! here's nginx.conf upstream django { server 127.0.0.1:8000; } server { listen 80 default_server; listen [::]:80 default_server; server_name example.com; charset utf-8; include /etc/nginx/default.d/*.conf; location / { include uwsgi_params; uwsgi_pass django; } location /static/ { alias /usr/local/etc/dmp/static/; } } and uwsgi setting [uwsgi] chdir = /usr/local/etc/dmp module = DMP_python.wsgi plugins = python3 socket = :8000 chmod-socket = 666 master = true processes = 2 vacuum = true -
python table app that cycles itself
I am kinda new to python programming and i would need some help with a project i am trying to accomplish. So, i managed to scrape some data i needed from a website and store them to csv files. What i want to do now is to project/print them on a table/tables. But, there are some rules : 1) i want the table to be like 25 rows per page (1 data/row) and fill the whole screen. if the data i want to project/print exceed 25 rows, a new page will be created and store the next data and so on and so on. The data i am fetching are not specific every time. Sometimes could be like 10 data = 1 page/table with 10 rows, an other time could be like 70 data = 3 pages/tables (with 25 + 25 + 20 rows). 2) Then i want to cycle through pages/tables automatically Is this even possible to be made with python ? Also, is this possible to be made as an app or it would be easier to be made as a website app though Django for example ? I would love to point me to some direction guys, … -
Robust way to control access to model querysets in django
I am looking for a safe way to protect access from Organisations seeing other Organisations clients throughout my whole project. One organisation's users should never see other's and I was wondering if there is a structural way I can setup my project so that I am protected from making a coding mistake and revealing the wrong data to the wrong user. Currently I am just filtering all the Client queries by Organisation but I am concerned that at some point I may make a hole somewhere. I was thinking I could create a custom model manager for Client so that an Organisation is required for Client.objects.all() or Client.custommanager.all() Curious if there are other/better ways to do this? I have the following simplified model structure: class Organisation(models.Model): name = models.CharField(null=True, verbose_name = 'Name', max_length=100) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) organisation = models.ForeignKey('Organisation', null=True, on_delete=models.CASCADE) class Client(models.Model): advisor = models.ForeignKey(User, on_delete=models.CASCADE) -
How can I get the identifier of a comment for the response to that comment?
Anybody can help me ? I'm doing comments features in django and i stop because i don't know how to do his. My idea is set variable value with comment.id for each comment when click on "RESPONDER" button and send to view for save the comment including the parent identifier if the new comment is an answer. The form is displayed when you click on the button, showing the CSS class and anchor link. post.html: <div id="#comments"> {% for comment in comments %} <div class="single-blog-comment"> <div class="blog-comment-details"> <div class="review__info"> <h4><a>{{ comment.title }}</a></h4> </div> <div class="review__date"> <span>{{ comment.author }} | {{ comment.created_date }}</span> </div> <p>{{ comment.content }}</p> <div class="review__date"> <span> {% get_user_authenticated request username=comment.author as user_authenticated %} {% if user_authenticated %} <a href="{% url 'blog:delete_comment' comment_id=comment.id %}">BORRAR</a> {% else %} <a href="#answer_form" class="blog__answer__reply"> <input class="blog__answer__reply" type="submit" onclick="setCommentParentId( '{{ comment.id }}' )" value="RESPONDER"> </a> {% endif %} </span> </div> </div> </div> {% endfor %} <div class="blog__answer__form hidden"> <div id="answer_form" class="contact-form-wrap"> <form method="POST" action="{% url 'blog:add_comment' post_slug=post.slug %}"> {% csrf_token %} <div class="single-contact-form"> <div class="contact-box subject"> {{ comment_form.name }} </div> </div> <div class="single-contact-form"> <div class="contact-box subject"> {{ comment_form.email }} </div> </div> <div class="single-contact-form"> <div class="contact-box subject"> {{ comment_form.title }} </div> </div> <div class="single-contact-form"> … -
How do I accept multiple choices for a Charfield from CheckboxSelectMultiple widget in Django?
I'm trying to build a form in Django 1.11, where I have a set of checkboxes on a watch list to allow a user to set multiple alerts on an item they want to receive notifications on later. However, I'm not sure how to represent multiple options on a field like this. Here's my model code: class Watchlist(models.Model): CLOSES_IN_2_WEEKS, CLOSES_IN_1_WEEKS, CLOSES_IN_3_DAYS, CLOSES_TOMORROW = ( "CLOSES_IN_2_WEEKS", "CLOSES_IN_1_WEEKS", "CLOSES_IN_3_DAYS", "CLOSES_TOMORROW" ) ALERT_OPTIONS = ( (CLOSES_IN_2_WEEKS, "Closes in 2 weeks",), (CLOSES_IN_1_WEEKS, "Closes in 1 weeks",), (CLOSES_IN_3_DAYS, "Closes in 3 days",), (CLOSES_TOMORROW, "Closes tomorrow",), ) # I want to store more than one option alert_options = models.CharField(max_length=255, blank=True) def save(self): """ If this is submitted create 1 alert: "CLOSES_IN_1_WEEKS" If this submitted, create 3 alerts: "CLOSES_IN_2_WEEKS", "CLOSES_IN_1_WEEKS", "CLOSES_IN_3_DAYS", """ # split the submitted text values, to create them # yes, this should probably be a formset. I wasn't sure how I'd # handle the logic of showing 4 optional alerts, and only creating models # on the form submission, and remembering to delete them when a user # unchecked the choices in the form below And here's the form I'm using, below. I'm hooking into the __init__ method to pre-populate the form with possible … -
Django + Django REST: Updating two files at the same time Fails with unique constraint error
I have two files, I like to upload them to my server. Because I want to create a backup of my files, I have overridden the perform_update method. If I update one after another, everything works fine and as expected. But running tow request at the same time form my frondend I get the Unique-Constraint error. Can someone explain this behavior? def perform_update(self, serializer): instance = self.get_object() instance.create_backup() instance = serializer.save() # here it fails with Unique-Constraint The first request 5/ and 4/ are executed one after one. The last two are executed together, than the Unique-Constraint error occurs. -
How to set Python3 path in Phusion Passenger?
I'm currently trying to deploy a Django 2.0 app to our server using Apache and Phusion Passenger. However, whenever I run my test app, the page keeps telling me it is using Python 2.7 and Django 1.X. I have tried creating a virtual environment but I do not know how to tell the web server to use it instead. -
Django admin model, remove fields in select
To remove from request list fields? An example of a pseudocode can be used: admin.site.register(UserTask.objects.values('id', 'title'), admin.ModelAdmin) -
Django url based multi database
I need to write users into two databases. I decided to send them to different url. For example: /register/dbone/ and /register/dbsecond/ and then get request.url. But in Router two functions db_for_read() db_for_write() do not know anything about request object and url. How best to solve this? P.S. Maybe there is some other way to separate users into two databases, not url but something else? -
Password Reset functionality inheriting from Django clases - reverse url issues ('uidb64')
I want to create a Password Reset functionality but changing the templates. So I'm inheriting from Django classes. After I insert the email to reset password, I ge the following error: NoReverseMatch at /accounts/password-reset/ Reverse for 'confirm_reset_password' with keyword arguments '{'uidb64': '', 'token': '4y5-9ae986836e35f95b842c'}' not found. 1 pattern(s) tried: ['accounts\/password-reset-confirm/(?P[0-9A-Za-z_\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] I think the issue is that 'uidb64', but I don't know why is empty. Views: class CustomPasswordResetView(PasswordResetView): form_class = CustomPasswordResetForm email_template_name = 'account/password_reset_email.html' template_name = 'account/password_reset.html' class UserPasswordResetConfirmView(PasswordResetConfirmView): pass Form: class CustomPasswordResetForm(PasswordResetForm): email = forms.EmailField(widget=TextInputWidget) Urls: path('password-reset/', UserPasswordResetView.as_view(), name='reset_password'), re_path(r'^password-reset-confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', UserPasswordResetConfirmView.as_view(), name='confirm_reset_password') in reset template: <form action="" method="post"> {% csrf_token %} <div class="row "> {{ form.email }} </div> <div class="l-action"> <input type="submit" class="button" value="Reset my password"> </div> </form> In email template: a href="http://{{ domain }}{% url 'users:confirm_reset_password' uidb64=uidb token=token %}" -
Nested serializer using foreign key with only one object in DRF
I'm using Django Rest Framework with two models, a service and a message, where a service can have many messages. Using a foreign key. class Service(models.Model): servicename = models.TextField(blank=False) sender = models.TextField(blank=False) class Message(models.Model): service = models.ForeignKey(Service, related_name='messages', on_delete=models.CASCADE) description = models.TextField(blank=False) The only usecase is where you enter a service, which is nested to take input for the message. Therefore, service will create both the service and the message at the same time. If the service doesn't exist, it will be created. If it does exist, the message will point towards the service. As it is a one-to-many, it seems like I need many=True in my serializer, which is undesirable as there is never a usecase where two messages are inputted simultaneously, and also means the web UI will not work since lists are not supported. class MessageSerializer(serializers.ModelSerializer): class Meta: model = Message fields = ('description',) class ServiceSerializer(serializers.ModelSerializer): messages = MessageSerializer(many=True) class Meta: model = Service fields = ('servicename', 'sender', 'messages') def create(self, validated_data): messages_data = validated_data.pop('messages') print(messages_data) service, created = Service.objects.get_or_create( servicename=validated_data['servicename'], sender=validated_data['sender'] ) Message.objects.create(service=service, **messages_data[0]) return service So, is it possible to have a nested serializer with only one object during input? Removing many=True results in a … -
I get unable to load app 0 error while running django on uwsgi
I run; uwsgi --http :8091 --module proj2.wsgi But i get below errors; *** Operational MODE: single process *** Traceback (most recent call last): File "./proj2/__init__.py", line 5, in <module> from .celery import app as celery_app File "./proj2/celery.py", line 5, in <module> from celery import Celery ImportError: No module named celery unable to load app 0 (mountpoint='') (callable not found or import error) *** no app loaded. going in full dynamic mode *** *** uWSGI is running in multiple interpreter mode *** spawned uWSGI worker 1 (and the only) (pid: 13930, cores: 1) When i check celery, (proj2) [proj2@localhost proj2]$ which celery ~/Env/proj2/bin/celery It is strange that if i run project with runserver, it works. (proj2) [proj2@localhost proj2]$ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). July 23, 2018 - 17:46:01 Django version 1.9.1, using settings 'pro.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. But not working with uwsgi... -
ImportError: No module named django.core.wsgi with apache in ubuntu
First of all I have to tell you that I have already seen many solutions for this question. And I have tried most of them. But still could not resolve the issue. So I'm posting it again. Please find my 000-default.conf for apache WSGIPythonHome /usr WSGIPythonPath /home/test-admin/Documents/web_project:/home/test-admin/.local/lib/python2.7/site-packages <VirtualHost *:80> Alias /static /home/test-admin/Documents/web_project/static <Directory /home/test-admin/Documents/web_project/static> Require all granted </Directory> <Directory /home/test-admin/Documents/web_project/website> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess test-collection WSGIProcessGroup test-collection WSGIScriptAlias / /home/test-admin/Documents/web_project/website/wsgi.py ServerName www.test-collection.com ServerAlias test-collection.com ServerAdmin admin@test-collection.com sys.prefix >>> import sys >>> sys.prefix '/usr' >>> wsgi.py import os import sys path = r'/home/test-admin/.local/lib/python2.7/site-packages' if path not in sys.path: sys.path.append(path) path = r'/home/test-admin/Documents/web_project' if path not in sys.path: sys.path.append(path) sys.stderr.write('\n'.join(sys.path)) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "website.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() And django installed in path r'/home/test-admin/.local/lib/python2.7/site-packages' and output for ldd /usr/lib/apache2/modules/mod_wsgi.so linux-vdso.so.1 (0x00007ffccd7d1000) libpython2.7.so.1.0 => /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0 (0x00007f0eeb607000) libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f0eeb3e8000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f0eeaff7000) libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1 (0x00007f0eeadda000) libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f0eeabd6000) libutil.so.1 => /lib/x86_64-linux-gnu/libutil.so.1 (0x00007f0eea9d3000) libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f0eea635000) /lib64/ld-linux-x86-64.so.2 (0x00007f0eebdbe000) so I think mod_wsgi is installed for python 2.7. And tried printing sys.path in the error log and it's coming correctly I guess. Please find the error.log below. [wsgi:error] [pid 4021:tid 140595830531840] /usr/lib/python2.7 [wsgi:error] [pid 4021:tid … -
Caching a ViewSet with DRF : TypeError: _wrapped_view()
I just want to use caching to a ViewSet too slow :(, with Django REST Framework. I've do this : ... from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page from django.views.decorators.vary import vary_on_cookie ... class PRPKViewSet(viewsets.ModelViewSet): serializer_class = PrpkSerializer queryset = Prpk.objects.all().order_by('begin') # Authentification ! permission_classes = (IsAuthenticated,) # Only 'get' method http_method_names = ['get'] # Cache requested url for each user for 2 hours # @method_decorator(vary_on_cookie) @method_decorator(cache_page(60*2)) def get_queryset(self): """ allow rest api to filter by submissions """ queryset = Prpk.objects.all().order_by('begin') highway = self.request.query_params.get('highway', None) if highway is not None: queryset = queryset.filter(highway=highway) return queryset But when querying, I've this error : TypeError: _wrapped_view() missing 1 required positional argument: 'request' Memcached is installed. So, can I caching just one ViewSet (not using an extension ?) ? Thanks a lot. F. -
Reactjs - persist login jwt authentication
I am learning jwt authentication using this article as reference. I have a doubt from the code mentioned in the article. So there is a view called current_user: @api_view(['GET']) def current_user(request): """ Determine the current user by their token, and return their data """ serializer = UserSerializer(request.user) return Response(serializer.data) which was called in the frontend in App's componentDidMount function: constructor(props) { super(props); this.state = { displayed_form: '', logged_in: localStorage.getItem('token') ? true : false, username: '' }; } componentDidMount() { if (this.state.logged_in) { fetch('http://localhost:8000/core/current_user/', { headers: { Authorization: `JWT ${localStorage.getItem('token')}` } }) .then(res => res.json()) .then(json => { this.setState({ username: json.username }); }); } } The part that I don't understand is: Where is the code that retrieves user based on the token? The view (current_user) is just serializing and returning the request.user without checking if the token even belongs to request.user. -
Email confirmation link fail in django
I'm trying to create a confirmation system using email link and tokens using Django here are my files : tokens.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) account_activation_token = TokenGenerator() That is where I've created the token Forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(required=True, help_text='Must be a valid E-mail') user_name = forms.CharField(required=True, help_text='') password1 = forms.CharField(widget=forms.PasswordInput, help_text='') password2 = forms.CharField(widget=forms.PasswordInput, help_text='Password confirmation') avatar = forms.ImageField(required=False) class Meta: model = User fields = ('email', 'user_name', 'password1', 'password2', 'avatar') labels = { 'user_name': 'user_name', 'email': ' email', 'password1': 'password1', 'password2': 'password2', 'avatar': 'avatar', } def clean_email(self): data = self.cleaned_data['email'] return data.lower() That is where I've created the signup form views.py def signup(request): current_user_ip = get_client_ip(request) current_temp = Temp.objects.filter(created_by_ip=current_user_ip) current_temp.delete() if request.method == 'POST': signup_form = SignUpForm(request.POST, request.FILES) if signup_form.is_valid(): user = signup_form.save(commit=False) user.is_confirmed = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your Jehlum account.' message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) to_email = signup_form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Please confirm your email address to complete the registration') else: signup_form = SignUpForm() context = { 'signup_form': signup_form, … -
When creating a superuser
I want to create a superuser with email and username. I'd like it to be the way that email has the first priority over a username. I decided to change the built-in user. And so I created 2 classes. The first is UserManager(BaseUserManager), and the second class is User(AbstractBaseUser) Back to the problem, when I create a superuser through the command line, it creates a user, but it puts an email in the username field and the opposite way with the username. Here is my models.py class UserManager(BaseUserManager): def create_user(self, username, email, password=None, is_active=True, is_staff=False, is_admin=False): user_obj = self.model( email=self.normalize_email(email), username=username ) user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self, email, password): ... def create_superuser(self, username, email, password): user = self.create_user( email, username, password=password, is_staff=True, is_admin=True ) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name = 'email address', max_length=255, unique=True ) username = models.CharField(max_length=40, unique=True, verbose_name='username') active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD= 'email' REQUIRED_FIELDS = ['username',] objects = UserManager() Why does it mess up with username and email??? -
modelmultiplechoicefield django return queryset
Cannot assign "]>": "VehicleBattery.vehicle" must be a "Vehicle" instance. when form submit send upside define error so how can handle this query set in django this is form.py code class VehicleBatteryForm(forms.ModelForm): vehicle = forms.ModelMultipleChoiceField(queryset=Vehicle.objects.all()) class Meta: model = VehicleBattery fields =('vehicle') this is view.py code bform = VehicleBatteryForm(request.POST) print bform if bform.is_valid: print "*********if***************" bform.save() else: print "*********else*************"