Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
cookiecutter-django local development with docker
I've never use docker for development on local machine so I have few questions that I didn't find in documentation. After setup I can't figure out how do I can install my packages via pip. I tried: docker-compose -f local.yml run --rm django pip install some-package. It installed package somewhere, but not in project. Do I need to build every time when I add new package? How to run django managment commands in another thread docker-compose -f local.yml run --rm django python manage.py mycommand stop runserver command that is not convenient Where do I see celery tasks log ? How to run: celery -A apps.taskapp worker -l info celery -A apps.taskapp beat -l INFO to see debug messages of my tasks -
pg_dump: too many command-line arguments (first is "--host=localhost")
I have another one question about this "...too many CLA..." with pg_dump. Any answer under another questions didn't help for me. I try to use djang-dbbackup lib with my Django project. I make $ python manage.py dbbackup and get this error: CommandConnectorError: Error running: pg_dump last_cosmetics --host=localhost --username=postgres --no-password --clean b'pg_dump: too many command-line arguments (first is "--host=localhost")\r\nTry "pg_dump --help" for more information.\r\n' Also I try to run this pg_dump last_cosmetics --host=localhost --username=postgres --no-password --clean command from Windows cmd, but get also the same error. What is the problem? -
django apache dot in url creating relative path
disclaimer, I am new to Apache/Django. Hi all, I am having trouble with Django running on Apache. Right now my web app uses dynamic URLS. Apache appends the current directory to the end of the URL anytime there is a . (dot) in the URL path. example- url I want: http://127.0.0.1/jfe/customer/566069/277271. url I get: http://127.0.0.1/jfe/customer/566069/277271./jfe/customer/566069/277271/jfe/customer As you can see Apache interprets the dot as a directory and appends it to the end of the URL. This issue does not happen when running the local Django server. my urls.py: url(r'^customer/(?P<customer_number>[0-9]+)/(?P<invoice>[^/]+)/$', views.cbt_portfolio, name='cbt_portfolio') is this something I would configure in .htaccess, or is there no point since URL's are being handled by Django urls.py? or in httpd.conf? or urls.py? any help would be appreciated. -
Alternative Django package for "django.core.xheaders" in Django 2.0
I'm migrating an old Django project to Django 2.0. In one of view files, I came across an import statement: from django.core.xheaders import populate_xheaders I'm trying to figure out the alternatives of this packages - neither in google nor in stackoverflow. Can anyone help me find the alternative package? -
Change GET to POST request in 'sort' of tables2
I need to have a sorting request back to my template page in the POST request form, but the sort of the column provide by django-tables2 give a GET request form like that : http://127.0.0.1:8000/mypage?sort=mycolumn mytemplate.html <form id="test" action="{% url 'myview' %}" method="post"> {% csrf_token %} #somes buttons and filters <div class="row" style=" white-space: nowrap; top: 950px;"> <div class="form-group col-lg-7 center"> {% load django_tables2 %} {% render_table table %} <br /> </div> </div> </form> How transform this 'sort' in POST request instead of the GET request ? Thanks in advance. -
Django - invalid literal for int() with base 10: '[{"added": {}}]'
Ive just come across an issue as per the below: invalid literal for int() with base 10: '[{"added": {}}]' This site data object does not have any sitesupernets as yet. so it should just return empty not try to query with the "added stuff", I have no idea where that is coming from? site_data = get_object_or_404(Site.objects \ .prefetch_related('sitesupernet_set') \ .prefetch_related('sitesupernet_set__subnet_type') \ ,id=site_id ) -
django vs qlik sense: naming the ID field "id" vs "table1_id"
Qlik sense recommends that each table's primary key be named something like "table1_id" if the table name is Table1. This allows their "automatic association" to properly detect like-named fields and link them. On the other hand, the django best practice is to just use the default primary key name "id" for each table, e.g. table named Table1 will have a field called "id", same for a table named Table2, etc. As such, a django-managed database will not yield optimal ID field names for Qlik Sense's automatic association. What's the best practice among Qlik Sense + Django users? -
Django REST asks for CSRF token even with TokenAuthentication
I am building a server for both mobile and web environments and I want to have session auth alongside with token auth. However, these seem to be at odds with each other. I have a different view for logins in both schemes. If I log in as a user inside the browsable API and then send a request for token login for a different user, the server complains that there is no CSRF token. However if I log out, suddenly there's no problem. I am not sure how severe it will be after frontend is implemented and the logins come from different devices, but so far it doesn't look good. Any idea how to stop requiring CSRF token if the correct Authorization: Token <token> header is passed? Or different solution to my problem? -
How can I load multiple files to Django using Web UI and select individual file from them and perform analytics on that?
So, I want like to insert multiple files (I will use S3 for storage) and I should be able to select individual file and do visualizations and analytics on that. I don't have problems connecting to S3 or creating visualizations using D3.js, the question is how can I select individual file? Thanks for you help in advance! -
Django - set model field to the DB "Now" value in a model method
I am trying to set one of the model's DateTime fields to "now". To avoid any time difference issues, I am trying to stick to the time values generated in the DB (as opposed to those generated in Python, like datetime.datetime.now()). However, it looks like it is difficult to do it from within an instance method. I am trying to do something like the below: class MyModel: ... last_fetched = models.DateTimeField(null=True) def fetch_scenes(self): # Do some work ... self.objects.get(id=self.id).update(last_fetched=django.db.models.functions.Now()) Django does not allow accessing the model's manager from within instance methods (probably for a good reason). Is there any way to access and update the query set consisting of the instance alone? -
Django postgres make custom migration from CharField to JSONField
I need to change this data = models.CharField(max_length=500, null=True) to this data = JSONField(null=True, blank=True, default={}) From what I understand, I have to write custom migration. Closest info I managed to find is here, but I am completely clueless what to do with RunPython if that even correct thing to do here. -
Django - prefetch query not working on related mapping tables
I am trying to prefetch and select related some foreign key models whilst traversing multiple mapping tables. however I am still stuck with 500+ queries, I managed to get it down from 1000, but it doesn't look like the subnet field is getting fetched. I have tried the below: circuits = SiteCircuits.objects.all() \ .exclude(circuit__decommissioned=True) \ .select_related('site') \ .select_related('circuit') \ .prefetch_related( Prefetch( 'circuit__devicecircuitsubnets_set', queryset=DeviceCircuitSubnets.objects.all() \ .select_related('subnet') ) ) \ .prefetch_related('circuit__circuitnotes_set') \ .prefetch_related('circuit__circuit_type') \ .prefetch_related('circuit__circuitfile') \ .prefetch_related('circuit__service_provider') \ .prefetch_related('circuit__circuit_type') and this way also: circuits = SiteCircuits.objects.all() \ .exclude(circuit__decommissioned=True) \ .select_related('site') \ .select_related('circuit') \ .prefetch_related('circuit__devicecircuitsubnets_set') \ .prefetch_related('circuit__devicecircuitsubnets_set__subnet') \ .prefetch_related('circuit__circuitnotes_set') \ .prefetch_related('circuit__circuit_type') \ .prefetch_related('circuit__circuitfile') \ .prefetch_related('circuit__service_provider') \ .prefetch_related('circuit__circuit_type') but I have 500+ queries of below, which I thought I would of got by selecting related on subnet: SELECT "config_devicecircuitsubnets"."id", "config_devicecircuitsubnets"."device_id", "config_devicecircuitsubnets"."circuit_id", "config_devicecircuitsubnets"."subnet_id", "circuits_circuit"."id", "circuits_circuit"."name", "circuits_circuit"."order_no", "circuits_circuit"."ref_no", "circuits_circuit"."expected_install_date", "circuits_circuit"."install_date", "circuits_circuit"."circuit_type_id", "circuits_circuit"."preference", "circuits_circuit"."service_provider_id", "circuits_circuit"."username", "circuits_circuit"."password", "circuits_circuit"."tel_no", "circuits_circuit"."cost_per_month", "circuits_circuit"."contract_length", "circuits_circuit"."speed_down", "circuits_circuit"."speed_up", "circuits_circuit"."rssi", "circuits_circuit"."bearer", "circuits_circuit"."decommissioned", "config_subnet"."id", "config_subnet"."subnet", "config_subnet"."mask", "config_subnet"."subnet_type_id" FROM "config_devicecircuitsubnets" INNER JOIN "circuits_circuit" ON ("config_devicecircuitsubnets"."circuit_id" = "circuits_circuit"."id") INNER JOIN "config_subnet" ON ("config_devicecircuitsubnets"."subnet_id" = "config_subnet"."id") WHERE "config_devicecircuitsubnets"."circuit_id" = '1' ORDER BY "config_devicecircuitsubnets"."id" ASC LIMIT 1 Duplicated 526 times. Line error: {{ item.circuit.devicecircuitsubnets_set.first.subnet }}{{ item.circuit.devicecircuitsubnets_set.first.mask }} High level models: -Site -Circuit -Device -Subnet --SiteCircuits (mapping table) --DeviceCircuitSubnets (mapping table) -
Can only edit one object in a database in Django - why?
I have created a booking system whereby users can have multiple bookings. I am trying to create a way for users to edit these bookings and have created the following mechanism. Users book -> object created in database -> users can see upcoming bookings listed on upcoming template -> users can change the booking. Where I am running into the issue is when I am trying to access the editing view. Essentially when the edit button is clicked, regardless of the booking it will always take the user to the booking form of the first object in the database but not the related one. See code below: models.py class Booking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) unique_id = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) coursename = models.CharField(max_length=200) daterequired = models.DateTimeField(default=datetime.now(timezone.utc)) students = models.CharField(max_length=200) length = models.IntegerField() matches = models.ManyToManyField(Student, related_name='matches') slug = models.SlugField(max_length=40, blank=True) def save(self, *args, **kwargs): if not self.pk: self.slug = slugify(self.name) super(Booking, self).save(*args, **kwargs) def __str__(self): return str(self.user.username) views.py def upcoming(request): booking = Booking.objects.filter(user=request.user) for bookings in booking: bookingtime = bookings.daterequired currenttime = datetime.now(timezone.utc) timedifference = currenttime - bookingtime bookinglength = int(bookings.length*3600) timeremaining = bookinglength - timedifference.seconds hoursremaining = timeremaining/3600 hours = int(hoursremaining) minutes = (hoursremaining*60) % 60 seconds = (hoursremaining*3600) … -
How to pass context to DjangoAdmin's change_list_results.html
I currently have the following in my admin class def changelist_view(self, request, extra_context=None): context = extra_context or {} context['econtext'] = 'Extra Context' return super(BaseModelAdmin, self).changelist_view(request, extra_context=context) However, calling {{ econtext }} in my change_list_results.html turns up empty. Am I overriding the wrong method for this? -
Can't connect to django wesite started on VPS
I have tried to start server with Django project like this: python3.4 manage.py runserver 0.0.0.0:8000 and like this: python3.4 manage.py runserver my_domain.com:8000 and it starts fine but I can't visit my site. Any ideas what I've done wrong? -
Remove option from ModelChoiceField
I just got my hands on an user account create view that looks like this: @login_required def user_create(request): template_name = 'user/User_Create.html' if request.method == 'POST': #this part is not important pass else: form = UserCreateForm() user_error = '' context = {'form': form, 'user_error': user_error} return render(request, template_name, context) with the UserCreateForm written like this: class UserCreateForm(forms.ModelForm): def save(self, commit=True): user = super(UserCreateForm,self).save(commit=False) username = self.cleaned_data['username'] username = username.replace(".", "") username = username.replace("-", "") user.username = username if commit: user.save() return user class Meta: model = User fields = ['username', 'name', 'profile', 'redefine_password', 'name_created'] widgets = { 'username': forms.TextInput(), 'name': forms.TextInput(), 'profile': forms.Select(), 'redefine_password': forms.CheckboxInput(), 'name_created': forms.TextInput(), } My problem is that we have different types of users(Admin, Supervisor, Support, Normal) and currently, Supervisors are able to create Admin accounts... My initial approach was to pass the user from the view to the form, like this: form = UserCreateForm(user=request.user) and in the form, I'm trying to delete the option if the user is not an Admin, like this: def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(UserCreateForm, self).__init__(*args, **kwargs) if not user.is_superuser: del self.fields['profile'][1, 'Administrador'] but that failed miserably, I got a TypeError: 'ModelChoiceField' object does not support item deletion. I … -
Separator Between Multiple Variables in Django Template (DTL)
Given three or more variables in my DTL template what is the most convenient way to assure that an interpunct is always between two variables? <div>{{ person.name }} · {{ person.phone }} · {{ person.city }}</div> Expected: <div>John · 1234567 · New York</div> <!-- {{ person.city }} is null or empty--> <div>John · 1234567</div> Is there an easy way to solve this with built-in functionality? I try to avoid writing custom Django filters/template tags. -
Installing django-tables2 on heroku returning error: invalid command 'egg_info'
I'm trying to install django-tables2==1.21.1 on my Heroku dyno. Below is the error logs when I try to install it: ~ $ pip install django-tables2 Collecting django-tables2 Using cached django-tables2-1.21.1.tar.gz Complete output from command python setup.py egg_info: /app/.heroku/python/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'extras_require' warnings.warn(msg) /app/.heroku/python/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'include_package_data' warnings.warn(msg) /app/.heroku/python/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'install_requires' warnings.warn(msg) usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: -c --help [cmd1 cmd2 ...] or: -c --help-commands or: -c cmd --help error: invalid command 'egg_info' ---------------------------------------- I am running python 2.7.14 and django 1.11.11. All other packages install without any issues. Any ideas on what the issue could be? Thanks -
modelname.objects.all() displays error [duplicate]
This question already has an answer here: Unresolved attribute reference 'objects' for class '' in PyCharm 3 answers I get an error whenever i try to access the data from database in the program. This is models.py from django.db import models class Files(models.Model): serno=models.IntegerField(primary_key=True) firstfile=models.CharField(max_length=1000) secondfile=models.CharField(max_length=1000) def __str__(self): return self.firstfile +' '+ self.secondfile This is views.py from .models import Files def getfile(request): data=Files.objects.all() return data This displays an error at objects in "Files.objects.all()" The error is Unresolved attribute reference 'objects' for class 'Files' This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items -
Get common ManyToMany objects with django extra select
class Seller(object): type = ... name = ... cars = models.ManyToManyField(Car) class PotentialBuyer(object): name = ... cars = models.ManyToManyField(Car) class Car(object): extra_field = ... extra_field2 = ... Suppose I have a relationship like this. I would like to use extra queryset modifier to get the list of cars that are already been picked out by PotentialBuyers when I fetch a seller object. I suppose the query queryset will something like this. def markPending(self) return self.extra(select={'pending': 'select images from PotentialBuyer as t ...'}) How can I accomplish this? Is there a better way? I could fetch the seller object and the potential object and do sets, but I'd think it would be cleaner to make it handled by the database. I am using PostgreSQL 9.5. -
Problems when trying to show LDAP attributes
I need help concerning the authentication in Django with an LDAP user. I want to show more than just this: class Meta: model = User fields = ( 'first_name', 'last_name', 'email', ) Am I right, when I say I need a new Model by using django-ldapdb? Something like this: class LdapUser(ldapdb.models.Model): base_dn = "CN=LDAP_IPA,CN=Users,DC=sbvg,DC=ch" object_classes = ['posixAccount', 'shadowAccount', 'inetOrgPerson'] # inetOrgPerson first_name = CharField(db_column='givenName', blank=True) last_name = CharField("Final name", db_column='sn') email = CharField(db_column='mail') salutation = CharField(db_column='title', blank=True) phone = CharField(db_column='telephoneNumber', blank=True) mobile_phone = CharField(db_column='mobile', blank=True) Or is it even easier with django-auth-ldap: AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", "mobile": "mobile", "salutation": "title", "dn": "distinguishedName", } How do I call these in my forms? As you can see, I need help about this. If you are familiar with the problem or have any idea, please do not hesitate to post it. -
Django: Best practice regarding auto increment primary key
Hi I am building a Django application and during this I am doing test uploads into my database, then deleting the data. I understand that when I do this, the next insert will 'pick up where it left off' when inserting the auto-increment primary key int. I.e: I insert 3 rows into my table 'Sample': auto_id | sample 1 | JSUDH172 2 | QIUWJ185 3 | PNMSY111 When i delete these, and enter them in again, it will start at 4: auto_id | sample 4 | JSUDH172 5 | QIUWJ185 6 | PNMSY111 I understand this is built in to stop Django overwriting primary keys, but when the primary keys are no longer there, it (mainly from a superficial point of view) annoys me that it doesn't reset. I am uploading thousands of rows into certain tables during this development, so sometimes it starts hundreds/thousands in. I know I can always restart the project 'from scratch' after development is finished, but I was wondering whether anyone had any useful workarounds or if people just left it as it is (if they have the same view as me) thanks -
How do I point password reset to my own templates?
In my urls.py, I have: from django.contrib.auth import views as auth_views urlpatterns += [ url("^reset-password/$", auth_views.password_reset, { "template_name": "pages/password_reset_form.html" }, name="reset_pw" ), ] My password_reset_form.html has this: <form id="reset-pw-form" name="resetPWForm" method="post" action="{% url 'reset_pw' %}"> {% csrf_token %} <input id="id_email" type="email" placeholder="Enter email" name="email" required> <button type="submit" >Submit</button> </form> When you hit the submit button on the form, it POSTs to /reset-password, then GETs /password_reset/done/. How can I make it GET /reset-password/done and load my_template.html instead? -
Can I check if a user is logged in for the first time after this user is logged in? - Django
I'm trying to catch the first time someone logs in so I can redirect him/her to another page then normally. I'm working with groups. A admin can make a group with multiple users (with generated usernames and passwords). So it can be that a user is already created before the user logs in (There is no register form for just one user) This is the code that I want: def index(request): if request.user: user = request.user if user.last_login is None: return redirect('profile') else: return redirect('home') else: return redirect('/login') I've read about checking user.last_login but for this case that doesn't work because it checks this method AFTER the user logs in. Which means that user.last_login is never None. Can someone help me how can see when a user logs in for the first time? -
Why is 'DIRS': ['templates'] also works? 【About Django templates】
To be able to find the template file in django, everybody said you shoud amend the settings.py like this: TEMPLATES = [{ 'DIRS': [os.path.join(BASE_DIR, 'templates')] }] but I found that this also works: TEMPLATES = [{ 'DIRS': ['templates'], }] My question is what is the difference between them. Why does no one recommend 'DIRS': ['templates']?