Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sublimetext "Close Tag" command doesn't work with Django static tags
For some reason, when I am programming in SublimeText with Python / Django,%} tags interfere with Sublime's 'Close Tag' function. Here's an example of what I'm talking about in practice. It's an <img> tag that references a static file within an outer <div>. Notice that the %} tag is white — Sublime has, for some reason, not recognized it as valid code: When I position my cursor at the other end of this line and use the 'Close Tag' command, I would expect sublime to close my </div>. Instead, it does this: Any idea how to fix this problem? -
Django - How long should migrations take for large PostgreSQL table (4m rows)? [on hold]
I'm adding a ForeignKey field with null=True to an existing table with about 4 million rows. The table has 30 fields. I am using PostgreSQL 9.5. The migration has been running for about an hour now, and it is still applying. Is it normal for a migration for a large table to take this long? Or is it caused by some other issue? -
Extend table with a related metadata table
i've looking for the best solution in order to extend a generic table ("Sensors") with another table that defines all the communications specification, those informations are not easily predictable and they can be different by the "Communication protocol specification", for example: serial speed address http endpoint endpoint username token for authentication mqtt endpoint and so on... Now, basically, i'm thinking to create a metadata table and associate the table via a foreign key with n-1 relation between Sensors (n) and the Communication Protocol Specification (1), but i want to be sure about this solution. I'm using Django with Postgres -
Use objects as field choices in Django model
I'm trying to figure out how to use Django Field.choices as strategy selector. Here's a super simple example of what I'm trying to achieve: class AbstractStrategy: description = str() def do_something(self): raise NotImplemented def __init__(self, description): self.symbol = description def __str__(self): return str(self.description) class ABCStrategy(AbstractStrategy): def do_something(self): print('doing something abc way') return class XYZStrategy(AbstractStrategy): def do_something(self): print('doing something xyz way') return ABC = ABCStrategy('ABC') XYZ = XYZStrategy('XYZ') STRATEGIES = ( (ABC, 'ABC'), (XYZ, 'XYZ'), ) And then STRATEGIES is used as choices=STRATEGIES. Later in implementation I theoretically should be able to call strategy from Model's object directly with strategy_field.do_something but unfortunately this method doesn't work for now. Is the problem in implementation or it's generally impossible to use choices this way? -
Django 2.1 Models Importing Custom User Model
I have been working on an extended User model in my Django 2.1 project. I am curious to know if the way in which I am importing my CustomUser model into another model (for use as a ForeinKey) is the correct way of doing so. I have encountered verbiage in the past indicating that it is not correct to simple import the User model from the admin app, but rather import it from django.conf. example importing from the base User model: from django.conf import settings User = settings.AUTH_USER_MODEL ... class <ModelName>(models.mode): user = ForeignKey(User, on_delete=models.CASCADE, default=1) Now that I am using a CustomUser Model (extending AbstractUser), users/models.py: class CustomUser(AbstractUser): objects = CustomUserManager() def __str__(self): return self.username Is it better practice to import this model via setting (as shown above) or is how I am doing it below (in my Post app) the right way to it: posts/models.py: from users.models import CustomUser class Post(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, default=1) I am assuming this is the wrong way to go about this, but I am not sure why, can someone let me know why the above is not best practice? Note: It does get the job done though. Thanks! -
Can I render form wizard with message and with data preserved?
I have a form wizard that checks if google recaptcha is valid. If not, the form shows a message that it is invalid and please try again. The issue is that the form forgets its data when this happens, so if the user tries to submit the form again, instead of submitting normally, the form goes back to step 1 because it doesn't have all the data. Any ideas on how to remedy this? Here is the code: def done(self, form_list, **kwargs): recaptcha_response = self.request.POST.get('g-recaptcha-response') url = 'https://www.google.com/recaptcha/api/siteverify' values = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } captcha = urllib.parse.urlencode(values).encode() req = urllib.request.Request(url, data=captcha) response = urllib.request.urlopen(req) result = json.loads(response.read().decode()) if result['success']: *** success logic *** else: form = self.get_form(step=self.steps.current, data=self.request.POST, files=self.request.FILES) messages.add_message(self.request, messages.ERROR, 'Invalid captcha. Please try again.') return super(FormView, self).render(form, **kwargs) -
Multiple queries in django ORM
I have the following user model, class User(AbstractBaseUser, PermissionsMixin, Base): email = models.EmailField(db_index=True, unique=True, max_length=255) mobile = PhoneNumberField(null=True) and room model, class Room(Base): name = models.CharField(db_index=True, unique=True, max_length=255) members = models.ManyToManyField(User) I want to check if there exists a room which has both a and b as members. I tried this, PrivateRoom.objects.filter(members__id=first.id, members__id=second.id).exists() This gives me an error keyword argument repeated. Can someone help me with the query. -
postgres authentication failed for user that doesn't exist anymore
I recently switched from PostgreSQL 10 to 11 (perhaps not in the cleanest way), but I made sure that all of version 10 was uninstalled and cleaned out of my computer. I had a Django project running on the v10 instance prior to the reinstall, but after I got rid of all of the old stuff, and after I attempted to migrate onto the new databases, I began getting: psycopg2.OperationalError: FATAL: password authentication failed for user "Elliott" "Elliott" was a user on the old install that is entirely gone at this point. I attempted reinstalling psycopg2 and Django, but neither did the trick. I went as far as to reinstall Python entirely, but it still didn't work. No database functions work (makemigrations, migrate, etc.). Are there files somewhere that I need to get rid of? Where am I going wrong? -
Unit Test for Django that clicks a JS button
I'm new to django- and to testing in Python in general. I've written a simple test application that contains a page with a JS button which displays some text on the page when clicked. I'm wanting to write a test that makes sure that when that button is clicked, the text actually appears on the page, but I'm not sure how to actually define that programmatically, and my google-fu is lacking- there's plenty of instructions on how to make sure it's returning a 200 OK response, or that the page contains a certain string, but i don't know how to actually have it click on the button and then check for that string. Thanks for any help you can provide! -
Django no reverse match for admin
I'm working on somebody else's codebase, and I've hit a bug. I'm getting this error: NoReverseMatch at /admin/login/ Reverse for 'authorize' not found. 'authorize' is not a valid view function or pattern name. I've come across this error frequently before, but only in my own code. This seems to be happening in django's own admin system, which I've never come across before... -
How to add more form widgets on button click in django?
So i created simple models (pasted below) and passed forms based on those models to template view. Now i want to add button which will allow user to add more fields of Ingrediends class and there I have few questions. Is it somehow possible to do without using JS only in django? If not what is the best way to do it? And one more question about the way I am dealing with forms. Is it ok or should I put both models in one form? Thank you for answers. MODELS: class Recipe(models.Model): title = models.CharField(max_length=254) author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL) description = models.CharField(max_length=200) add_date = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Ingrediends(models.Model): name = models.CharField(max_length=254) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name="ingredient") FORMS: class RecipeForm(forms.ModelForm): class Meta: model = Recipe fields = ('title',) class IngrediendForm(forms.ModelForm): class Meta: model = Ingrediends fields = ('name', ) Template: {% extends 'recipes/base.html' %} {% block body_block %} <form class="" method="post"> {% csrf_token %} {{form.as_p}} {{ingredient_form.as_p}} <input type="submit" value="Add recipe"> </form> {% endblock %} In case I didn't explain well what I want: Before: Title: [_______] Ingredient: [________] [+]<-click After: Title: [_______] Ingredient: [________] Ingredient: [________] [+]<-click -
Django Custom User --- Edit new CustomUser fields in admin
I am trying to expand on the tutorial by William Vincent, posted below: https://wsvincent.com/django-custom-user-model-tutorial/ I am trying to add new fields to the CustomerUser model I extended via the AbstractUser import from django.contrib.auth.models: users/models.py: from django.db import models from django.contrib.auth.models import AbstractUser, UserManager class CustomUserManager(UserManager): pass class CustomUser(AbstractUser): bio = models.TextField(max_length=500, blank=True) objects = CustomUserManager() def __str__(self): return self.username I added the 'bio' field to the model above, but when I access a user via the django admin portal, I don't see the new 'bio' field in there with the default admin fields packaged with django: ie: Personal info: first name, last name, email address, etc. My CustomUser app is registered to the admin portal like so (following the tutorial mentioned above): As a test for myself, I was able to display the bio field successfully (showing blank as expected) in my list_display. To reiterate, my problem is I have no way of updating this field when I click to edit a user. The good news is that django picked up the migration of my new 'bio' field. from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class … -
What may cause OperationalError in Django, to be specific in base.py in line 296?
Every time I am trying tu run my django base website I get an OperationalError at /. - no such table: django_session. It says the error is in base.py in line 296. When I enter the file, Python indeed shows that in the last function of the base.py: def process_exception_by_middleware(self, exception, request): """ Pass the exception to the exception middleware. If no middleware return a response for this exception, raise it. """ for middleware_method in self._exception_middleware: response = middleware_method(request, exception) if response: return response raise the last raise has no exception to reraise. I have been trying to fix it for ages but I gave up. I was thinking that I might have deleted some code of base.py but the local history says it was not edite, and the function looks exactly the same when I check it on Django github repository. Any ideas what may be wrong? -
how to add new django app to deployed django project (using nginx,gunicorn)?
While running the django project locally, I can access my home, admin, app1, app2 directory (i.e localhost:portnum , localhost:portnum/admin , localhost:portnum/app1 , localhost:portnum/app2 ) The problem begins when I deployed the app in a server ( I used nginx and gunicorn for django deployment with the help of this guide ) Problem : - I'm unable able to access example.com/admin, example.com/app1 , example.com/app2. I'm able to access my home example.com anyway. When I trying to access example.com/app1/ the page give an error 403 forbidden 2018/11/17 18:00:55 [error] 28459#28459: *8 directory index of "/home/ubuntu/project/app/" is forbidden, client: 172.68.146.88, server: studevsoc.com, request: "GET /events/ HTTP/1.1", host: "www.studevsoc.com" 2018/11/17 18:00:58 [error] 28459#28459: *13 open() "/usr/share/nginx/html/app" failed (2: No such file or directory), client: 172.68.146.10, server: example.com, request: "GET /events HTTP/1.1", host: "www.example.com" Some solutions which I tried to follow before this question::- Django: when trying domain.com/admin gives 404 with an old unexisting urls file Nginx 403 error: directory index of [folder] is forbidden Thank You for trying to solve my problem. -
ValueError: Related model cannot be resolved in Django
I'm using Django 2.x. I have a model user_setting which have foreign Key to Country model which was created under address module. Now, I'm using djanog-countries-plus to add Country data and thus have changed user_setting module to now point to Country model of django-countries-plus. from countries_plus.models import Country from django.contrib.auth.models import User class UserSetting(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField(User, on_delete=models.CASCADE) country = models.ForeignKey(Country, on_delete=models.PROTECT, blank=True, null=True, default=None) modified = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) The initial migration generated was # 000_initial class Migration(migrations.Migration): initial = True dependencies = [ ('address', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UserSetting', fields=[ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('modified', models.DateTimeField(auto_now=True)), ('created', models.DateTimeField(auto_now_add=True)), ('country', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='address.Country')), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'db_table': 'user_setting', }, ), ] and the new migration generated after changing the reference of the ForeignKey field is # 0002_auto_20181108_0724 class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.AlterField( model_name='usersetting', name='country', field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='countries_plus.Country'), ), ] The settings have installed apps like 'countries_plus', ##################### # created apps ##################### 'accounts', But when I run migrate, it gives error as raise ValueError('Related model %r cannot be resolved' % self.remote_field.model) ValueError: Related model 'countries_plus.Country' cannot be resolved Full log Running migrations: Applying … -
How to list Django Template Cache keys?
I'm looking for a way to list out the cache keys from a specific template file when using Django's (Django 2+; Python 3.5+) template caching. For example: {% load cache %} {% block header %} {% cache 600 contact_page_header %} Contact page header, this will create a cache file. {% endcache %} {% endblock header %} {% block content %} <!-- HTML stuff here --> {% cache 600 contact_page_content %} {# Fragment #} Contact page header, this will create a cache file. {% endcache %} <!-- More HTML stuff --> {% endblock content %} In here, there's contact_page_header and contact_page_content. Both of these will have their own .djcache file. I want to check for these keys (dynamically) whenever the model is saved, and delete contact_page_header.djcache and contact_page_content.djcache. I know I can do this specifically with cache.delete('contact_page_header') and cache.delete('contact_page_content'). I'd like to find a way to dynamically find the cache fragments from a template and delete them without delete all the other template cache, and without specifically specifying which cache files to delete because the template cache might change, and I want to use re-usable code in other views. Ideally, I'd like to write a Mixin that, on save, will check … -
How to include forward slash in django username
I am working on a website that requires user username to include forward slash. something like 'CSC/15U/1155' as username. django says 'Enter a valid username. This value may contain only letters, numbers, and @/./+/-/_ characters.'. my question is as follows: is there a way to allow forward slash in username without extending the user model, if there is please help. thanks in advance. -
Log multiple uwsgi logger to stdout
I'm running uwsgi inside a Docker container for a Django application. I want to log uwsgi, request, and django logs differently, so I created the following configuration in my .ini file. [uwsgi] logger = main file:/dev/stdout logger = django file:/dev/stdout logger = req file:/dev/stdout log-format = "method": "%(method)", "uri": "%(uri)", "proto": "%(proto)", "status": %(status), "referer": "%(referer)", "user_agent": "%(uagent)", "remote_addr": "%(addr)", "http_host": "%(host)", "pid": %(pid), "worker_id": %(wid), "core": %(core), "async_switches": %(switches), "io_errors": %(ioerr), "rq_size": %(cl), "rs_time_ms": %(msecs), "rs_size": %(size), "rs_header_size": %(hsize), "rs_header_count": %(headers), "event": "uwsgi_request" log-route = main ^((?!django).)*$ log-route = django django log-route = req uwsgi_request log-encoder = format:django ${msg} log-encoder = nl:django log-encoder = json:main {"timestamp": "${strftime:%%Y-%%m-%%dT%%H:%%M:%%S+00:00Z}", "message":"${msg}","severity": "INFO"} log-encoder = nl:main log-encoder = format:req {"timestamp": "${strftime:%%Y-%%m-%%dT%%H:%%M:%%S}", ${msg}} log-encoder = nl:req The problem is that now my logs for my django and req don't show up. I'm guessing that's because multiple loggers want to write to /dev/stdout and can't. How can I 1. Write everything to stdout while 2. Formatting my logs differently based on a regex? I confirmed this is the case by turning of some of the log routes and seeing everything work. -
Extra Id in model
I am trying to build list of reports that belongs to a project. Each project can have a number of reports. Each report has to have unique ID, ie: 1, 2, 3, etc.. I am storing all reports in one table and that is why I can't use Django's autoField because I am already using it for Primary Key. class Cawreport(models.Model): caw_id = models.AutoField(primary_key=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) # report_id is unique for each project report_id = models.IntegerField(default=1) What is the best way to increase report_id for each new report? What would you recommend? Do you recommend me to find maximum number (report_id) for each project? Or, should I "count" report_id entries for each project and add +1? Or maybe something completely different? Thanks in advance -
Django Autocomplete Light create new choice
I have been working through the following tutorial provided for Django Autocomplete Light: https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html I have successfully implemented autocompletion for one of the fields in my form, however I am unable to complete the following section: https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html#creation-of-new-choices-in-the-autocomplete-form The documentation states that I should be able to add in a feature which allows the user to create a new choice in the form if their required choice is unavailable. However the tutorial is not particularly clear in explaining how to do this. I am trying to implement a form in which the user: Selects from an autocompleting list of Categories Selects a Message corresponding to the chosen Category If the Category or Message they wish to choose is not available, they should be able to add to the existing choices I have this partly implemented, but it does not appear to work correctly as if no Category is selected, the drop down for the Messages displays the list of Categories. However, if a Category is selected, the correct Messages are displayed as required. models.py class Category(models.Model): name = models.CharField(max_length=20, default="Empty",primary_key=True) def __str__(self): return self.name class Message(models.Model): category = models.ForeignKey('Category',on_delete=models.CASCADE,null=True,blank=True) text = models.CharField(max_length=200,default="No message",primary_key=True) def __str__(self): return self.text forms.py class FeedbackForm(autocomplete.FutureModelForm): optional_message … -
How do I implement a machine learning model trained by python to a webpage?
In spyder, I have trained a Naive Bayes classifier for predicting whether or not a school will be canceled base on the amount of snow and other features. So, my question is two parts. First, how do I make a website so that a user can input the snow and temperature, and when the user clicks a button, the classifier (which is in python) can spit out a response? Do I have to use Django for that (so that everything is in python and would maybe make stuff easier)? Second, How do I save the classifier so that the model doesn’t have to be trained every time? -
React calling Django API CSRF
Yo guys , I'm doing a frontend react that call a Django api. I ve got a big problem : I want to call a Django API with reactjs but the API need a csrf and I have no idea how i could get that csrf, after looking on internet, i saw some people using function other telling that the django api need a route that retrun the token. I'm totally lost. my discord if needed Wadi #1916 -
ERROR: could not open extension control file "/usr/pgsql-9.6/share/extension/postgis.control": No such file or directory
I want to deploy my project to VPS Centos7. But i am getting error while installing postgres. When i type create extension postgis; Getting error ERROR: could not open extension control file "/usr/pgsql-9.6/share/extension/postgis.control": No such file or directory Because postgis.contol is located in another place, find /usr -name postgis.control /usr/share/pgsql/extension/postgis.control But postgres trying to create it from /usr/pgsql-9.6/share/extension/postgis.control This question already was asked before, but my problem is other. -
Confused about modeling relations for feedback in django
New to Django. I'm trying to develop a Feedback module, but designing a database structure makes me confused for various reasons: Where do I need to store feedback_score(positive/neutral/negative feedback ratio), should it be put in custom User, or somewhere else? How should I get the recipient of the feedback credentials, should it be passed by URL, how to link recipient to FeedbackModel in class-based-views? How to feedback_score to be calculated each time for every User? models.py User = get_user_model() # Create your models here. class FeedbackModel(models.Model): id = models.AutoField(primary_key=False, db_column='id') sender = models.ForeignKey( User, on_delete=models.CASCADE, primary_key=False, related_name='feedback_left_by') # recipient = models.ForeignKey( # User, # on_delete=models.CASCADE, # primary_key=True) FEEDBACK_OPTION = ( (-1, 'Negative'), (0, 'Neutral'), (+1, 'Good'), ) feedback = models.IntegerField(choices=FEEDBACK_OPTION) opinion = models.CharField(max_length=255) class Meta: ordering = ['left_by', '-id'] urls.py from django.urls import path from . import views app_name = 'feedback' urlpatterns = [ path('leave_feedback/<str:left_to>/', views.leave_feedback.as_view(), name='leavefeedback'), ] views.py from django.shortcuts import render, reverse from django.views.generic import TemplateView, CreateView from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from .models import FeedbackModel decorators = [login_required] @method_decorator(decorators, name='dispatch') class leave_feedback(CreateView): model = FeedbackModel fields = ['feedback', 'opinion'] success_url = '/' #template_name = "feedback/leave_feedback.html" def form_valid(self, form): form.instance.sender = self.request.user # ? return … -
Return type of the save() method of form of Django
I am beginner learning to create registration form here. Here is the register view class which I had written earlier. def register(request): registered= False if request.method=="POST": user_form= UserRegistrationForm(data=request.POST) profile_form= UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): print(type(user_form.save())) user_form.set_password(user_form.password) user_form.save() profile_form.save(commit=False) profile_form.user=user_form if 'profile_pic' in request.FILES: profile_form.profile_pic=request.FILES('profile_pic') profile_form.save() registered=True else: print(user_form.errors,profile_form.errors) else: user_form=UserRegistrationForm() profile_form=UserProfileInfoForm() return render(request,'basic_app/register.html', {'user_form':user_form, 'profile_form':profile_form, 'registered':registered}) This is gives me the error that my user_form object has no set_password() method. I then changed my code by saving the "user_form" into another instance named "user". Here is my new code. I have added an additional print function to check the type of the two objects. def register(request): registered=False if request.method=="POST": user_form=UserForm(data=request.POST) profile_form=UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user=user_form.save() print(type(user_form)," ",type(user)) user.set_password(user.password) user.save() profile=profile_form.save(commit=False) profile.user=user if 'profile_pic' in request.FILES: profile.profile_pic=request.FILES['profile_pic'] profile.save() registered=True else: print(user_form.errors,profile_form.errors) else: user_form=UserForm() profile_form=UserProfileInfoForm() return render(request,'basic_app/register.html', {'user_form':user_form, 'profile_form':profile_form, 'registered':registered}) The output for the print statement gave this <class 'basic_app.forms.UserRegistrationForm'> <class 'django.contrib.auth.models.User'> I do not understand howcome their type is different when both are instances of the same form. Also why did the first code didn't work when the second one did. Its my first question on SO. Thank you.