Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where are Django User model fields saved?
Sorry, if this is a very basic question, but I was wondering where Django User model field values like is_active are saved as I don't see them in the database. I am using a custom User model, but they must still be saved somewhere... :) models.py class MyUserManager(BaseUserManager): def create_user(self, username, email, password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) self.username = username user.set_password(password) user.save(using=self._db) return user ... class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_active = False objects = MyUserManager() USERNAME_FIELD = 'email' ... Tables in database: Schema | Name | Type | Owner --------+------------------------+-------+------------ public | auth_group | table | xxx public | auth_group_permissions | table | xxx public | auth_permission | table | xxx public | django_admin_log | table | xxx public | django_content_type | table | xxx public | django_migrations | table | xxx public | django_session | table | xxx public | drillapp_myuser | table | xxx public | drillapp_question | table | xxx public | drillapp_story | table | xxx (10 rows) This is how the user table looks. No … -
Unable to show model data from db to template
I am unable to show data from django 3rd model(class Jenkinsjobsinformation) to template. It is possible to publish data from 1st and 2nd model(Projectname and Jenkinsjobsname).Below find below my model: model.py class Projectname(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Jenkinsjobsname(models.Model): projectname=models.ForeignKey(Projectname) jobsname = models.CharField(max_length=200) def __str__(self): return self.jobsname class Jenkinsjobsinformation(models.Model): jobinformation=models.ForeignKey(Jenkinsjobsname) build = models.IntegerField() date = models.DateField(null=True) views.py def index(request): project_name=Projectname.objects.order_by('-name')[:5] context = {'categories': project_name} return render(request,'buildstatus/index.html', context) def detail(request,projectname_id): project_name=Projectname.objects.order_by('-name')[:5] jobs=Projectname.objects.get(pk=projectname_id) context = {'jobs': jobs, 'categories':project_name} return render(request,'buildstatus/detail.html', context) def jobdetail(request,projectname_id,jobinformation_id): project_name=Projectname.objects.order_by('-name')[:5] jobs=Projectname.objects.get(pk=projectname_id) jobdetail=Jenkinsjobsname.objects.get(pk=jobinformation_id) context = {'jobs': jobs,'categories':project_name,'jobdetail':jobdetail} return render(request,'buildstatus/job_detail.html', context) urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<projectname_id>[0-9]+)/$', views.detail, name='detail'), url(r'^(?P<projectname_id>[0-9]+)/(?P<jobinformation_id>[0-9]+)/$', views.jobdetail, name='job_detail'), ] index.html {% extends "base.html" %} {% block text1 %} {% if categories %} <ul> {% for category in categories %} <li><a href ="{% url 'detail' category.id %}">{{category.name }}</a></li> {% endfor %} </ul> {% else %} <strong>There are no test categories present.</strong> {% endif %} {% endblock %} detail.html {% extends "base.html" %} {% block text1 %} {% if categories %} <ul> {% for category in categories %} <li><a href ="{% url 'detail' category.id %}">{{category.name }}</a></li> {% endfor %} </ul> {% else %} <strong>There are no test categories present.</strong> {% endif %} {% … -
Django multiple database transaction lock
I have 2 databases configured like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db1', ... }, 'db1': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db1', ... }, 'db2': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db2', ... } } Notice that default and db1 is the same database. And if I have two nested transactions like this: with transaction.atomic(): with transaction.atomic(using='db1'): ... Django wants to start two transactions in the same database and it causes OperationalError: (1205, 'Lock wait timeout exceeded; try restarting transaction'). Is there any way to avoid this? I'm using Django 1.10 and it worked well in Django 1.9. And I cant change db names and aliases in settings. -
Is it possible to call an Django Foreign Key object in success of Ajax?
Is it possible to call an Django Foreign Key object in success of Ajax ? models.py class Message(models.Model): id = models.AutoField(primary_key=True) chat = models.ForeignKey(Chat, models.CASCADE, null=True, related_name='chat') message = models.CharField(max_length=5000) date = models.DateTimeField(auto_now_add=True) views.py def message_view(request): chatid = request.GET.get('chatid', None) messages = Message.objects.filter(chat__id=chatid) message_list = list(messages.values()) data = { 'message_list': message_list } return JsonResponse(data) chatoverview.html $(document).ready(function(){ $(".btn_load_messages").click(function(){ var chatid = $(this).val(); $.ajax({ url:'/ajax/messages', data: { 'chatid': chatid }, dataType: 'json', success: function(data){ var message_list = data.message_list; var requestuser = "{{ request.user.id }}" $(".container-text2").empty(); $.each(message_list, function(index, value){ $(".container-text2"). append("<div class=text1>"+ value.message +"</div>"); }); } }); }); }); I need the chat.buyer.id. So i would do something like: $(".container-text2").append("<div class=text1>"+ value.chat.buyer.id +"</div>"); But this does not work. Is it possible to do something like this ? If yes, could you please tell me what i have to change to get it working ? -
Send CSRF Token in dropzone
I have tried to send csrf token in my AngularJS/Django app using the following code. The $rootScope.CSRFToken contains token value that is received from Cookie object. All other services are working fine with ajax but when I call the service via dropZone, using headers, it gives the error that Server responded with 403 code. This is how I'm configuring dropzone: $scope.dzOptions = { url : $scope.saveUrl, paramName : 'newCaseFiles', maxFilesize: $rootScope.maxCaseFileSize, addRemoveLinks : true, autoProcessQueue: false, uploadMultiple: true, parallelUploads: 20, headers: { 'X-CSRFToken': $rootScope.CSRFToken } }; It worked fine until CSRF mechanism was implemented in the application. Please, help. -
python - Packaging my webapp
Please I'm new to python. I want to know how to package my web application to make it downloadable and installed on a device(like facebook, whatsapp, Instagram and the like). I've searched but all I get is directing me on packaging python modules. Can anyone help please? Thanks in advance. -
Eventlet is_monkey_patched issues False
Hello I have a django app. My whole system configuration is the following: python 3, django 1.11, eventlet 0.21.0. 1) Nginx as an upstream server: upstream proj_server { server unix:///tmp/proj1.sock fail_timeout=0; server unix:///tmp/proj2.sock fail_timeout=0; } 2) Supervisor that controls workers. There is a gunicorn worker: [program:proj] command=/home/vagrant/.virtualenvs/proj/bin/gunicorn -c /vagrant/proj/proj/proj/deploy/gunicorn.small.conf.py proj.wsgi:application directory=/vagrant/proj/proj/proj/deploy user=www-data autostart=true autorestart=true stdout_logfile=/var/log/supervisor/proj.log 3) This is a gunicorn.small.conf content: bind = ["unix:///tmp/proj1.sock", "unix:///tmp/proj2.sock"] pythonpath = "/vagrant/proj/proj/proj/deploy" workers = 2 worker_class = "eventlet" worker_connections = 10 timeout = 60 graceful_timeout = 60 4) And this is proj.wsgi content: """ WSGI config for proj project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import eventlet eventlet.monkey_patch() from eventlet import wsgi import django.core.handlers.wsgi import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settings") # This … -
Initial value in django form dropdown is not empty?
I have a form where I define selection criterias for report. One of the dropdowns 'building' that is auto populated from the model , should be not mandatory and have default value as empty. I can't achieve the empty part . I want first field in my dropdown in my form building = forms.IntegerField( widget=forms.Select( choices=Building.objects.all().values_list('id', 'name') ) , required=False ) in view file when I initialize the code form = PaymentRangeForm(initial = {'building': 0 }) I use crispy forms in my template but I don't think it makes any difference. {{ form|crispy}} I am not getting any error but the default is not empty it has a value of first record from the model. What I am missing? -
Deploying Django to a server
I've been studying django, and mostly django rest framework for many months now, and now have something I wish to deploy. This is my first time deploying Django to a server, but I've deployed Angular applications in the past with nginx. I've gone through so many tutorials, and nothing is working for me, I have no idea what I'm doing wrong. Oh and to be clear, my attempts have been on freshly made virtual servers, not the same server that is currently running my angular frontends. I've followed this page https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 to the letter, I get upto the part with ~/myproject/manage.py runserver 0.0.0.0:8000 but then where they show that navigating to the servers ip address on port 8000 shows an 'It worked' page, I get no response. I've also followed https://simpleisbetterthancomplex.com/tutorial/2016/10/14/how-to-deploy-to-digital-ocean.html, with the same problem. I've also followed: http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html, with the same problem, and also ran # test.py def application(env, start_response): start_response('200 OK', [('Content-Type','text/html')]) return [b"Hello World"] # python3 #return ["Hello World"] # python2 with uwsgi --http :8000 --wsgi-file test.py, and still no response. The server is with digitalocean, I've tried so many different variations of tutorials for this too, all with the same effect. Things notable that I've tried … -
Django custom serializer response
Is there a way of getting django API response as {"1":"country1", "2":"country2"} instead of [{"id":1,"country":"country1"},{"id":2,"country":"country2"}] -
How to resolve the Migration Errors?
I have two models ie; Model1 and Model2. One field in Model2 acted as a foreign key of Model1. Here Primary Key of Model1 is 'id'. But now i modified the primary key field, removed id and added field called demo_num as primary key.Now my models looke like class Model1(models.Model): dem_num = models.IntegerField(primary_key=True) class Model2(models.Model): dem_fk = models.Foreignkey('Model1') but when i am doing migrate it is showing error like, django.db.utils.OperationalError: (1829, "Cannot drop column 'id': needed in a foreign key constraint of table Model2) How to solve this problem? Note: Without deleting migrations file I want to do it -
changin from function based view to class based view - Django
This is my function based view def reset(request): return password_reset(request, template_name='login/reset.html', email_template_name='login/reset_email.html', subject_template_name='login/reset_subject.txt', post_reset_redirect=reverse('success')) TO change this view to the class based view I have to written this class ResetPassword(View): def get(self, request): return password_reset(self.request, template_name='login/reset.html', email_template_name='login/reset_email.html', subject_template_name='login/reset_subject.txt', post_reset_redirect=reverse('success')) def post(self, request): return password_reset(self.request, template_name='login/reset.html', email_template_name='login/reset_email.html', subject_template_name='login/reset_subject.txt', post_reset_redirect=reverse('success')) Anything wrong here? Thank you. Code works perfectly -
Failing to connect Facebook with Django using AllAuth library
After trying to connect the ALLAUTH library with Django suing the post: https://medium.com/@jinkwon711/django-allauth-facebook-login-b536444cbc6b I went for the documentation and for the information, it was of no use to me. I want to know the simplest way to connect my facebook profile with AllAuth and Django 1.11.5 Kindly, let me know as I am struggling to get the connect with Facebook and Django 1.11.5. -
How do you put data from one form as a default for another in the same view in django?
Basically, I am new to Django. I am attempting to create a timesheet website where the user would select a task for the week and then add the hours they worked for each day that week. However, each day is intended to be stored in an individual record. How would you create a form that would take only take one task input, but loop through and create 5 records, one for each day? -
I get no log message from django running heroku
I'm running a Django site on Heroku, and the server returns a 500 error, but no reason why. All I get from heroku logs is this message: heroku[router]: at=info method=GET path="/accounts/login/" host=dagenssalg.herokuapp.com request_id=02ec11bf-ea26-4f98- ab5a-270147167d42 fwd="87.57.162.154" dyno=web.1 connect=0ms service=29ms status=500 bytes=234 protocol=https DEBUG is set to false: DEBUG = False Is there any way to display the detail of the error? Best regards Kresten -
Customize django_admin_log change message
I am trying to make the best use of the django_admin_log for our project. In short, we want (on the ADMIN side) the user to be FORCED to input a detailed CHANGE MESSAGE that overrides the existing change log entry. For example, when I add a new record to a table/model, the change message just reads "added" / "deleted" etc... but what I am wanting is for this to be much more detailed.. does anyone have any experience or an idea for a solution here? We're at a loss as to the best way to approach it. More specifically - is there a way to re-direct when a user clicks "save" to the latest django_admin_log entry?? -
Can I pass the data to base template ?
I have a base template, and every other template extends from it. but the base.html, how can I set the data in it? This is code snippet of base.html: ... <li class="dropdown bell"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class=" fa fa-user-circle"></i>191457****@qq.com</a> <ul class="dropdown-menu nav-menu"> ... I want to change the 191457****@qq.com to the passed data, it should be flexible, variable, that is take out from database. There is static html now. I tried in every template to set it, but you know this is a lot of repetition operation, if there is a simple method, I think python will be worthy of the name. -
Localization doesn't work
I created a Django site with localization built in, using python manage.py runserver to test it. But after setting it live with Apache/WSGI, the localization doesn't work correctly. I can see dates being translated (so somehow it knows the current language), but all my site-specific strings are untranslated. I have no idea where to look though on where to fix this. -
ValueError: Cannot query "": Must be "User" instance
I am trying to create a follower system where user can get to follow investor not between user and user but between user and investor. However I am getting an error. I am still not sure if i have to create a different table for follow or not but here is the code. Please share your idea for better modelling of follow system between user and investor class Investor(models.Model): investor = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=False, null=False, help_text='Full Name') followers = models.ManyToManyField( User, related_name='followers', blank=True) @classmethod def follow_investor(cls, investor, follower): investor, created = cls.objects.get_or_create(investor=investor) investor.followers.add(follower) @classmethod def unfollow_investor(cls, investor, follower): investor, created = cls.objects.get_or_create(investor=investor) investor.followers.remove(follower) url(r'^investor/(?P<action>.+)/(?P<slug>[-\w]+)$', views.follow_unfollow_investor, name="follow-unfollow-investor"), def follow_unfollow_investor(request, action, slug=None): follower = request.user investor = Investor.objects.get(slug=slug) if action == "add": Investor.follow_investor(investor, follower) elif action == "remove": Investor.unfollow_investor(user, follower) return redirect('/') -
Django file sharing application (issues providing link to user)
i am creating file sharing app. I am able to upload files but unable to provide its download link to user. Please find below view, def user_in(request): if not request.user.is_authenticated: return render(request, 'accounts/logout.html') else: if request.method == 'POST': form_new = Fileupload(request.POST, request.FILES ) #instance=form_new.save(commit=False) #instance.save() if form_new.is_valid(): instance = form_new.save(commit=False) instance.user_uploaded=request.user instance.save() return redirect('in') else: form_new = Fileupload() data = user_files.objects.filter(user_uploaded=request.user) args = {'form_new': form_new, 'data': data}#, 'url': form_new.get_absolute_url()} return render(request, 'accounts/in.html', args) and model.py is, class user_files(models.Model): Filename = models.CharField(max_length=50) Browse = models.FileField(upload_to='img/') user_uploaded = models.CharField(max_length=50, blank=True) template is , <form action="." method="POST" enctype="multipart/form-data" > <h3>Welcome to DropBox<br><br></h3> {% csrf_token %} {{form_new.as_p}} <p><input type="submit" value="Save" ></p> <br> <a href="{% url 'logout' %}">Logout</a> {%else%} <p>You must login first</p> <a href="{% url 'login' %}">Logout</a> {% endif %} <br><br> S <a href="{% url 'share' %}">Share Files</a> <br><br> User is : {{request.user}} {% for da in data %} <h3>{{da.Filename}} {{da.Browse}} </h3> {% endfor %} </form> Requesting you to please guide me how to provide download link for uploaded link, i am stuck at this point. thanks in advance. -
IO error after I change my template settings
Im new to django, I am trying to make an e-commerce site. Since I always received errors each time I try to do makemigrations I have removed TEMPLATE_DIRS and included it to TEMPLATES settings are stated below: #TEMPLATE_DIRS = (os.path.join(os.path.dirname(BASE_DIR), "static", 'templates', ), ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ (os.path.join(os.path.dirname(BASE_DIR), "static", 'templates',), ) after I change it my site returned to this kind of error, what could be the problem Request Method: GET Request URL: http://localhost:8000/admin/ Django Version: 1.11.6 Exception Type: IOError Exception Value: [Errno 22] Invalid argument: u"C:\\trydjango\\src\\ ('C:\\trydjango\\static\\templates',)\\admin\\index.html" -
How to limit field choices related to another table in database?
I'm working on simple expenses manager. Every user is able to add/remove/edit an Operation, which represents expense or earning. However I have noticed a bug - while adding new Operation it is possible to choose other users Accounts and Categories. Here is my Operation model: class Operation(models.Model): def get_category_color(self): return Category.objects.get(name=self.category).color types_tuples = ((-1, 'expense'), (1, 'earning')) user = models.ForeignKey(User) account = models.ForeignKey(Account) category = models.ForeignKey(Category) date = models.DateField() amount = models.DecimalField(max_digits=10, decimal_places=2) type = models.IntegerField(choices=types_tuples) currency = models.CharField(max_length=3) color = property(get_category_color) OperationCreate view: class OperationCreate(CreateView, OperationMixIn): model = Operation form_class = OperationForm success_url = reverse_lazy('manage_operations') def form_valid(self, form): operation = form.save(commit=False) operation.currency = Account.objects.get(pk=form.instance.account_id).currency self.update_account_balance(form) form.instance.user = self.request.user return super(OperationCreate, self).form_valid(form) and OperationForm: class OperationForm(ModelForm): class Meta: model = Operation fields = ['account', 'type', 'category', 'date', 'amount'] The question is how can I limit choices for Account and Category that are available during posting new Operation? I would like user to see only those which are related to his/her account. I tried limit_choices_to as a parameter for models.ForeignKey(Account) and models.ForeignKey(Category) in Operation model but couldn't make it work that way. I assume I need to use a query which will return only Accounts and Categories related to the current … -
How django save method works? Sometimes it creates new record and sometimes update, why?
I want to ask why this code: object(group_id=group_id, sr=11).save() updates all records with particular group_id and set its sr to 11, whereas the following code creates a new record in the database instead of updating existing records. g = object(group_id=group_id, sr=11).save() g.save() The code above creates new record in the database whereas the first code update existing records, why? What is the difference? Thanks for your answers. -
Saving django form inside for loop
This question is related to this. I'm planning to save values from my form fields. Below is my code for loop code: def form_valid(self, form): tooth = [18, 17, 16, 15, 14, 13, 12, 11, 21, 22, 23, 24, 25, 26, 27, 28, 48, 47, 46, 45, 44, 43, 42, 41, 31, 32, 33, 34, 35, 36, 37, 38] tooth.reverse() mytooth = {} pt = self.kwargs['pk'] for t in tooth: mytooth = self.request.POST.getlist('tooth_' + str(t), []) mytooth = " ".join(mytooth) form.instance.status = me form.instance.position = t form.instance.patient = PatientInfo.objects.get(pk=pt) return super(DentalRecordCreateView, self).form_valid(form) The problem is that I can see values using show = str(t) + mytooth messages.success(self.request, show) # display values but only the field form.instance.patient has value in my db. What am I missing here? -
Django save user as inactive
Why is doing something so simple seem so complicated in Django? It started with setting up a user model where email is used to login, a pain... Now I am trying to save a user as user.is_active = False but it is saved as active. Any tips very welcome or any other guidance as Django has been quite a painful experience so far compared to Flask. Note, I have also tried @receiver(pre_save, sender=get_user_model()) below. views.py ... from .models import Story, MyUser from .forms import SignupForm, LoginForm from django.dispatch import receiver from django.db.models.signals import pre_save @receiver(pre_save, sender=MyUser) def set_new_user_inactive(sender, instance, **kwargs): if instance._state.adding is True: print("Creating Inactive User") instance.is_active = False else: print("Updating User Record") ... def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): user = get_user_model() user.objects.create_user( form.cleaned_data['username'], form.cleaned_data['email'], form.cleaned_data['password'], ) return HttpResponseRedirect(reverse('index')) else: form = SignupForm() return render(request, 'drillapp/signup.html', {'form': form}) ... models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager ... class MyUserManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) self.username = username user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, date_of_birth, password): user = self.create_user( email, password=password, ) user.is_admin = True …