Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: dropdown selecting a model in a generic view
I have a generic Django generic DetailView and I'd like to be able to render a dropdown via a django.form. The options are a list of objects that belong to the user. I can do this for ALL objects with something like Model.objects.all() in the form, but how can I filter out the options that belong to the user without being able to access the request.user from the form? I've seen an example where the queryset can be injected into the form: form = MyForm() form['field'].queryset = Model.objects.filter(user=user) But there is no place to really do this in a django generic view (is there?) -
How to complete user (set password) registration with email in django-allauth?
I would like to register the user with some basic info (Name, Company...) and email. After the user submits the form i would like to send an email with a link that takes the user to a page to set his password. I have tried with a solution from this question: Django AllAuth - How to manually send a reset-password email?. The email was send and the link inside the email is working, but i get an AssertionError on my site. The error is in /allauth/account/utils.py inside the setup_user_email(request, user, addresses) function. The line: assert not EmailAddress.objects.filter(user=user).exists() What am i doing wrong here? My models.py: from django.contrib.auth.models import AbstractUser from django.db import models from allauth.account.views import PasswordResetView from django.conf import settings from django.dispatch import receiver from django.http import HttpRequest from django.middleware.csrf import get_token class Kompanija(models.Model): naziv = models.CharField(max_length=50) adresa = models.CharField(max_length=50, blank=True) def __str__(self): return self.naziv class Meta: verbose_name = "Kompanija" verbose_name_plural = "Kompanije" class CustomUser(AbstractUser): ime = models.CharField(max_length=30, default='') prezime = models.CharField(max_length=30, default='') kompanija = models.ForeignKey(Kompanija, on_delete=models.CASCADE, null=True, blank=True) is_premium = models.BooleanField('premium status', default=False) def __str__(self): return self.ime + " " + self.prezime @receiver(models.signals.post_save, sender=settings.AUTH_USER_MODEL) def send_reset_password_email(sender, instance, created, **kwargs): if created: request = HttpRequest() request.method = 'POST' if … -
NoReverseMatch at /^users/login/ (Reverse for 'index' not found. 'index' is not a valid view function or pattern name.)
I set up a user registtation and authorization system to allow people to register an account and log in and out. the first error is about TypeError: login() got an unexpected keyword argument 'template_name', I fixed it ,but the second problem arises.like this: NoReverseMatch at /^users/login/ Reverse for 'index' not found. 'index' is not a valid view function or pattern name. Request Method: GET Request URL: http://localhost:8000/%5Eusers/login/ Django Version: 2.2.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'index' not found. 'index' is not a valid view function or pattern name. Exception Location: D:\learning-note\ll_env\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 668 Python Executable: D:\learning-note\ll_env\Scripts\python.exe Python Version: 3.7.3 Python Path: ['D:\\learning-note', Error during template rendering In template D:\learning-note\learning_logs\templates\learning_logs\base.html, error at line 2 Reverse for 'index' not found. 'index' is not a valid view function or pattern name. 1 <p> 2 <a href="{% url 'learning_logs:index' %}">Learning Log</a> - 3 <a href="{% url 'learning_logs:topics' %}">Topics</a> - 4 {% if user.is_authenticated %} 5 Hello, {{ user.username }}. 6 {% else %} 7 <a href="{% url 'users:login' %}">log in</a> 8 {% endif %} 9 </p> 10 11 12 learning_log/urls.py from django.contrib import admin from django.urls import path, include urlpatterns =[ path('admin/',admin.site.urls), path(r'^users/', include('users.urls', namespace='users')), path('', include('learning_logs.urls',namespace = 'learning_logs')), ] … -
Django Custom User authentication, lookup error User not registered
After running a migration I get the following error: LookupError: Model 'users.UserProfile' not registered. I am trying to create a customer User for Django-cms. It just does not want to do it. Full Traceback: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\user\Envs\p37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\user\Envs\p37\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\user\Envs\p37\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\user\Envs\p37\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\user\Envs\p37\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\user\Envs\p37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\user\Envs\p37\lib\site-packages\djangocms_text_ckeditor\models.py", line 10, in <module> from cms.models import CMSPlugin File "C:\Users\user\Envs\p37\lib\site-packages\cms\models\__init__.py", line 4, in <module> from .permissionmodels import * # nopyflakes File "C:\Users\user\Envs\p37\lib\site-packages\cms\models\permissionmodels.py", line 21, in <module> User = apps.get_registered_model(user_app_name, user_model_name) File "C:\Users\user\Envs\p37\lib\site-packages\django\apps\registry.py", line 270, in get_registered_model "Model '%s.%s' not registered." % (app_label, model_name)) LookupError: Model 'users.UserProfile' not registered. Models.py file: from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from … -
Postgresql: could not connect to server
I'm use postgresql 9.6, Django 2.0, psycopg2==2.8.3 psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? pg_hba.conf local all postgres peer # TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all peer # IPv4 local connections: host all all 127.0.0.1/32 md5 # IPv6 local connections: host all all ::1/128 md5 # Allow replication connections from localhost, by a user with the # replication privilege. #local replication postgres peer #host replication postgres 127.0.0.1/32 md5 #host replication postgres ::1/128 md5 host all all 0.0.0.0/0 md5 host all all ::/0 md5 status ● postgresql.service - PostgreSQL RDBMS Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled) Active: active (exited) since Mon 2019-08-05 11:52:49 EEST; 19min ago Process: 26617 ExecStart=/bin/true (code=exited, status=0/SUCCESS) Main PID: 26617 (code=exited, status=0/SUCCESS) сер 05 11:52:49 lexvel-MS-7A72 systemd[1]: Starting PostgreSQL RDBMS... сер 05 11:52:49 lexvel-MS-7A72 systemd[1]: Started PostgreSQL RDBMS. settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'keyua_dev', 'USER': 'postgres', 'PASSWORD': '***', 'HOST': '127.0.0.1', 'PORT': '', } } -
Django Selected Radio button choice and dropdown
I have created radio button and dropdown menu populated from the static tuple from the Form. I would like to fetch the item what user selected on the same page below the submitting. FORM.py ## VIEW: Populate dropdown to select Data center def get_role_dc_data(request, *args, **kwargs): if request.method == 'POST': form = SelectionForm(request.POST or None) if form.is_valid(): form.save() return render(request, 'selectsite.html', {'form': form }) else: form = SelectionForm() return render(request, 'selectsite.html', {'form': form }) ## POPULATE: Data def gather_data(request, *args, **kwargs): selectedsite = '' roletype = '' if request.method == 'POST': form = SelectionForm(request.POST or None) if form.is_valid(): selectedsite = form.cleaned_data.get('location') roletype = form.cleaned_data.get('roletype') print (selectedsite) print (region) context_dict = { "selectedsite": selectedsite, "roletype": roletype } else: context_dict = {} return render(request, 'configure.html', context_dict) HTML: <form method="post" action=/configure/> {% csrf_token %} <table class="table"><tr><th> <label name="roletype" for="region" class="form-check-label"> Type: {% for choice in form.roletype %} <name="roletype"> {{ choice }} {% endfor %} </label></th><th> <select name="location"> <datalist id="location">Select an the site</option> {% for dc in form.location %} <option selected="selected" value="{{ dc }}"></option> {% endfor %}</datalist></select></th><th> <button align="right" class="button execute" name="submit" value="submit">GO TO</button> </th></tr></table></form> -
Add a virtual field to a django query
I want to add an extra field to a query set in Django. The field does not exist in the model but I want to add it to the query set. Basically I want to add an extra field called "upcoming" which should return "True" I already tried adding a @property method to my model class. This does not work because apparently django queries access the DB directly. models.py class upcomingActivity(models.Model): title = models.CharField (max_length=150) address = models.CharField (max_length=150) Views.py def get(self, request): query = upcomingActivity.objects.all() feature_collection = serialize('geojson', query , geometry_field='location', fields= ( 'upcoming','title','address','pk' ) ) -
Primary key validation after Django's sqlsequencereset [duplicate]
This question already has an answer here: IntegrityError duplicate key value violates unique constraint - django/postgres 9 answers I've migrated a DB from a Django App from SQLite to Postgres. When I enter new data on the admin view I get an error message that the primary key already exists. duplicate key value violates unique constraint I tried to resync the sequences in postgres using the following command, which generates the required SQL script. python manage.py sqlsequencereset app | python manage.py dbshell I still get the same error as before. How can I check whether the sequence was resynced correctly and the next id is set to MAX(id)+1 or so? -
While creating python file on IIS with django Error 500
When i try to create a python file (.py) in my django application i get an error 500. The File is created and the code isn't the problem. I can create a text file or any other format. It would need to be a python file cause i need it for further steps. I am using Windows 10 and run the django Application on IIS. Windows, IIS and Django are all uptodate. I already tried to add permission to the folder I will edit. I tested around with some other settings but havent figuerd out the problem yet. I think it should be something with permission of the iss or django. This is my error message: d:\django\virtualenv0\scripts\python.exe - The FastCGI process exited unexpectedly Most likely causes: IIS received the request; however, an internal error occurred during the processing of the request. The root cause of this error depends on which module handles the request and what was happening in the worker process when this error occurred. IIS was not able to access the web.config file for the Web site or application. This can occur if the NTFS permissions are set incorrectly. IIS was not able to process configuration for the … -
How to get data by one query
I have two models question and option class Question(AbstractStatusModel): pass class Option(models.Model): option = models.TextField() is_correct = models.BooleanField(default=False) question = models.ForeignKey(Question, on_delete=models.CASCADE) How can I get a question with at least one correct option? -
Is there any support for constraint ON UPDATE in django
In the Django model on the foreign key attribute, I can add on_delete= models.CASCADE constraint but similarly I also need on_update RESTRICT. Is it possible? and is there any source of documentation if available -
How can i set a default value to an OneToOneField relationship which it's automatically generated?
I have two model classes they like below: from django.db import models from django.urls import reverse class Place(models.Model): address = models.CharField(max_length=80) class Author(Place): name = models.CharField(max_length=50) But when i want to execute makemigartions django shows me error below: You are trying to add a non-nullable field 'place_ptr' to author without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: I have some data in Author table but i dont want to remove that data. how can i fix this issue? -
Django Messages are loading only after refresh after ajax call to delete a product from wishlist
In my django oscar project i have a wishlist templte which contains button to delete product from wishlist. The product is getting deleted after ajax call but the success message which is created in deleteview is loading after refreshing page. -
How to substitute a custom user in django?
Could anyone help me? I have been trying for so many days. I have read documentation but not understanding how to add custom user field in User of admin page? Whenever I makemigrations, it gives me following error. Different pages #admin.py from django.contrib.auth.admin import UserAdmin admin.site.register(UserProfile, UserAdmin) #models.py from django.contrib.auth.models import AbstractUser class UserProfile(AbstractUser): Id_card_number = models.CharField(max_length=15) #forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True)._unique = True Id_card_number = forms.CharField(max_length=15, required=True)._unique = True class Meta: model = UserProfile fields = ['username','email','password1','password2','Id_card_number'] Error whenever I use AUTH_USER_MODEL = 'users.UserProfile' in settings.py ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'UserProfile.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'UserProfile.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'UserProfile.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'UserProfile.user_permissions'. users.UserProfile.groups: (fields.E304) Reverse accessor for 'UserProfile.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'UserProfile.groups' or 'User.groups'. users.UserProfile.user_permissions: (fields.E304) Reverse accessor for 'UserProfile.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'UserProfile.user_permissions' or 'User.user_permissions'. Error whenever I don't use AUTH_USER_MODEL = … -
Django test chooses database randomly
I have multiple database settings (master/slave) as follow: DATABASES = { 'default': dj_database_url.parse('postgres://localhost:5432/master_db'), 'slave': dj_database_url.parse('postgres://localhost:5432/slave_db'), } Slave database is only used explicitly for some offline expensive query (with objects.using and is not used any of testcases. As noted in django docs 'default' database is used when there is no database specified explicitly. The problem is when I run python manage.py test --keepdb it sometimes run tests with slave database which raises error (because there is no table created in slave databse). The output of python manage.py test --keepdb when it uses slave: Using existing test database for alias 'slave'... Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "categorization_category" does not exist LINE 1: ...rization_category"."last_modified_date" FROM "categoriz... The output of when it uses default: # some ..... and warnings showing tests are running Creating test database for alias 'default'... # some debug info in tests Destroying test database for alias 'default'... Ran 119 tests in 91.456s OK How can I force test to use only 'default' database as test database? -
expected string or bytes-like object in Django save() method
I have Job Model that I can see list of them, create new one and see details of one of them. But when I want to edit objects of this model, I got this error: match = datetime_re.match(value) TypeError: expected string or bytes-like object And in Traceback this line be come bold: job_resume.save() This is my view: def edit_admin_job_resume(request, id): resume = get_object_or_404(JobRecord, id=id) if request.method == "POST": form = AddAdminJobForm(request.POST, request.FILES,instance=resume) if form.is_valid(): job_resume = form.save(commit=False) job_resume.upload_url = form.cleaned_data['upload_url'] job_resume.time_start = date_picker(date=request.POST['time-start-input']) job_resume.time_end = date_picker(date=request.POST['time-end-input']) job_resume.save() return redirect('administrator:view_admin_job_resume') else: form = AddAdminJobForm(instance=resume) template = 'administrator/resumes/add_edit_resume.html' context = {'form': form} return render(request, template, context) What is wrong with this codes? -
How to calculate unique IP's in Django (1 unique IP per day)?
** I'would like to calculate on many unique IP's have visited a page from my website, with maximum visit per IP per day = 1. ** I have a model with various fields. Two of them are : - date: created_at.strftime("%d-%m-%y, %H:%M") - ip: request_ip A example of these two informations would be : - 2019-07-15 17:43:09 - 127.0.0.1 I tried a combinaisons of various Django's methods like : values, distinct, filter, etc. But I can't get the result I want. Because I cannot change the format of my fields, the distinct method won't work because the date changes every second. It would have been nice to have a date format like ("%d-%m-%y) = without the seconds, minutes and hours. This is why the following example won't work. I have as a result, all the IPs in my database. Example : try: all_views = reward_views.objects.all().order_by('-updated_at') except: return HttpResponse(status=500) ip_number = reward_views.objects.values('request_ip', 'updated_at').distinct().count() So I tried to put the informations, IPs and dates, in lists in order to modify the date format and do better manipulations on it. try: all_views = reward_views.objects.all().order_by('-updated_at') except: return HttpResponse(status=500) all_dates = [] for view in all_views: all_dates.append({ 'reward_creation_date': view.created_at.strftime("%d-%m-%y"), 'user_ip': view.request_ip, }) print (all_dates) But … -
How to turn django's 'rest_framework.utils.serializer_helpers.ReturnList' to dict to compare get and post data with pytest correctly
I am trying to test an API with pytest. My idea is to create data with a post method and then make a get request and compare the created data with the get data. It works fine to post and get the data. Yet I can't compare using django's compare operators because - I think - I get different types back. Here is my test (with lots of print statements to debug) def test_auth_user_can_create_graph(self, client, user): """Test if an authenticated user can create a new graph. """ create_data = graph_data url = api_reverse('create-graph') graph_objects = Graph.objects.count() response = client.post(url, create_data, content_type='application/json') url_get_request = api_reverse('list-graph') response_get = client.get(url_get_request, content_type='application/json') # response_json = json.loads(response_get.data) # print(response_get.get_data(as_text=True)) print(type(response_get.data)) print(type(url_get_request)) print(response_get.data) print(graph_data) assert (response_get.data) == (graph_data) assert response.status_code == 200 The line assert (response_get.data) == (graph_data) throws me an assertion error. I guess that's because my get-data is of type <class 'rest_framework.utils.serializer_helpers.ReturnList'> and graph data is of type <class 'dict'> I tried serializing the get_data with my GraphSerializer. I also tried to dump my data with json.dumps and I tried comparing it turning both into sets. None of it worked for me. Is there a simple way of doing this without any extra dependencies? … -
How to create order in razorpay , And how to pass order_id to template in Django
I have been trying to implement Razorpay standard checkout in Django 2 ! As docs say i have tried to create order in my view.py but its not creating an order and if order is created how do i pass order_id to my template ? if request.method == 'POST': DATA = { 'amount': 50000, 'currency': 'INR', 'receipt': 'order_rcptid_11', 'payment_capture': 0, } client.order.create(data=DATA) -
Keras progress real time output to Django html page
How to show the progress of Keras model training on a Django web application in a real time? Something like this library which solves the problem within jupyter notebook: https://github.com/bstriner/keras-tqdm from keras_tqdm import TQDMNotebookCallback # keras, model definition... model.fit(X_train, Y_train, verbose=0, callbacks=[TQDMNotebookCallback()]) -
Use serializer of model having foreign key to do CRUD on parent table in Django Rest Framework
In my API, I have two models Question and Option as shown below class Question(models.Model): body = models.TextField() class Options(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) option = models.CharField(max_length=100) is_correct = models.SmallIntegerField() While creating a question it would be nicer the options can be created at the same time. And already existed question should not be created but the options can be changed if the options are different from previous. I am using ModelSerializer and ModelViewSet. I use different urls and views for Question and Option. serializers.py class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = '__all__' class OptionReadSerializer(serializers.ModelSerializer): question = QuestionSerializer(read_only=True) class Meta: model = Option fields = ('question', 'option', 'is_correct') class OptionWriteSerializer(serializer.ModelSerializer): class Meta: model = Option fields = ('question', 'option', 'is_correct') views.py class QuestionViewSet(ModelViewSet): seriaizer_class = QuestionSerializer queryset = Question.objects.all() class OptionViewSet(ModelViewSet): queryset = Option.objects.all() def get_serializer_class(self): if self.request.method == 'POST': return OptionWriteSerializer return OptionReadSerializer urls.py from django.urls import include from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('api/question', QuestionViewset, base_name='question') router.register('api/option', OptionViewSet, base_name='option') urlpatterns = [ path('', include(router.urls)) ] In this way, I always have to create questions first and then I can individually add the option for that question. But this is not a practical approach. It would … -
How i Can add my own Models and display them in Oscar Dashboard?
I want to create my own models and theme in Django Oscar, please let me know the process. Where I can add Models in Django Oscar and How I will Display that model in my Django Oscar Dashboard. I am Trying to do this from last 2 days but still did not find ant solution for this. -
check username already exists in django
I am a beginner in django web development.I want to submit a form in django and database used is sqllite.i want to student id in my form already exists in db or not without submitting form.Here i am not using Ajax in it.Can anyone help us? -
ConnectionRefusedError at /password-reset/ [WinError 10061] No connection could be made because the target machine actively refused it
When user enter email for password reset then error arise connection failure which is related to server failure error . -
How to update User model while getting existed info?
There is something wrong with my edit_profile code. I'm using "settings.AUTH_USER_MODEL". When I try to edit profile, it turned out that all the fill box was blank. I want the existing information to be there so the user would be editing their profile easier. Please help me. accounts/models.py class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.DO_NOTHING) first_name = models.CharField(max_length=30,null=True,blank=True) last_name = models.CharField(max_length=30,null=True,blank=True) address_number = models.CharField(max_length=15,null=True,blank=True) road = models.CharField(max_length=30,null=True,blank=True) kwang = models.CharField(max_length=30,null=True,blank=True) ked = models.CharField(max_length=30,null=True,blank=True) province = models.CharField(max_length=30,null=True,blank=True) postal = models.IntegerField(null=True,blank=True) mobile = models.IntegerField(null=True,blank=True) def __str__(self): return str(self.user) accounts/views.py @login_required def profile(request): """Display User Profile""" user = request.user profile = get_object_or_404(UserProfile, user=user) return render(request, 'accounts/profile.html', { 'profile': profile }) @login_required def edit_profile(request,id): user = request.user form = ProfileForm(instance=user) if request.method == 'POST': form = ProfileForm(instance=user, data=request.POST) if form.is_valid(): form.save() messages.success(request, "Updated the Profile Successfully!") return HttpResponseRedirect(reverse('profile')) return render(request, 'accounts/edit_profile.html', { 'form': form })