Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django allauth invalid token error not showing
I'm using allauth for authentication in my Django project. In PasswordResetFromKeyView, I can't figure out why there is not error showing when the password reset token is invalid, for whatever reason. Instead, the token is caught as invalid but the page simply reloads without any message to the user. allauth.account.views.PasswordResetFromKeyView class PasswordResetFromKeyView(AjaxCapableProcessFormViewMixin, FormView): template_name = ( "account/password_reset_from_key." + app_settings.TEMPLATE_EXTENSION) form_class = ResetPasswordKeyForm success_url = reverse_lazy("account_reset_password_from_key_done") def get_form_class(self): return get_form_class(app_settings.FORMS, 'reset_password_from_key', self.form_class) def dispatch(self, request, uidb36, key, **kwargs): self.request = request self.key = key if self.key == INTERNAL_RESET_URL_KEY: self.key = self.request.session.get(INTERNAL_RESET_SESSION_KEY, '') # (Ab)using forms here to be able to handle errors in XHR #890 token_form = UserTokenForm( data={'uidb36': uidb36, 'key': self.key}) if token_form.is_valid(): self.reset_user = token_form.reset_user return super(PasswordResetFromKeyView, self).dispatch(request, uidb36, self.key, **kwargs) else: token_form = UserTokenForm( data={'uidb36': uidb36, 'key': self.key}) if token_form.is_valid(): # Store the key in the session and redirect to the # password reset form at a URL without the key. That # avoids the possibility of leaking the key in the # HTTP Referer header. self.request.session[INTERNAL_RESET_SESSION_KEY] = self.key redirect_url = self.request.path.replace( self.key, INTERNAL_RESET_URL_KEY) return redirect(redirect_url) self.reset_user = None response = self.render_to_response( self.get_context_data(token_fail=True) ) return _ajax_response(self.request, response, form=token_form) def get_context_data(self, **kwargs): ret = super(PasswordResetFromKeyView, self).get_context_data(**kwargs) ret['action_url'] = reverse( … -
Tags know as string in template
I use nicedit for admin site. It save data with tags, as below: admin page I expect it render HTML tags in page but it display string instead, as image below: tag show is string Please help me with this issue. -
Send csv file data to sqlite table in django
Model.py class Tag(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, unique=True) def __str__(self): return self.name class Question(models.Model): name = models.CharField(max_length=255, unique=True) Tag_name = models.ManyToManyField(Tag) I need to create an API for onboarding the data in the csv into the tables. -
Unable to load a pandas dataframe having a JSON column into mysql database
I have a pandas dataframe that looks like this when I print it out in the terminal in pycharm. This is inside a django project exception recommendation time_dimension_id 0 {'exception': []} 0 217 1 {'exception': []} 0 218 2 {'exception': []} 0 219 3 {'exception': []} 546 220 4 {'exception': []} 2876 221 5 {'exception': []} 7855 222 6 {'exception': [{'error': '', 'fatal': 'com.mat... 5041 223 7 {'exception': []} 57 224 8 {'exception': []} 0 225 9 {'exception': []} 0 226 10 {'exception': []} 0 227 11 {'exception': []} 108 228 12 {'exception': []} 0 229 13 {'exception': []} 12 230 14 {'exception': []} 0 231 15 {'exception': []} 0 232 16 {'exception': []} 0 233 17 {'exception': []} 0 234 18 {'exception': []} 0 235 19 {'exception': []} 0 236 20 {'exception': []} 0 237 21 {'exception': []} 0 238 22 {'exception': []} 0 239 23 {'exception': []} 0 240 I tried to insert this dataframe into a table using the below code. connection = engine.connect() df.to_sql('table_name', con=connection, if_exists='append', index=False) Then, I got the below error graphql.error.located_error.GraphQLLocatedError: (MySQLdb._exceptions.OperationalError) (3140, 'Invalid JSON text: "Missing a name for object member." at position 1 in value for column \'fact_exception.exception\'.') [SQL: 'INSERT INTO … -
python cdll does not working on production
i work with python CTypes libary (in django project), when i run the application with pycharm - all is ok, but i'v been deployed project on Windows - IIS Manager. The libary doesnt workin. and says : "[WinError 250477278] Windows Error 0x%X" I thinking it's a trouble with server level. My project config similar to this tutorial : https://www.mattwoodward.com/2016/07/23/running-a-django-application-on-windows-server-2012-with-iis/ how i may fix this bug? -
how can I fix this issue: Provide a one-off default now?
You are trying to add the field 'post_date' with 'auto_now_add=True' to userasking without a default; the database needs something to populate existing rows. 1) Provide a one-off default now (will be set on all existing rows) 2) Quit, and let me add a default in models.py Select an option: in this code I try to set the date field and i find this error. when i do a search about this issue i find that i need to set the default and i set: from django.utils import timezone post_date = models.DateField(auto_now_add=True, default=timezone.now()) when I set default i get this error: WARNINGS: community.UserAsking.post_date: (fields.W161) Fixed default value provided. HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If y ou want to have the current date as default, use `django.utils.timezone.now` how can I skip this issue and migrate successfull models.py class UserAsking(models.Model): userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=False, help_text='Be specific and imagine you’re asking a question to another person') question = models.TextField(max_length=500, blank=False, help_text='Include all the information someone would need to answer your question') field = models.CharField(max_length=20, choices=CHOICE, default='Technology', help_text='Add the field to … -
Set custom error messages in Django 3 ModelForm in default pop-out window
I'm new in Django3 and now I got a task to create custom error-messages text in default pop-out window of ModelForm. This window: default pop-out window, when I press submit button Models.py class Application_form_model(models.Model): user_name = models.CharField( max_length=30, null=True ) Forms.py class ApplicationForm(forms.ModelForm): class Meta: model = Application_form_model fields = ( 'user_name', ) widgets = { 'user_name': TextInput( attrs={ 'placeholder': 'Введіть ім\'я' }, ), } error_messages = { 'user_name': { 'required': _("Custom error message."), }, } views.py def app_form(request): formset = ApplicationForm(request.POST) if formset.is_valid(): save_data = Application_form_model( user_name=formset.cleaned_data['user_name'], ) save_data.save() return HttpResponseRedirect('') return render( request, 'application_form/application_form.html', { 'formset': formset } ) -
Within a formset loop how do i render additional objects coming from a seperate yet related list object?
My problem is this: I have a formset in which each form is used to answer one question. Next to the form i need to be able to show the question text itself. Also, this questionnaire is being filled in and submitted multiple times a year by the user (its a review about colleagues) and because of that i also want to show a list of previous answers the user made for a particular question. The problem is however, in the template i cannot reference any of these additional lists via the index. What i mean is: I can't make a statement like this {{ list[0].property }} in the view. What would be the best way to add information like question text and previous answers to a formset? Is there a way to add meta information to each form within a formset? -
python manage.py migrate does not create a table
I use postgresql and my python version is 3.7 I have tried all the commands python manage.py makemigrations This creates a file in migrations named 0001_initial.py # Generated by Django 2.2.10 on 2020-02-17 12:01 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Support', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=40)), ('email', models.EmailField(max_length=254)), ('message', models.TextField()), ], ), ] now when I pass the command to migrate, python manage.py migrate It shows that 'No migrations to apply' (myvenv) C:\nid\project>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, scholarship, sessions Running migrations: No migrations to apply. This is my models.py class: from django.db import models from django.utils import timezone # Create your models here. class Support(models.Model): name = models.CharField(max_length=40) email = models.EmailField() message = models.TextField() def __str__(self): return self.name I know that this question has been asked before. I checked them all but no answer is able to solve this problem. Please help -
Autocomplete in Django from 2 different models
I designed the following search bar: And I started reading about a solution found here: https://stackoverflow.com/a/50613330/12323384 But what i want, is to be able to make the search bar look from 2 different models: Model1.objects.all() and Model2.objects.all() and when the user starts typing keywords, both results are being shown and the type is displayed next to the result (like Model1 or Model2). Kind of like when you are searching on LinkedIn and it displays the suggestions with their categories (People, Companies, etc...) Any idea on how to achieve that using one view and in the same search bar? -
Page Not Found Error trying to render form in django
I've been following the instructions here. This is the error it gives me, when i try to run it on localhost: Page not found (404) Request Method: GET Request URL: http://localhost:7000/account.html Using the URLconf defined in gettingstarted.urls, Django tried these URL patterns, in this order: [name='index'] [name='account'] db/ [name='db'] admin/ ^celery-progress/ The current path, account.html, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. This is what i have in my urls.py urlpatterns = [ path("", hello.views.index, name="index"), path("", hello.views.account, name="account"), path("db/", hello.views.db, name="db"), path("admin/", admin.site.urls), re_path(r'^celery-progress/', include('celery_progress.urls')) ] This is what i have in views.py def account(request): if request.method == 'POST': form = AccountForm(request.POST) if form.is_valid(): return HttpResponseRedirect('loading.html') else: form = Nameform() return render(request, 'account.html', {'form': form}) Finally this is the form itself(account.html): <form action="/account/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> I have the feeling i'm missing something really simple but i can't for the life of me see it. Any help would be greatly appreciated. -
Django, how to save User and model extended from User in 1 form?
I'm very new to Django so likely I'm missing something obvious here. I have a model 'Profile' that extends form Django's User model. This model is for storing extra settings for the user which should be decided when registering. So I have a register form that I want to use to save a User and a Profile. Currently the User is created and the User's Profile is created but the Profile is not populated with the POST data in the registration form. I'm using signals but I must be missing a crucial component somewhere. models.py class Profile(models.Model): BUTTON_SIZES = ( ('S', 'Small'), ('M', 'Medium'), ('L', 'Large'), ) COLOUR_OPTIONS = ( ('Def', 'Default'), ('Con', 'High Contrast'), ('Pro', 'Protanopia'), ('Deu', 'Deuteranopia'), ('Tri', 'Tritanopia'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) teacher = models.BooleanField(default=False) button_size = models.CharField(max_length=1, choices=BUTTON_SIZES) colours = models.CharField(max_length=3, choices=COLOUR_OPTIONS) group = models.ForeignKey(Class, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return f'{self.user.username} Profile' forms.py class UserRegisterForm(UserCreationForm): BUTTON_SIZES = ( ('S', 'Small'), ('M', 'Medium'), ('L', 'Large'), ) COLOUR_OPTIONS = ( ('Def', 'Default'), ('Con', 'High Contrast'), ('Pro', 'Protanopia'), ('Deu', 'Deuteranopia'), ('Tri', 'Tritanopia'), ) button_size = forms.ChoiceField(choices=BUTTON_SIZES) teacher = forms.BooleanField(required=False) colours = forms.ChoiceField(choices=COLOUR_OPTIONS) # added to UserRegisterForm after creating Class model group = forms.ModelChoiceField(queryset=Class.objects.all(),required=False) class Meta: model = … -
obj.save() reverts changes in Django
I have a model like: class product(): title = models.CharField("name", max_length=20) exist_flag = models.BooleanField('flag', default=True) in a view I use this function: def my_view(product): print(product.exist_flag) product.exist_flag = False print(product.exist_flag) product.save(['exist_flag']) print(product.exist_flag) it prints: True False True why obj.save() reverts the exist_flag field? how can I fix it to save correctly? -
Please guide how to use pk_of_user_without_token in django rest_framework. I am getting error in using this
from django.contrib.auth.models import User from rest_framework.authtoken.models import Token user = User.objects.get(pk=pk_of_user_without_token) Image clearly showing code and error -
Saving multiple instances of the form in django
Unable to store multiple instances of the form in Django after submitting automatically redirect to success URL that is home.html I wanted to build signup form that consists of three forms first form is basic login info, second form can have multiple instances of the single form where user can add more form or remove it. and third form if nested from where user also can add from or remove it. all these in under single submit button. I'm doing right or is there any proper solution or method for that. The first Form that is sign up for user is submitted successfully but the second form(vendor material) is not getting saved third form I'm working on it view.py class VendorSingUp2(View): VendorMaterialSet = formset_factory(VendorMaterialForm) template_name = "singup2.html" def get(self, request, *args, **kwargs): context = { 'vendormaterials': self.VendorMaterialSet(), 'vendor': VendorSignUpForm() } return render(request, self.template_name, context) def post(self, request, *args, **kwargs): vendor = VendorSignUpForm(self.request.POST) vendormaterials = self.VendorMaterialSet(self.request.POST) if vendor.is_valid() & vendormaterials.is_valid(): self.user = vendor.save() self.vendordata = Vendor.objects.get(user=self.user) for vm in vendormaterials: vm.instance = self.vendordata vm.save() print("success") return redirect('home') else: print("invalid") return render(request, self.template_name, {'vendor': vendor, 'vendormaterials': self.VendorMaterialSet(self.request.POST)}) signup2.html {% extends 'base.html' %} {% load static %} {% block content %} <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> … -
How to migrate django app without specifying each app name?
I am migrating django model by using makemigrations. Ex :- python manage.py makemigrations But it is not migrating some apps. Ex:- app1, app2 etc. Ex :- python manage.py makemigrations app1 Now, I want to migrate all apps without specifying each app name. i.e when i run command python manage.py makemigration, then i need to migrate all the apps. I have already specified all apps in settings.py INSTALLED_APPS. -
How to timeout a connection after certain time period, say 15s is over
I am trying to implement a connection timeout for any connection that exceeds 15s even if the connection is active. We are facing an issue with multipart image upload where some image randomly takes over a minute to upload, sometimes a couple of minutes. The same image takes less than a second to upload in the subsequent requests. We are uploading the image from an IoT device. As we have limited access to the device, we are unable to implement the timeout on the device end, and therefore have to do it at the server-side. I am using Nginx, gunicorn and django. Also, I have already tried implementing these settings: For nginx : #To have them timeout after just 1s keepalive_timeout 1; proxy_connect_timeout 1; proxy_send_timeout 1; proxy_read_timeout 1; send_timeout 1; For Gunicorn : --timeout 1 With these settings, I expected to close any connection that went over 1s. However, the request is completing even if it takes 5 mins. Going through the internet, I could only find answers and tutorials for increasing the timeout, with these same settings, so I thought the reverse was also true. Seems like that is not the case. Can anyone help me with this? -
How to declare a time-based alphanumerical id field with predefined aplphabetic part (Django model)
I am developing an app in Django. I wanted to insert in my model an auto-incrementing alphanumerical unique ID field, having, by default, a fixed alphabetical part and an auto-incrementing numerical part. But I also want the availability to change, from admin section, this id to another alphanumerical one, with a different alphanumerical and numerical part. I tryed to implement this, but it turned out that trying to implement such a field and making it the autofield of the model generates problems in my database. So I am changing my aim: now I want to implement a time-based alphanumerical unique field with predefined aplphabetic part. Please note: I don't want to overwrite the django default id field, I just want to include in my model a field that gets as default value a unique customized alphanumerical value. Here is what I did, in my models.py: def return_timestamped_id(): prefix = "ITCH" import time this_time = time.time() this_time = this_time *10000000 this_time = int(this_time) timestamp = str(this_time) default_value = prefix + timestamp return(default_value) class object_example(models.Model): name = models.CharField(max_length=256, blank=True, null=True) Id_generated = models.CharField(max_length=256, blank=False, null=False, unique=True, default=return_timestamped_id()) The problem is that, as I add objects to this model from the admin section, … -
How to add/push data if we have EmbeddedField without using admin page(i.e using python code)
How to add/push data if we have embedded-field without using admin page(i.e using python code) -
NoReverseMatch at ...... in django
I am working on a blog site where you can search for posts by using searching with keywords (basically a normal searchbar). I have imported Q from django.db.models The view I created: def search(request): queryset = Article.objects.all() query = request.GET.get('q') if query: queryset = queryset.filter( Q(title__icontains=query) | Q(overview__icontains=query) ).distinct() context = { 'queryset': queryset, } return render(request, 'search_results.html', context) The urlpattern: path('search/', search, name='search-results'), The form itself: <form action="{% url 'search' %}" class="search-form">{% csrf_token %} <button type="submit" class="submit"><i class="icon-search"></i></button> <div class="form-group"> <span class="icon icon-search"></span> <input type="text" class="form-control" name="q" placeholder="Type a keyword and hit enter"> </div> </form> When I want to access the page to which I have put this form in, it says: Reverse for 'search' not found. 'search' is not a valid view function or pattern name. Below it also shows this: 1 <!DOCTYPE html> 2 <html lang="en"> 3 4 {% include 'head.html' %} 5 6 <body> 7 8 {% include 'header.html' %} 9 10 {% block content %} I have tried adding/removing csrf_token and the submit button, but the result is always the same. Please help! -
Django Create Class From Multiple Functions
I have several functions in my utils.py file that my views use to calculate trade stats. Below I added just 3 but there are 8 and soon there will be several more. The way I currently have it set up works but it's very inefficient. You can see each function starts from the beginning and calls other functions that set similar variables. What is the proper way to turn this into a class? Is this even the right approach? utils.py | multiple functions def max_amount_function (pk): trade = get_object_or_404(Trade, pk=pk) entries_buy = Entry.objects.filter(trade=trade, entry_type="entry") max_amount_function = entries_buy.aggregate(max_amount_function=Sum('amount'))['max_amount_function'] if max_amount_function is None: return 0 else: return max_amount_function def fees_function (pk): trade = get_object_or_404(Trade, pk=pk) entries = Entry.objects.filter(trade=trade) fees_function = entries.aggregate(fees_function=Sum('fee'))['fees_function'] return fees_function def entry_cpu_function (pk): if max_amount_function(pk) > 0: trade = get_object_or_404(Trade, pk=pk) entries_buy = Entry.objects.filter(trade=trade, entry_type="entry") entry_cpu_function = entries_buy.annotate( s=F('amount') * F('price') ).aggregate( entry_cpu_function=ExpressionWrapper( Sum( Cast('s', output_field=models.FloatField()) ) / Sum('amount'), output_field=models.FloatField() ) )['entry_cpu_function'] return entry_cpu_function else: return 0 utils.py | one class class TradeStats: trade = get_object_or_404(Trade) entries_buy = Entry.objects.filter(trade=trade, entry_type="entry") def __init__(self): pass def max_amount_functio(pk): pass def fees_function(pk): pass def entry_cpu_function(self): pass -
Custom plugin TextField Django CMS
I am trying to implement my custom CMS plugin with a TextField and would like to have all the text styling options provided by the CKEditor but when I add a TextField or CharField in my models it creates a simple text input field. class Something(CMSPlugin): text = models.TextField(max_length=512) image = models.ImageField() Anybody an idea what I have to add so the styling options for text are available in the frontend editor? Also thought about overriding one of the existing Plugins but this doesnt seem to be the right path. -
How to use Django "empty_forms" correctly to dynamically add new formsets : Select Widget's failure
I am using Django modelformset_factory for one of my models where I am creating a number records in a single page. Two of the form fields are select widgets and the rest of the fields are simple text/number inputs. With the initial number of rows the records get created perfectly. To add extra rows dynamically I have adapted the solution from here. New rows of empty forms are getting generated as expected. However, when a new row is added, the select boxes are generating a list of FK (available) choices, instead of drop downs which are otherwise being generated for the original set of forms. On changing the .Select widget to a .TextInput, the dynamically added rows display now such issue (and I can create new records using the formsets, including, using those added dynamically by manually inputting the values for the fields). My question is: What could make the select widgets to fail as they exhibit here? Note: Images added to demonstrate what exactly is happening. Original Rows New Rows Added (The highlighted object is the FK field value which is getting displayed here, instead of a .Select widget!!) -
How to execute psql interactive in its docker container?
I want to run a query in Postgres interactive shell. I'm using a docker container for this purpose as the following: Here is the relevant piece of docker-compose: db_of_ivms: image: postgres:10 restart: unless-stopped ports: - 5432:5432 container_name: db_of_ivms environment: POSTGRES_PASSWORD: xxx POSTGRES_USER: ivms_usr POSTGRES_DB: ivms_db Nevertheless, I'm dealing with this error: docker exec -it -u 0 db_of_ivms bash # psql psql: FATAL: role "root" does not exist -
Get the username with django profileserializer
I developed api with django. I created a code structure like below. How do I get the user's first_name and last_name in class ProfileSerializer? that is, with ProfileSerializer, I want to get information such as the user's name, surname, id number `` from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password from rest_framework.serializers import ModelSerializer, Serializer from rest_framework import serializers from account.models import Profile class ProfileSerializer(ModelSerializer): class Meta: model = Profile fields = ('id', 'userKey', 'phone', 'email', 'address', 'userState') class UserSerializer(ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ('id', 'first_name', 'last_name', 'profile') def update(self, instance, validated_data): profile = validated_data.pop('profile') profile_serializer = ProfileSerializer(instance=instance.profile, data=profile) profile_serializer.is_valid(raise_exception=True) profile_serializer.save() return super(UserSerializer, self).update(instance, validated_data) ``