Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is staff is not updating in Django-allauth custom signup form
i created a custom form from the Django-allauth package adding a first name, Lastname and is_staff. This was after i had extended the user model using abstart user. i think it has something to do with is_staff being a boolean value. All suggestions are welcome. thank you. My user model looks like this from django.contrib.auth.models import AbstractUser, UserManager class CustomUserManager(UserManager): def get_by_natural_key(self, username): case_insensitive_username_field = '{}__iexact'.format(self.model.USERNAME_FIELD) return self.get(**{case_insensitive_username_field: username}) class User(AbstractUser): is_student = models.BooleanField('student status', default=False) location = models.CharField(max_length=30, blank=True) # first_name= models.CharField( blank=False, max_length=30, verbose_name='first name') email = models.EmailField(unique=True) objects = CustomUserManager() My custom form is as shown below from django.contrib.auth.models import User, Group class CustomSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, label='Last Name') is_staff = forms.BooleanField(required=True ,label = 'Are you been assigned as a staff?') def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() return user -
call the model of the secondary database in djnago using Multiple Databases
I am following Django multiple databases. (https://docs.djangoproject.com/en/2.2/topics/db/multi-db/) settings.py DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'database_1', 'USER': 'username_1', 'PASSWORD': 'password_1', 'HOST': 'localhost', 'PORT': 'xxxx', }, 'secondary' : { 'NAME' : 'database_2', 'ENGINE' : 'django.contrib.gis.db.backends.postgis', 'HOST' : 'xx.xx.xx.xx', 'PORT' : 'xxxx', 'USER' : 'username_2', 'PASSWORD' : 'password_2', }, } As the documentation suggests we need to create a router. DATABASE_ROUTERS = ['app_name.router.AuthRouter', ] routers.py class AuthRouter: """ A router to control all database operations on models in the auth and contenttypes applications. """ route_app_labels = {'login','images'} def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return 'database_2' return None def db_for_write(self, model, **hints): """ Attempts to write auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return 'database_2' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth or contenttypes apps is involved. """ if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the auth and contenttypes apps only appear in the 'auth_db' database. """ if app_label in self.route_app_labels: return db == 'database_2' return None I … -
django only getting the first value of the loop
Hello guys so i have this function that get new data and avoid duplicate data of the task manager the problem is that my for loop it only getting the first value and stop there, i maybe know the problem that is maybe the "return" within my for loop is the problem but i don't know how i can fix this. can somebody give me explanation how to fix this? thanks. task = [] request.session['task'] = task id_task = request.GET.getlist('array[]') for data in id_task: if data not in task and task_admin_form.objects.filter(id__exact=data).exists: data_id = task_admin_form.objects.filter(id__exact=data) task.append(data) for task_id in data_id: task_dict = {} task_dict['username'] = task_id.username.username request.session['task_update'] = task_dict print(task_dict) return HttpResponse(json.dumps(task_dict),content_type="application/json") else: data_task_new = request.session.get('task_update') task = request.session.get('task') print(data_task_new) print(task) return HttpResponse(json.dumps(data_task_new),content_type="application/json") -
Get Related Model From Many To Many Through
I am receiving a m2m_changed signal which is passing me the through field of the two models with the m2m relationship. Using this I want to get one of the models it's joining. The through field contains the data: id:3 | model1_id: 5 | model2_id: 9 I figured I could get model1's id using model_id = through_model.model1_id but this just returns through_model's id. I'd then get the object using modules_models.ModulePackage.objects.get(id=model_id). Thank you. -
How to pass an type with python in a stored procedure
i have a legacy datamodel with three schemas. data, view and api. The tables are stored in data, views in views and stored procs in api. Now i want to use django to build an app for it. In the api i have procedures with custom types as arguments to store the data, write the history and take care about user rights and logging. I made a model which is not managed by Django and try to overwrite the save method: from django.db import models from django.db import connection class Mandator(models.Model): mdt_id = models.IntegerField(primary_key=True) mdt_name = models.CharField(max_length=100) mdt_insert_date = models.DateField() mdt_insert_user = models.CharField(max_length=100) mdt_update_date = models.DateField() mdt_update_user = models.CharField(max_length=100) class Meta: managed = False db_table = 'fdb_mandator' def save(self, *args, **kwargs): with connection.cursor() as cursor: cursor.callproc('prc_fdb_mandator_insert',(self)) When i execute the save method, i get the following error: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/*****/Workspaces/FlexDB/flexdb-django/flexdb/fmgr/models/mandator.py", line 18, in save cursor.callproc('prc_fdb_mandator_insert',(self)) File "/home/*****/.local/lib/python3.7/site-packages/django/db/backends/utils.py", line 62, in callproc return self.cursor.callproc(procname, params) TypeError: object of type 'Mandator' has no len() The database is an PostreSQL 12! Did anybody know how i can pass an object type to an stored procedure with python? -
How to make serializer accept a data type, but converts it before save in DRF?
I have the following model and serializer class MyModel(db_models.Model): name = db_models.CharField(max_length=120) description = db_models.CharField(max_length=1024, blank=True) complex_data = db_models.BinaryField(null=True, default=None) class MyModelSerializer(serializers.ModelSerializer): class Meta: model = models.MyModel fields = ( "id", "name", "description", ) I use this serializer for CRUD operations, but for creating or updating, I would like the client to be able to input a "complex_data", which consists of arrays and numerical data, it should be valid for the serializer, but before saving the data, I would like the serializer to convert the the complex_data to bytes format (for that I use msgpack), and save the model object with the converted complex_data. since I only manipulate the complex_data field on create and on update actions, the complex_data should be a write-only field. Thanks in advance -
How to pass Django template variable to JavaScript function
I passed personal information in js file using views.py. So, In the js file, I added the Django template for loop to iterate the personal information and pass the javascript function. but it's not working for me. I am new in this concept. View file def sample(request): p=[] p.append({name:santhosh, age:20},name:kumar, age:21}) return render(request, 'index.js',{'p':p}) index.js {% for i in p %} var data = load_html(i) {% endfor %} function load_html(i){ return '<h1>{{ i.name }}</h1>' } This is my sample code. I tried to pass (i value in load_html()) function. but it cannot pass the value in that function. How to pass value and get name. -
leaflet marker not showing on the map : TypeError t.addLayer
I'm trying to add some markers on my geo-django map using Leaflet. i manage to show the map on the page and i have all my positions on a database list. <div id="travel_map"> {% leaflet_map "location_map" %} <script> var marker = L.marker([51.5, -0.09]).addTo(location_map); {% for place in travels_list %} console.log({{ place.city.position.y }}); L.marker([{{ place.city.position.y }}, {{ place.city.position.x }}]).addTo(location_map).bindPopup('{{place.city.location_name}}'); {% endfor %} </script> </div> When the code run, this is what i get in my html <script> var marker = L.marker([51.5, -0.09]).addTo(location_map); console.log(48.8667); L.marker([48.8667, 2.3333]).addTo(location_map).bindPopup('Paris'); console.log(45.5); L.marker([45.5, -73.5833]).addTo(location_map).bindPopup('Montreal'); </script> But the map doesn't show any marker and i keep getting this error. leaflet.js:5 Uncaught TypeError: t.addLayer is not a function When I log the the y value on the console, it works. What it wrong with the '.addTo()' function? -
Cant show total amount of purchase in my django app
i building a basic ecom site , when i try to make total amount of purchase nothings shows in page, But i can make total of individual items , But can't figure out how to show total amount of the purchases html <h1>Bill Of Purchase</h1> <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">#</th> <th scope="col">Item</th> <th scope="col">Quantity</th> <th scope="col">Cost</th> </tr> </thead> <tbody> {% for obj in item %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{obj.item}}</td> <td>{{obj.quantity}}</td> <td>${{obj.get_total_item_price}}</td> </tr> {% endfor %} <tr> <td>total</td> <td>${{item.get_total}}</td> </tr> </tbody> views.py def bill_page(request): item= BillItem.objects.all() return render(request,'bill.html',{'item':item}) model.py CATEGORY_CHOICES = [ ('U', 'Pulses'), ('O', 'Oil'), ('F', 'Flour'), ('V', 'Vegetable')] class Item(models.Model): name = models.CharField(max_length=100) price = models.FloatField() quantityofproduct = models.IntegerField(blank=True, null=True) quantityAvailable = models.IntegerField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES,max_length=1) CreatedDate = models.DateTimeField(auto_now_add=True) UpdatedDate= models.DateTimeField(blank=True, null=True) def __str__(self): return self.name class BillItem(models.Model): item = models.CharField(max_length=100) quantity = models.IntegerField() price = models.FloatField() def __str__(self): return self.item def get_total_item_price(self): return self.quantity*self.price def get_total(self): total = 0 orderitems = self.orderitem_set.all() total = sum([item.get_total_item_price for item in orderitems]) return total i cant make total amount of purchase , can any one help me.? -
circular import in django framework
I have been trying to run a client-server application using Django. When I am trying to run my server in Django , it is giving me the following error. raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'blog.urls' from 'C:\Users\adimin\projects\Portfolio\blog\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. The project urls.py- django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')) ] The application(blog.urls) from . import views from django.urls import path urlsPatterns = [path('', views.PostList.as_view(), name='home'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), ] App's views.py - from django.views import generic from .models import Post class PostList(generic.ListView): queryset = Post.objects.all() template_name = 'index.html' class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html' kindly ,where am I going wrong? -
Is there a django library to show difference between 2 text files?
I intend to show the difference between 2 texts to user inside my python/django web application like meld or other merge/diff applications: I don't want the full feature to merge, just to show the diff. Is there any python or django library to help me to do that? -
Programmatically create permissions using Django Guardian
I have some Django models structures like so: model A <- 1 to N -> model B model B <- 1 to N -> model C I also have the ability to associated to each user an arbitrary number of instances of A (0 or more) and a certain permission like UPDATE. ------------------------ | user | type | model_a | ------------------------ | Joe | UPDATE | 12 | | Joe | READ | 12 | | ... | ... | ... | ------------------------ Given that, I would like to put together an authorization system that allows me to: Have B and C inherit permissions put together for A (in the example above Joe should be able to read and update A with ID 12 and all associated models B and C) Setup an out of pattern permission (like, Joe can DELETE model C even if he can't read A or B, or Joe cannot READ model_C with id 100) I already have a semi-working solution that works around keeping permissions updated through a django command in the permissions table on the database. I would like this to work more programmatically (all the above logic explained above should be more a … -
Working with UX/UI designers for website development
I'm trying to create a website for my company, I have a UX/UI developer who has created the design already, how can I bring it to life, like a real website using Wordpress or Django? -
How to use pagination nested object serializer - Django rest framework
Look at this picture of me first -> Here I have 2 nested objects - in which I want to add pagination to the array named list. I want to use pagination in the "array" that I have listed here. -
Sorting the django objects based on SerializerMethodField
I am trying to order the user profiles based on the timestamp of the last message in between both the users. I am using SerializerMethodField to get the timestamp of the last message. is there any way I can sort the data? class UserProfileSerializer(serializers.ModelSerializer): lastmessage = serializers.SerializerMethodField() class Meta: model = User fields = ['id','lastmessage'] def get_lastmessage(self,obj): k = self.context.get('view').kwargs['sid'] data =( Message.objects.filter(receiver=obj.id,sender=k) | Message.objects.filter(sender=obj.id,receiver=k)).order_by('-timestamp').values('message','timestamp') if len(data) == 0: return "" else: data = data.first() data["timestamp"] = str(data["timestamp"]) return str(data) Now my views return: [{ "id": 4, "lastmessage": "{'message': 'random', 'timestamp': '2020-06-14 23:49:33.077749+00:00'}" }, { "id": 5, "lastmessage": "" }, { "id": 6, "lastmessage": "{'message': 'sample', 'timestamp': '2020-06-14 11:53:03.880833+00:00'}" }, { "id": 7, "lastmessage": "" }] But I want it to sort based on the timestamp of last message -
How to get sql query for query with Subquery?
I have a query q = Product.objects \ .annotate(t=Subquery(Purchase.objects.filter(user=user))) and when I do print(q.query) I get exseption {FieldError}Cannot resolve expression type, unknown output_field What to do and why they can't resolve expression type? -
Django channels Custom AuthMiddleware
I have a problem. I am using DJango Rest Framework for my project, with simpleJWT authorization. And when I am trying to make custom auth for Channels from asgiref.sync import sync_to_async from channels.db import database_sync_to_async from django.contrib.auth.models import AnonymousUser from django.db import close_old_connections from rest_framework_simplejwt.tokens import UntypedToken from rest_framework_simplejwt.exceptions import InvalidToken, TokenError from jwt import decode as jwt_decode from django.conf import settings from prowl_auth.models import NewUser from urllib.parse import parse_qs def close_connections(): close_old_connections() def find_user(id): return NewUser.objects.get(id=id) class TokenAuthMiddleware: """ Custom token auth middleware """ id = 0 def __init__(self, inner): # Store the ASGI application we were passed print('FUCK1') self.inner = inner def __call__(self, scope): # Close old database connections to prevent usage of timed out connections close_connections() print('FUCK2') # Get the token print('FUCK3') token = parse_qs(scope["query_string"].decode("utf8"))["token"][0] # Try to authenticate the user try: # This will automatically validate the token and raise an error if token is invalid UntypedToken(token) except (InvalidToken, TokenError) as e: # Token is invalid print(e) print('FUCK4') return None # Then token is valid, decode it decoded_data = jwt_decode(token, settings.SECRET_KEY, algorithms=["HS256"]) print(decoded_data) # Will return a dictionary like - # { # "token_type": "access", # "exp": 1568770772, # "jti": "5c15e80d65b04c20ad34d77b6703251b", # "user_id": 6 # } … -
Django admin documentation with mixed case project name
I'm having a problem with the Django admin documentation, largely down to the fact that when I first started I used a capitalised name for the app. I have a project "Survey" with an app "Report", and for sake of argument, a model in "Report" called "Question" Having enabled the admin documentation, I can access the documentation for my models from the Documentation -> Models page, but any links on the model pages - either automatically generated or added by myself using the :model:'app.model' format fail. The admin pages are using the correct case, but the links generated use all lowercase, i.e. the link from the Documentation -> Models page is http://localhost:8000/admin/doc/models/Report.question/ and this shows correctly, however the link generated on the model page is http://localhost:8000/admin/doc/models/report.question/ Is there a setting or something I can do to ensure that the links use the correct case, i.e. with capital R? Thanks in advance! -
Is there a way to make a user only view related objects to him in a model in django administration?
I'm new to django and i'm trying to make a school web app fully inside the django administration. The thing i'm trying to do is to make a permission for the students that gives them the ability to only see the scores which its student field is same to the student user. This is my Student model: class Student(models.Model): student_name = models.CharField(max_length=12) student_last_name = models.CharField(max_length=12,null=True) student_age = models.PositiveSmallIntegerField(null=True) student_class = models.ForeignKey(Clas,on_delete=models.SET_NULL,null=True) student_idnum = models.CharField(max_length=15,null=True) user = models.OneToOneField(User,on_delete=models.SET_NULL,null=True) pub_date = models.DateTimeField("date published") def __str__(self): return self.student_name And this is my students Score model: class Score(models.Model): exam = models.ForeignKey(Exam,on_delete=models.SET_NULL,null=True) student = models.ForeignKey(Student, on_delete=models.CASCADE,null=True) score = models.FloatField(null=True) def __str__(self): return str(self.score) I have seen the Meta model which i should use it for the custom permission, but i really don't know what should i do. -
How can I connect style.css to base.html django?
Im trying to make style.css file work but i cant figure out what am i doing bad. I added to settings: (i have tried many paths(i tried every way of absolute path)) STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/polls'), ] to base.html: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" /> my structure: PizzaPortal -PizzaPortal -settings.py -polls -static -polls -style.css -templates -
Django issue with form - local variable referenced before assignment
I have a view which returns information from a queryset. I'm trying to include a form on this same page. In my view, I have implemented the form logic exactly like another form I have in a different view which works perfectly. However with this view I get the error in the title. My view is: def managecustomer(request, urlid): customer = Customer.objects.get(id=urlid) form = AssignCustomerForm() if request.method == "POST": form = AssignCustomerForm(request.POST) AssignCustomerForm = forms.ModelChoiceField(queryset=Manager.objects.all(), to_field_name="full_name") if form.is_valid(): post = form.save(commit=False) post.save() return render(request, 'mysite/managecustomer.html', {}) else: form = AssignCustomerForm() context = { 'customer': customer, 'urlid': urlid, 'form': form, } return render(request, 'mysite/managecustomer.html', context) I assign the form variable as the second line in my view, so why am I getting the error that I am trying to reference the form before it has been assigned? -
Is Django registration redux form open source
Can we use Django registration redux form in professional website. I am confused. Please help. -
pgcrypto- TypeError: from_db_value() missing 1 required positional argument: 'context'
I get this error when i try to use Encrypted fields provided by "pgcrypto" in Django models. I have found that newer versions of Django do not support the context argument but I cannot find any workaorund for this. Any help would be appreciated. Here is my error stack: Traceback (most recent call last): File "C:\Users\maz\PycharmProjects\dbEncryption\venv\lib\site-packages\django\core\handlers\exception.py", line 3 4, in inner response = get_response(request) File "C:\Users\maz\PycharmProjects\dbEncryption\venv\lib\site-packages\django\core\handlers\base.py", line 145, i n _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\maz\PycharmProjects\dbEncryption\venv\lib\site-packages\django\core\handlers\base.py", line 143, i n _get_response response = response.render() File "C:\Users\maz\PycharmProjects\dbEncryption\venv\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\maz\PycharmProjects\dbEncryption\venv\lib\site-packages\django\template\response.py", line 83, in rendered_content return template.render(context, self._request) File "C:\Users\maz\PycharmProjects\dbEncryption\venv\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\maz\PycharmProjects\dbEncryption\venv\lib\site-packages\django\template\base.py", line 171, in ren der return self._render(context) File "C:\Users\maz\PycharmProjects\dbEncryption\venv\lib\site-packages\django\template\base.py", line 163, in _re nder return self.nodelist.render(context) File "C:\Users\maz\PycharmProjects\dbEncryption\venv\lib\site-packages\django\template\base.py", line 936, in ren der bit = node.render_annotated(context) File "C:\Users\maz\PycharmProjects\dbEncryption\venv\lib\site-packages\django\template\base.py", line 903, in ren der_annotated return self.render(context) File "C:\Users\maz\PycharmProjects\dbEncryption\venv\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\maz\PycharmProjects\dbEncryption\venv\lib\site-packages\django\template\base.py", line 163, in _re nder return self.nodelist.render(context) File "C:\Users\maz\PycharmProjects\dbEncryption\venv\lib\site-packages\django\template\base.py", line 936, in ren der bit = node.render_annotated(context) File "C:\Users\maz\PycharmProjects\dbEncryption\venv\lib\site-packages\django\template\base.py", line 903, in ren der_annotated return self.render(context) File "C:\Users\maz\PycharmProjects\dbEncryption\venv\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\maz\PycharmProjects\dbEncryption\venv\lib\site-packages\django\template\base.py", line 163, in _re nder return … -
Get spider list from Scrapy in Django Project
I'm following this answer to get the spider list on my Scrapy Project inside Django, so this is what the structure looks like. my_app/ -- apps/ # django apps folder -- crawler/ -- __init__.py -- admin.py -- apps.py -- views.py <~ here is where the code below located -- etc.. -- my_app/ # django project folder -- __init__.py -- asgi.py -- settings.py -- etc.. -- scraper_app/ # scrapy dir -- scraper_app/ # scrapy project folder -- spiders/ -- abc_spider.py -- __init__.py -- middlewares.py -- pipelines.py -- settings.py -- etc.. -- scrapy.cfg -- manage.py -- scrapyd.conf -- setup.py -- etc.. and here is the piece of codes that showing the list of available spiders, when I run it on scrapy shell, but its always return an empty string when I tried to run it from django app in views.py, which is crawler app. project_settings = project.get_project_settings() spider_loader = spiderloader.SpiderLoader.from_settings(project_settings) spiders = spider_loader.list() so my problem is, how to make those script working on django project as well using Django or Scrapy way if available? thanks -
clear.cache() still loads cached pages on redis server
I am performing caching in django with Redis. I want to clear the cache Whenever a user changes the language of website. I am trying to clear the cache using clear.cache() but django still loads the same old cached pages. I have tried several ways to fix it,but nothing works. settings.py CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, "KEY_PREFIX": "example" } } Views.py def changeLanguageToAR(request): cache.clear() #this is the part where i am clearing the cache user_language = 'ar-ae' translation.activate(user_language) request.session[translation.LANGUAGE_SESSION_KEY] = user_language return JsonResponse({'status':200}) Is there any way to clear the cache completely?