Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django TransactionManagementError when trying to create token on user post_save signal with Django Rest Framework
I am getting a django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. error when trying to create a Token during a post_save signal with Django Rest Framework. If I remove the post_save signal for the Token creation, everything works, but I get no token so I know it's the token creation causing the issue. If I wrap the Token create statement with a with transaction.atomic(): I get no errors, but the token is never saved to the DB, but I can print the token key value? I'm currently at a loss. Note that I am using PostgreSQL if that makes a difference. Any help is appreciated. Django (1.11.7) djangorestframework (3.7.7) Here is my serializers.py: ... from rest_framework import serializers from django.contrib.auth import get_user_model class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField() password = serializers.CharField(write_only=True) def create(self, validated_data): user = UserModel.objects.create( username=validated_data['email'], email=validated_data['email'] ) user.set_password(validated_data['password']) user.save() return user class Meta: model = UserModel fields = ('id', 'email', 'password',) This is my signals.py: ... from rest_framework.authtoken.models import Token @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: # with transaction.atomic(): # commented out see above token = Token.objects.create(user=instance) print(token.key) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_profile(sender, instance=None, … -
Dynamic formsets with search inputs
Initially, on the page was only the FIRST formset instance with input so I can search objects in database. After adding some other dynamically via javascript, clicking any of fresh added inputs launch the search in the FIRST, initial input. The problem goes away if i refresh the page. The goal is to achieve that behaviour without refreshing the page. Even when I installed plugin designed for dynamic django forms - the inputs behave in correct way if theyre just standard inputs, but switching them to searchfields triggers behaviour mentioned above. -
how to compare a date field to the current date in django
this is my model class class Truck(models.Model): reg = models.IntegerField() host = models.CharField(max_length = 20) insuranceExp = models.DateField() pollutionExp = models.DateField() fitnessExp = models.DateField() def __str__(self): return str(self.reg) this is my function def asset(request): template = 'notice/alert.html' trucklist = Truck.objects.all() d = date.today() reminder = {'message':[],'trucklist':trucklist} for truck in trucklist: while d<=truck.insuranceExp: if (truck.insuranceExp-d).days==30: warning = 'only 30 days remaining to expire insurance of truck Id = '+str(truck.reg) reminder[message].append(warning) elif (truck.insuranceExp-d).days==15: warning = 'only 15 days remaining to expire insurance of truck Id = '+str(truck.reg) reminder[message].append(warning) elif (truck.insuranceExp-d).days==7: warning = 'only 7 days remaining to expire insurance of truck Id = '+str(truck.reg) reminder[message].append(warning) else: pass how would i compare both of them in a no. of days please help me thanks in advance -
pass data from Django to amchart JS with JSON
I want to pass data from my Django view to my html and then take the data to my chart js or pass the data directly to my amchart. views.py: def nodo_detail(request,nodo_id): El_Nodo = Nodo.objects.get(pk=nodo_id) all_nodos = Nodo.objects.order_by('pk').all() var = Variable() v = dir(var) elemento = El_Nodo.variable_set.order_by('pk').all() watts = elemento.last().Watts prefix = '' chartData = "[" for t in elemento: chartData += prefix chartData += "{\n" chartData += " date: " chartData += '"' + str(t.Data_time.year) + "-" chartData += str(t.Data_time.month) + "-" chartData += str(t.Data_time.day) + " " chartData += str(t.Data_time.hour) + ":" chartData += str(t.Data_time.minute) + ":" chartData += str(t.Data_time.second) + '"' + ",\n" chartData += " value:" chartData += str(t.Watts) + ",\n" chartData += " volume: " chartData += str(t.Watts) + "\n }" prefix = ", " chartData += "]" context = {'El_Nodo': El_Nodo, 'all_nodos': all_nodos, 'v': v, 'watts': watts, 'chartData':chartData, "asdf":json.dumps(chartData)} return render(request, 'inicio/detail.html', context) The data that I want to pass is chartData, with the for loop I try to do the JSON format also I try the JSON python librery. detail.html: {% block Stock %} <input type="hidden" id="stock" value="{{chartData}}"> <!-- or asdf--> {% endblock%} amchartjs: var chartData = JSON.parse(document.getElementById("stock").value); // or directly var chartData … -
Django crudbuilder & Bootstrap datepicker
Django==1.11.7 django-crudbuilder==0.2.5 Using Bootstrap datepicker. Now trying to use the datepicker in a crud form for a date field. In a normal Django form, this would work: self.fields['payment_date'].widget.attrs.update({'class': 'datepicker'}) But how can the class:datepicker be set for a particular field in a crud form? The documentation does'n seem to mention anything useful on css or html class -
clean method not working for URLField
I'm working on something where I require users to enter URLs. I then realized that most users don't prepend 'http://' when writing a URL and then I decided to use a clean method. After checking lots of places for URLField clean methods, I came up with this: def clean(): cleaned_data = super().clean() url = cleaned_data.get('url') if url: if not url.startswith('http://'): url = 'http://' + url cleaned_data['url'] = url return cleaned_data Unfortunately, this doesn't work as I still get the invalid url error. Is there something I'm missing? And if yes, what? -
Django Form Wizard Dynamic Form Not Saving Data
Currently Happening: Dynamically generated form and form fields are being displayed. Enter some data into the said fields, but self.get_all_cleaned_data() returns nothing. Form returns to page 0 instead of submitting the form and using done() What I want to happen: - Data in fields to be retained and displayed when going back, or to the confirmation page - Form to actually submit and use done() to process and save The following the my forms.py class OrderForm(forms.Form): class Meta: localized_fields = ('__all__',) def __init__(self, *args, **kwargs): self.fields = kwargs.pop('fields') fields = self.fields super(OrderForm, self).__init__(*args, **kwargs) if not isinstance(fields, str): for i in fields.fields.all(): widget = forms.TextInput() _type = forms.CharField if i.field_type == Field.TEXTAREA_FIELD: widget = forms.Textarea ... self.fields[i.name] = _type(**fields) This is supposed to get Database created forms and field data and generate fields accordingly. For example: Form A has fields: Name (Regular Text Field) Address (Textarea) The above code will then generate fields for those. The next block of code is from my views.py file FORM_TEMPLATES = { "0": 'order/details.html', "1": 'order/details.html', "2": 'order/details.html', "3": 'order/details.html', "4": 'order/details.html', "confirm": 'order/confirm.html', } class Order(SessionWizardView): form_list = [OrderForm] def get_current_step_form(self, company, *args, **kwargs): step_form = [Form.objects.all()] step_form.append('Confirm') return step_form def get_context_data(self, form, … -
Django 2. Auth views template_name config
I want to use Django v2 LogIn class based view but i notified something there class LoginView(SuccessURLAllowedHostsMixin, FormView): """ Display the login form and handle the login action. """ form_class = AuthenticationForm authentication_form = None redirect_field_name = REDIRECT_FIELD_NAME template_name = 'registration/login.html' redirect_authenticated_user = False extra_context = None The template_name config was registration/login.html ? it is too strange I have another folder names. But here is as static template_name :( Many problems were due to this So question is what to do in my own views? in auth.views making template_name = None is showing a error: IsADirectoryError at /login/ Thanks) -
Using Firebase Auth with Django
I want to use firebase authentication for my django webapp. To achieve this, I think would I need to write a custom auth backend - is that right? I don't see any libraries that already do this - django-allauth looks like it comes pretty close as an alternative but I am interested in the phone number verification provided by firebase. I'm also confused about what happens to the User model and functions like request.user or user.is_authenticated. Right now I use the authenticate and login functions - how does django know that a user is logged in via firebase? Would I still be creating a User model for every user? Thanks -
Django form missing fields
I'm trying to get a simple form working. Oddly, other forms I wrote in this app are working fine, but this one wont show the fields. Can anyone tell me what I'm missing? Here are the files views.py: def newnote(request, record_id): if request.method == 'POST': form = NoteForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/tracker/all/') else: form = NoteForm() return render(request, 'tracker/noteform.html', {'form': form}) models.py class Note(models.Model): record = models.ForeignKey(Record, on_delete=models.CASCADE) note_text = models.CharField('Notes', max_length=2000) note_date = models.DateField('Date Entered') forms.py class NoteForm(forms.Form): class Meta: model = Note fields = ['note_text', 'note_date' ] template (noteform.html) <form action="/tracker/newnote/" method="post"> <div id="fields"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </div> </form> One other note, I have commented out the div id called "fields", to rule out CSS as the issue. -
Reverse Language Translation in Django
I'm building an API using Django Rest Framework that needs to support multiple languages, we're trying to use the Django translation framework, and using the answer from here I've decided how to implement translatable choicefields. However my issue is for the reverse case. Say I have a model like this: from django.utils.translation import ugettext_lazy as _ class Payment(models.Model): OPEN = 0 CLOSED = 1 BALANCE = 2 STATUS_CHOICES = ( (OPEN, _('open')), (CLOSED, _('closed')), (BALANCE, _('balance')), ) status = models.IntegerField(choices=STATUS_CHOICES, default=OPEN, verbose_name=_("Status")) This works fine for returning the information to the user, we use the stored status value and translate it before returning. However, I also want the user to be able to POST a new payment object using any language. So if the user wants to create an open transaction, they can send {'status':'open'} but they can also send it in Spanish as {'status':'abierto'}. Is there a way to handle this automatically? Basically I want to get the reverse of the ugettext_lazy function. -
styling django-userena templates
I have installed django-userena to manage profiles and accounts on my django app. It seems it is not fully configured and I am still working on. One of the problems that I am trying to solve is to figure out how to style the templates. For instance, this is the address for login on a development server: http://127.0.0.1:8000/accounts/signin/ and here is the sign in page, so my question is: How can I style the templates? It seems the templates should be styled by twitter bootstrap or maybe there are some css files that I can place them in my css folder? -
Django, upload image error
In my aplication, the users can change their profile data, like full name, gender, profile image and other stuff. The problem is when the user want to keep the same profile picture and the file input is empty. How do I support that in my view. Here is my html updateProfile.html <form action="{% url 'updateprofile' %}" enctype="multipart/form-data" method="POST">{% csrf_token %} <input type="file" id="logofile" name="avatar" accept="image/gif, image/jpeg, image/png" value=""> <input type="text"name="full_name"> <input type="date"name="birthdate"> </form> Here is my views.py updateprofile def updateprofile(request): #HERE IS WHERE I CHECK IF I CHANGE THE IMAGE OR NOT BUT THIS NOT WORKS IF THE FILE INPUT IS EMPTY if request.FILES['avatar']: avatar = request.FILES['avatar'] full_name=request.POST['full_name'] birth_date= request.POST['birthdate'] c = user.objects.get(id=request.session['account_id']) c.full_name = full_name c.avatar = avatar c.save() return redirect('userprofile') If I change the file in the file input everything works well. But If I don't upload a new Image and leave the file input in blank I have an error. How do I check if there is file or not in the POST request? please help -
how to filter search on contenttype in django
I have a listapiview, and I want to search in a model object. Say the model is ContentTypeObj and there are 3 models limit to it. The 3 other models have a GenericRelation to it. I am trying to perform a search on the ContentTypeObj. So far it is returning me everything. the search api class ContentTypeObjAPIView(ListCacheResponseMixin, generics.ListAPIView): serializer_class = ContentTypeObjSerializer permission_classes = (AllowAny,) pagination_class = SmallResultsSetPagination list_cache_key_func = ListKeyConstructor() filter_backends = ( DjangoFilterBackend) filter_fields = ('object_ct__genrelation') search_fields = ("object_ct__genrelation__location__city_city") def get_queryset(self): queryset = ContentTypeObj.objects.all().order_by('-time_stamp') return queryset ContentTypeObj model class ContentTypeObj (models.Model): object_ct = models.ForeignKey(ContentType, related_name='explore_objects', verbose_name='Object type',limit_choices_to={'model__in': ('model1', 'model2', 'model3')}) object_id = models.PositiveIntegerField(db_index=True, verbose_name='Object ID') obj = GenericForeignKey('object_ct', 'object_id') owner = models.ForeignKey(User, related_name='explore_objects') time_stamp = models.DateTimeField(verbose_name='Timestamp') and the models would have an extra field for the GenericRelation. class Model1(models.Model): ... genrelation = GenericRelation(ContentTypeObj) class Model2(models.Model): ... genrelation = GenericRelation(ContentTypeObj) -
Django admin linking me to a template
When programming locally on my development server, the site is functioning as expected. But when I go to my production site, a handful of the links in mysite.com/admin link me to a random template that's extending my base.html, rather than the typical database/form UI. For example, I expect this: But instead, I am getting: Any help would be great. -
Set a time for when object to be posted in Django admin?
I want to implement a feature where you can select a date for when a post can go public in the Django admin. Is there a way we can set this in Django? What's the best practice to do this? -
Error on inspectdb model creation django
I am using django with mssql. I already have a existing database and want to create django model for the tables in that database. I followed this django book instruction for inspectdb. http://django-book.readthedocs.io/en/latest/chapter18.html When i enter the command python manage.py inspectdb > interface/models.py I get following error Traceback (most recent call last): File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 547, i n _execute_command recordset = self.cmd.Execute() File "<COMObject ADODB.Command>", line 3, in Execute File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\win32com\client\dynamic.py", line 28 7, in _ApplyTypes_ result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft SQL Server Native C lient 11.0', "Invalid object name 'Attribute'.", None, 0, -2147217865), None) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 6 2, in execute return self.cursor.execute(sql) File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 647, i n execute self._execute_command() File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 558, i n _execute_command self._raiseCursorError(klass, _message) File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 488, i n _raiseCursorError eh(self.connection, self, errorclass, errorvalue) File "C:\Users\Suman Nepal\Anaconda3\lib\site-packages\sqlserver_ado\dbapi.py", line 103, i n standardErrorHandler raise errorclass(errorvalue) sqlserver_ado.dbapi.DatabaseError: (-2147352567, 'Exception occurred.', (0, 'Microsoft SQL Se rver Native Client 11.0', "Invalid object name 'Attribute'.", None, 0, -2147217865), None) Command: SELECT * FROM [Attribute] where 1=0 Parameters: … -
'Welcome' message from Nginx shown when I run my wsgi Django project + Nginx + Gunicorn
I'm beginner in Django and I've finished my first project. I have an Ubuntu server in Digital Ocean and this is what I've done: My project nginx configuration file: server { server_name domain.com; access_log off; location /static/ { alias /opt/myenv/static/; } location / { proxy_pass http://127.0.0.1:8001; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } My project is located in /opt/myenv/myenv/ When I execute gunicorn myproject.wsgi it looks like it's running Listening at: http://127.0.0.1:8000 (1481) But when I access into my IP, I just see an Welcome message from Nginx. What is happening? (Sorry my bad english) -
How to filter a QuerySet to max members of each group in django?
The model is something like this: class Application(models.Model): application_id = models.IntegerField() version_id = models.IntegerField() # some other attributes where application_id and version_id together determine an Application entry, in that one application may have several versions, and an entry with the largest version_id is the application's current version. And the goal is to find the current versions of all applications. The SQL (in MySQL) is something like: SELECT * FROM application AS app WHERE version_id = (SELECT max(version_id) FROM application WHERE application_id = app.application_id); How to achieve this? Please note that the object here is to filter the QuerySet, rather than only fetching the largest version_id, which would be as simple as using a GROUP BY, or in django a values() followed by an annotate(). I'm interested in the other attributes of the current version as well. -
Is it possible to do arithmetic operation on OuterRef expression?
I'm building an Experience booking system in django and I've the following models. class Experience(models.Model): name = models.CharField(max_length=20) capacity = models.IntegerField() class Booking(models.Model): experience = models.ForeignKey(Experience) occupied = models.IntegerField() Each experience has a limited number of capacity and when user perform booking, it will be added to the Booking table with occupied number. Now how will I find the experiences which are not occupied completely? available_experiences = Experience.objects.all().exclude(id__in=Subquery(Booking.objects.filter(occupied__gt=OuterRef('capacity') - request_persons).values_list('experience', flat=True))) Here, request_persons is the number of required vacancy in an experience. This is not working and showing an error like 'ResolvedOuterRef' object has no attribute 'relabeled_clone'. Is it possible to do arithmetic operation on OutRef() expression like F()? Without adding request_persons, the above code works. Why it is not possible to add a value to the OutRef() expression? NOTE: My actual code is much complex one and it will be really great to get an answer without modifying the entire structure of the above code. -
Django 1.11: Issues with utf8 writing to file on windows
I am trying to write some text into a file with data from django objects (CharField) and some formatting. The problem is with accentuated characters (é in the example below). On Linux I have no problems. However, on windows 7, I am getting extremely confusing behaviours. This (open call without encoding): from usermod.models import User user = User.objects.get(pk=134) with open('test.txt', 'w') as fout: fout.write(user.birth_place + ',') fout.write('Séoul') fout.close() produces: SxE9l,Séoul while this (open call with encoding): from usermod.models import User user = User.objects.get(pk=134) with open('test.txt', 'w', encoding='utf8') as fout: fout.write(user.birth_place + ',') fout.write('Séoul') fout.close() which produces: Séoul,Séoul Of course, the expected result is: Séoul,Séoul and this is what I get on Linux with the same database. So the weird thing is that each of those options gets different parts right and wrong. In one case the ORM retrieved value is wrong. In the other it is the string object created in the source code that is wrong. I can't find a way to get both right. All the files are encoded in UTF8 (as reported by notepad++). The python version is 3.5.4 The MySql database has all encodings in UTF8 and an SQL query on the user table shows the … -
settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details
Had a problem running locally project! Maybe problem with virtual environment? settings.py: import os import dj_database_url INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap_pagination', 'main', ] if os.environ.get('DEBUG', False): INSTALLED_APPS += ['django_extensions'] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'main.middleware.DeviceAuthMiddleware', ] WSGI_APPLICATION = 'cl.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases if os.environ.get('DEBUG', False): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } else: DATABASES = { 'default': dj_database_url.config(), } PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) DATAMUSE_URL = 'https://api.datamuse.com/words?sp=' I got the error message when trying to python manage.py runserver or python manage.py migrate. Here is the screen for the error: -
Django page for selecting model instances and adding them to a list
I am a beginner with Django, and my JS/HTML/CSS knowledge is intermediate. I have two models defined in models.py: One model Product that has some basic descriptive Fields (name, description, ...), and another model Category, that has a ManyToManyField products. I want to build a page where a user can select Products with checkboxes, and then add them to a category by pressing an "Add" button. Upon pressing, what should basically happen is: category.products.extend( selected_products ) # This only so that I know to which category a product has been assigned, not too urgent for product in selected_products: product.categories.append(category) Here is an image of what sort of page I am aiming for: https://i.imgur.com/BWs0eV0.png I am not asking for a full working example (unless there already happens to be one available of course). All I am looking for is some pointers on how to proceed creating this. I know how to create the list and the sidebar, but combining this with buttons per list element is new to me. Should the proposed page be essentially 1 giant form, and should I define it in forms.py? Should I be using the Django CheckboxInput widget? Is there a recommended structure for this type … -
Django Tutorial Help - "Not Found: /polls/index.html"
Working through the Django tutorial and have run into a problem I cannot figure out. Help would be appreciated. What am I missing here? Run this the tutorial a couple times now double checking all work, and code seems to match. Error: "Not Found: /polls/index.html" mysite/urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^polls/', include('polls.urls')), ] polls/templates/polls/index.html: {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} polls/urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), # ex: /polls/5/ url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), # ex: /polls/5/results/ url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'), # ex: /polls/5/vote/ url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ] polls/views.py: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render # Create your views here. from django.http import HttpResponse from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request)) def index(request): return HttpResponse("Hello, world. You're at the polls index.") def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're … -
ProgrammingError at / relation does not exist
I can not find answer in other places. (Sorry for asking again but) what is wrong? Did anyone have such an error? ProgrammingError at /register/ relation "user_user" does not exist LINE 1: SELECT (1) AS "a" FROM "user_user" WHERE "user_user"."userna... I extended user abstract model and error saying no relation When i extend user in sqlite3 no errors such this but postgre is full databse error class User(AbstractUser): social_username = models.CharField(max_length=100, null=True, blank=True) views.py def registration(request): if request.method == 'POST': form = RegisterUserForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) messages.success(request,'You were successfully registered %s' % user.first_name) return HttpResponseRedirect('/') messages.error(request, 'Something went wrong while authenticating') return render(request, 'project/register.html', {'form': form}) else: form = RegisterUserForm() return render(request, 'project/register.html', {'form': form}) settings.py AUTH_USER_MODEL = 'user.User'