Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Manually add User / Socialacount with Django-Allauth
I'm using django-allauth, strictly using google account for user sign in. However, I want it so that only manually added user can sign in. For example, A certain user with email test@google.com wants to be able to login. Now what I must do is manually add this user's email using the admin app. After that, the user would be able to login using google account. I tried disabling signup by returning false for the function 'is_open_for_signup' from DefaultAccountAdapter and then in the admin panel I added the user with the email provided and added the socialaccount. But when I try to login, it's recognized as signup instead. I think it has something to do with the uid or extra data in the socialaccount model. I tried signing up using google account and then deleted the uid and extra data. After that, I disabled signup and tried to login again but it says signup is closed/blocked. I don't know what to do next. -
how to display contents dynamically when the button is clicked
The below code shows that when the anchor tag is clicked the content related to that specific title is retrieved and shown in another html page name doc1.html. The link that redirects it to next page in present in this file. judge_civil.html file <div class="container-middle"> <div id="limitations" class="tabcontent"> {% for data in law_data %} {% if data.law_type == 'civil' and data.law_category == 'limitations' %} <div class="tab"> <!--<button class="tablinks" onclick="openLawtype(event,'title')">{{data.title}} &nbsp<i class="fas fa-chevron-circle-right"></i></button>--> <a href="{% url 'doc1' data.pk %}" target="_blank">{{data.title}}</a><br/><br/> </div> {% endif %} {% endfor %} </div> </div> Here when the link is clicked the content that is associated with {{data.title}} is opened and displayed in a new html file dynamically using the primary key that i have passed along with it. The code in doc1.html is below <p>{{ object.judgements|safe}}</p> But now I want to display this content that is being displayed in doc1.html in the judge_civil.html inside the below : <div class="container-right"> </div> I assume that this can only be done with javascript. I don't know javascript at all so if you can provide me the code to this task it will be really helpfull. I am also providing the models and viwes and urls code if needed: models.py … -
Is it safe just to remove the installed app and then delete the folder in Django?
I am using Django and I have an app inside called "stuff". I decided I didn't need it anymore so I removed all usage of it from all my files, I removed it from settings.py under installed apps, and then I just deleted its entire folder. Is that okay to do? So far everything seems to still be running fine and it no longer shows up in my admin panel which is what I want. I was reading some other posts on how to remove a Django App and they were doing a lot of extra things like this: https://stackoverflow.com/questions/3329773/django-how-to-completely-uninstall-a-django-app#:~:text=To%20remove%20the%20app%20from,your%20PYTHONPATH%20where%20it%20resides. Should I be worried something bad will happen down the road? I can makemigrations and changes and do everything perfectly fine currently. -
Django multiple user type implemenation
I am trying implementation where, one user type(end user) who will have email/phone number + password authentication where as the other type of user(admin/staff) will have username + password authentication. Struggling with many resources available on the internet but still has not been able to get through it. -
why django models error keeps raising error?
I moved these to models to chat app class Message(models.Model): sender = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name="فرستنده") receiver = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name="گیرنده", related_name="reciver") text = models.CharField("متن", max_length=500) date_and_time = models.DateTimeField(auto_now_add=True) subject=models.CharField(max_length=200,verbose_name="موضوع") notification=models.OneToOneField(Notification,on_delete=models.DO_NOTHING,related_name="message",null=True) class Meta: verbose_name = "پیام" verbose_name_plural = "پیام ها" class Response(Message): darkhast_sabt_sherekat=models.ForeignKey(SabteSherkat,on_delete=models.CASCADE,related_name="responses") After that it raise an error saying local id of Response crashed with message i made everything undo and this error keeps coming up * Operations to perform: Apply all migrations: accounts, admin, auth, consultation, contenttypes, sessions, utilities, web Running migrations: Applying web.0007_auto_20210815_0831...Traceback (most recent call last): File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: near ")": syntax error The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 231, in handle post_migrate_state = executor.migrate( File "/home/hamed/sqh-source/venv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 117, in migrate … -
Django to generate dynamic image/pdf
I want to generate course completion cetificates using Django (and or javascript library) When a user completes a course/exam his name should appear on this certificate along with score and should be downloadable. It can be a pdf or an image. How can I achieve this? Please suggest. -
Sockets in Django
In my project I have users who connect to a waiting room, after a certain time, I run an algorithm and then redirect all the users to a different room. In order to this I use sockets. Until now I have been using django_channels with daphne on Asgi, however it hasn't been 100% reliable. I need something that will work all the time. I am looking for an alternative. I need it to accurately tell me who is in the room and who has left etc. The options are: Pyzmq websockets - https://websockets.readthedocs.io/en/stable/index.html# Autobahn|Python python-socketio websocket-client graphene converse js I would really appreciate feedback. I would prefer something which can integrate easily with django if possible. The website is up on AWS. Thanks -
how to shuffle html field? - django
I am building a website for learning vocabulary in English. The website let users add words in English and an association on how to remember the word in Hebrew. The user gets 4 random words from the database and has to choose the right word and if he answered correctly he gets the right answer. The problem is that the correct answer is always in the same place and I can not find a way to mix the fields... I need some help .. def practice(request): words_list = Words.objects.filter(approved= True) # Take all the words that approved by the admin random_word_to_guess = random.choice(words_list) # Take one random words from the DB word_1 = random.choice(words_list) word_2 = random.choice(words_list) word_3 = random.choice(words_list) quiz_list = [word_1, word_2, word_3, random_word_to_guess] random_list = random.shuffle(quiz_list) count = 0 correct_answer = 0 incorrect_answer = 0 if request.method == "POST" : quiz = request.POST.get("quiz") #Grab the item from the form if request.POST.get('correct'): # if the user click on button that his name =correct - the choice is correct message = "תשובה נכונה" count += 1 correct_answer +=1 return render(request, "practice.html", {"incorrect_answer":incorrect_answer,"correct_answer":correct_answer,'count':count,'message': message, 'word_1':word_1,'word_2':word_2,'word_3':word_3,'random_word_to_guess':random_word_to_guess,"quiz":quiz}) elif request.POST.get('incorrect'): count += 1 incorrect_answer += 1 message = "תשובה לא נכונה" return render(request, … -
Django, "render" returns a POST request and not GET after a POST request
I'm having my view def my_wishlist(request): user = request.user user_products = WishlistProductPrices.objects.filter(user=user).all() ### Create filters ### filter = get_user_filter_fields_wishlist(user_products) filter = filter(request.GET,queryset = user_products) if request.method == "POST": post_form = MyForm(request.POST) if post_form.is_valid(): #do stuff form = MyForm() context = { "form":form, "filter":filter } return render(request, "myapp/add_wishlist.html",context=context) #Returns POST, seems like else: #invalid post_form context = { "form":post_form, "filter":filter } return render(request, "myapp/add_wishlist.html",context=context) else: #Get request form = MyForm() context = { "form":form, "filter":filter } return render(request, "myapp/add_wishlist.html",context=context) it works like a charm, but after the user has submitted something, and presses F5 the "do you want to resend the information again" pops-up. I find it weird, since I assume the render(request,"mypp/add_wishlist.html) ad the bottom of the page would return a GET request? -
My CSS files are not getting loaded from my S3 bucket, why?
Here's my S3 configurations: STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_QUERYSTRING_AUTH = False I have a couple of models that have ImageFields and when I upload an image it properly gets uploaded to my S3 bucket. But I also want to put my staticfiles there (JS, CSS). I have manually created a folder in the root of my S3 bucket called static and I have uploaded all of my CSS, JS files to that folder using S3's web app. However, in my template I am simply doing {% static 'css/main.css' %} and the file is not getting loaded. I used Chrome's inspect tool to check which resources are being loaded and I think it gets connected to my S3 bucket, but brings the file I want empty, so it is not getting loaded for some reason. enter image description here -
How can Django get session data in next request?
def home(request): # logged in if request.user.is_authenticated: request.session['username'] = str(request.user) request.session.set_expiry(0) # anonymous else: # how could Django get session data here ? cur = request.session.get('username', None) if cur: pass else: anon = random.choice(settings.SESSION_NAMES) request.session['username'] = anon request.session.set_expiry(42) res = render(request, 'ex/home.html', {'username': request.session['username']}) return res I'm trying to understand about session. In anonymous case above, I set session data 'username' to request that is already obtained. And in next request (after refreshing), I can get session data. But I don't understand how could it work. It's a new request, and I set 'username' in prev request, not response. How could I get 'username' from next request object despite not setting it to previous response object? -
Not able to redirect to home page using javascript after form submission in contact page
This is my contact.html page code: {% block body %} <form action="/shop/contact" method="POST">{% csrf_token %} <div class="container"> <h1 style="text-align:center;margin:10px">Contact Us</h1> <div class="mb-3"> <label for="name" class="form-label">Name</label> <input type="text" class="form-control" id="name" name="name" placeholder="Enter Your Name"> </div> <div class="mb-3"> <label for="email" class="form-label">Email</label> <input type="email" class="form-control" id="email" name="email" placeholder="name@example.com"> </div> <div class="mb-3"> <label for="phone" class="form-label">Phone Number</label> <input type="tel" class="form-control" id="phone" name="phone" placeholder="Enter Your Phone Number"> </div> <div class="mb-3"> <label for="desc" class="form-label">Comments and Feedback</label> <textarea class="form-control" id="desc" name="desc" rows="3"></textarea> </div> <button type="submit" class="btn btn-primary feed">Submit</button> </div> </form> {% endblock %} And this is my javascript code in contact.html: <script> $('.feed').click(function(){ window.location.href="http://127.0.0.1:8000/shop/"; alert('Thank You for your comment or feedback. We will definately try to improve or will reach you out regarding this issue.'); }); </script> {% endblock %} This window.location.href statement is not working to redirect me to shop(or home page). I cannot change my form action to /shop because I want form data to be stored in contact page only. So what can I do?? -
Django - Page not found (404) urls.py
problem: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/home/category/coding/ Raised by: blogapp.views.BlogDetailView urls.py from django.urls.conf import path from blogapp.views import BlogDetailView, BlogListView,searchposts,CatListView from . import views app_name = "blogapp" urlpatterns = [ path('', views.BlogListView, name="blogs"), path('home/search/', views.searchposts, name= "searchposts"), path('home/category/<slug:_id>/', views.BlogDetailView, name="blog"), path('home/category/<category>/', views.CatListView.as_view(), name="category"), ] if i reverse this two path('home/category/slug:_id/', views.BlogDetailView, name="blog"), path('home/category//', views.CatListView.as_view(), name="category"), it shows the html of the category , and the path of 'path('home/category/slug:_id/', views.BlogDetailView, name="blog"),' is not showing , vice versa here is the html of navbar {% for category in category_list %} {% if forloop.counter < 4 %} <li class="nav-item"> <a class="nav-link" href="home/category/{{category.name}}">{{ category.name|title }}</a> </li> {% endif %} {% endfor %} html that i want to render {% extends "_layouts/base.html" %} {% block css %} {{block.super}} {% endblock css %} {% block page_title %}Insert_your_name_here{% endblock %} {% load static %} <!-- load the image --> {% block maincontent %} <!-- Banner --> {% block banner %} {% load static %} {% include "layout/category_banner.html" %} {% endblock %} <!-- Banner Here --> !-- This is the main template --> <section class="blog-posts grid-system"> <div class="container"> <div class="row"> <div class="col-lg-8"> <div class="all-blog-posts"> <div class="row"> {% block categories-main %} {% include "layout/category.html" %} … -
Tags imported but relationship not imported with django-import-export
I am trying to import a csv file with quotes and tags into my django-taggit custom tag model following https://docs.wagtail.io/en/stable/reference/pages/model_recipes.html#custom-tag-models. I want to keep the tags for quotes separate from tags for blog posts. After looking at previous answers How do I import tags using django-import-export? and How to import django-taggit tag in django-import-export, I managed to import the csv file. The tags are imported but the relationship is not imported (see screenshots of admin). I think the problem is in QuoteTagResource and TaggedQuoteResource but I can't figure it out. I would appreciate any help, a hint or point me to a resource I can reference? Thanks in advance! #models.py from django.contrib.auth import get_user_model from django.db import models from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from modelcluster.contrib.taggit import ClusterTaggableManager from taggit.models import TagBase, ItemBase from wagtail.snippets.models import register_snippet from ckeditor.fields import RichTextField import sys sys.path.append("..") # Adds higher directory to python modules path. from userauth.models import CustomUser @register_snippet class QuoteTag(TagBase): class Meta: verbose_name = "Quote Tag" verbose_name_plural = "Quote Tags" class TaggedQuote(ItemBase): tag = models.ForeignKey(QuoteTag, related_name="tagged_quotes", on_delete=models.CASCADE) content_object = ParentalKey(to="Quote", related_name="tagged_items", on_delete=models.CASCADE) def get_sentinel_user(): return get_user_model().objects.get_or_create(username='deleted_user')[0] def set_admin(): return get_user_model().objects.get(pk=1).id class Quote(ClusterableModel): text = RichTextField(config_name='awesome_ckeditor', help_text="You must enter some … -
Django form init method failing
I have an user add form view that asks for information and saves a new user to the db. When I try saving a new user record, I get the following error. TypeError at /user/add/ __init__() missing 1 required positional argument: 'customer' Request Method: GET Request URL: http://localhost:8000/user/add/ Django Version: 3.0.5 Exception Type: TypeError Exception Value: __init__() missing 1 required positional argument: 'customer' Exception Location: D:\Job Documents\DDS\AuthenticationProject\env\lib\site-packages\django\views\generic\edit.py in get_form, line 33 Python Executable: D:\Job Documents\DDS\AuthenticationProject\env\Scripts\python.exe Python Version: 3.9.0 Python Path: ['D:\\Job Documents\\DDS\\AuthenticationProject\\auth', 'C:\\Users\\bratca\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\bratca\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\bratca\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\bratca\\AppData\\Local\\Programs\\Python\\Python39', 'D:\\Job Documents\\DDS\\AuthenticationProject\\env', 'D:\\Job Documents\\DDS\\AuthenticationProject\\env\\lib\\site-packages'] Server time: Sun, 15 Aug 2021 08:05:30 +0000 I am using customer object to differentiate users, therefore I want the form to know by whom it's being filled such that a new created user will have the same customer object as the creator. This error does not show exactly where is my bug in the code. Instead it shows some error in the actual django code, generic things that I am using. class AddUserFormView(FormView): form_class = TbUserAddForm template_name = 'users/add_user_modal.html' success_message = "Account has been created! The user is able to log in." def post(self, request): form = self.form_class(customer=request.user.customer, data=request.POST, files=request.FILES) if form.is_valid(): user_face_img_md5 = Image.open( request.FILES['user_face_img_md5'].file) user_head_img_md5 = Image.open( … -
Including two Inclusion Tags in Template Tag
Possibly the wording of my initial question is wrong, I was really unsure how to word it. Here is my current code. product_display.py from django import template from categorytree.models import CategoryTree register = template.Library() @register.inclusion_tag('templatetags/product_display.html') @register.simple_tag(takes_context=True) def this_shows_products(category, **kwargs): try: return {'ProductsModel': CategoryTree.objects.all().filter(title=category).first().products.all()} except: pass product_display.html {% load static %} <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> </style> </head> {% load product_display %} <div class='row'> {% for obj in ProductsModel %} <div class='col-xs-12 col-sm-12 col-md-6 col-lg-3 col-xl-2 col-xxl-1 ' style="margin-bottom:15px; margin-top:15px"> {% include 'products/snippets/card.html' with instance=obj cart=cart %} </div> {% endfor %} </div> Depending on the width of the screen, I want to be able to use different HTML templates. I want something like this - If screen width > 1600 then @register.inclusion_tag('templatetags/product_display.html') else @register.inclusion_tag('templatetags/product_display(1).html') end if I tried using pyauthogui, GetSystemMetrics and elsewhere in my code I have $(window).width but so far nothing I have tried has remotely solved this current problem. I could make two separate template tags but was hoping there was a more efficient way of addressing my problem. -
Django merge 2 querysets overide annotation
I have 2 models. Followers Influencers class Influencer(models.Model): username = models.CharField( _("username"), max_length=250, unique=True, null=False, blank=False, db_index=True) followers = models.ManyToManyField( "instagram_data.Follower", verbose_name=_("Followers")) I want to create a QS of followers from 2 influencers: influencer_choosen_by_user = [influ1name, influ2name] qs = Follower.objects.none() qs_influencers = Influencer.objects.filter(username__in=influencer_choosen_by_user) for influencer_obj in qs_influencers.iterator(): followers_of_influ_qs = influencer_obj.followers.all() # get all followers of this influencer followers_of_influ_qs = followers_of_influ_qs.annotate( influencer_source=Value(f'followers/{influencer_obj.username}', CharField())) qs = qs | followers_of_influ_qs ISSUE: All qs are of influencer_source == influ1name none of influ2name !!! Why ? -
AttributeError: 'QuerySet' object has no attribute 'active' in Django rest framework
I am trying to implement Coupon code feature in Django Rest framework. When a user tries to purchase a product and wants to use coupon codes presented on the item, the user should be able to get a discount based on that coupon code. The coupon should be vaild ie should be within the valid till date and also should be active. But when I try to make an order object from postman without sending the coupon codes, I got the following error. AttributeError: 'QuerySet' object has no attribute 'active' Before the application of Coupon code feature, I was able to make an order. My models: class Coupons(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE, blank=True,null=True,related_name="coupons") code = models.CharField(max_length=50,unique=True) valid_form = models.DateField() valid_till = models.DateField() active = models.BooleanField(default=False) discount = models.IntegerField(default=0) def __str__(self): return self.code Order model: Here every calculation for the prices are done. class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order_ID = models.CharField(max_length=12, editable=False, default=id_generator) #order_items = models.ManyToManyField('OrderItem',blank=True, null=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) current_points = models.FloatField(default=0) total_price = models.FloatField(blank=True,null=True) point_spent = models.FloatField(default=0) coupon_code = models.CharField(max_length=15, blank=True, null=True) def final_price(self): total = sum([_.price_1 for _ in self.order_items.all()]) total -= Decimal(self.price_of_points) dis = self.price_of_coupon print(dis) total = total - … -
how to search or filter data of two different model and return it in one
I have two models. First model is about the main information and the Second one is the detail of the first model(actually its about the way that the first one is delivered) and the second model has the ForeignKey of the first one and each data of the first model can have many data in the second one. what I want to do is to filter the data of both models and return it in one row of table! My First Model : class Report(models.Model): factory_account = models.ForeignKey(Account, on_delete=models.CASCADE) factory_state = models.CharField(choices=State, max_length=20) factory_id = models.IntegerField() factory_name = models.CharField(max_length=50) buyer_state = models.CharField(choices=State, max_length=20) buyer_name = models.CharField(max_length=50) buyer_national_id = models.IntegerField() buyer_city = models.CharField(max_length=50) buyer_address = models.CharField(max_length=500) landline_buyer_phone = models.IntegerField() buyer_phone = models.IntegerField() date = jmodels.jDateField() invoice_number = models.IntegerField(unique=True) bran_number = models.IntegerField() price = models.IntegerField() delivered = models.IntegerField() delivery_balance = models.IntegerField() My Second Model : class DeliverDetail(models.Model): invoice_number = models.ForeignKey(Report, on_delete=models.CASCADE, null=True) date = jmodels.jDateField() delivered = models.IntegerField() car_type = models.CharField(max_length=20) car_tag = models.CharField(max_length=20) driver_name = models.CharField(max_length=50) driver_national_code = models.IntegerField() My Filter.py (Using Django-filter(https://pypi.org/project/django-filter/)): class myFilter(django_filters.FilterSet): car_type = django_filters.CharFilter(lookup_expr='icontains', distinct=True, field_name='deliverdetail__car_type') car_tag = django_filters.CharFilter(lookup_expr='icontains', distinct=True, field_name='deliverdetail__car_tag') driver_name = django_filters.CharFilter(lookup_expr='icontains', distinct=True, field_name='deliverdetail__driver_name') driver_national_code = django_filters.NumberFilter(lookup_expr='iexact', distinct=True, field_name='deliverdetail__driver_national_code') class Meta: model = Report fields … -
Django: how to show a narrowed drop-down list based on the previous selection?
For example I would like make an instance CAR with two information: Manufaturer and CarModel. class Manufacturer(models.Model): name = models.CharField(max_length=10, blank=False) class CarModel(models.Model): name = models.CharField(max_length=10, blank=False) class Car(models.Model): producer = models.OneToOneField(Manufacturer, on_delete=models.CASCADE()) carmodel = models.OneToOneField(CarModel, on_delete= models.CASCADE()) Of course before I would make an instance for class Car I would have to make instances for class Manufacturer and CarModel. I would make BMW, Volvo, Toyota for Manucaturer and then series 3, series 5, X5, X7, XC90, V40, Prius, Land Cruiser, Corolla. Finally when I would make an instance for class Car I would see first: BMW, Volvo, Toyota I would choose Toyota and then I would like see in next drop-down list only: Prius, Land Cruiser, Corolla Of course BMW does not manufature Prius :) How can I do something like filter for that? -
What mistake am I making to cause these Django E304 errors?
I cannot for the life of me figure out what I'm doing wrong here, any help would be very much appreciated! The Goal: We have admins and appraisers signing up on the site. Admins can of course do everything you'd expect from the /admin site and appraisers have their own site, /portal. What I'm trying to do now is improve my current model so that I can add more fields to the appraiser users. The admin user's fields are a subset of the appraiser user's fields. The Error: SystemCheckError: System check identified some issues: ERRORS: accounts.Appraiser.groups: (fields.E304) Reverse accessor for 'accounts.Appraiser.groups' clashes with reverse accessor for 'accounts.Admin.groups'. HINT: Add or change a related_name argument to the definition for 'accounts.Appraiser.groups' or 'accounts.Admin.groups'. accounts.Appraiser.user_permissions: (fields.E304) Reverse accessor for 'accounts.Appraiser.user_permissions' clashes with reverse accessor for 'accounts.Admin.user_permissions'. HINT: Add or change a related_name argument to the definition for 'accounts.Appraiser.user_permissions' or 'accounts.Admin.user_permissions'. accounts.Admin.groups: (fields.E304) Reverse accessor for 'accounts.Admin.groups' clashes with reverse accessor for 'accounts.Appraiser.groups'. HINT: Add or change a related_name argument to the definition for 'accounts.Admin.groups' or 'accounts.Appraiser.groups'. accounts.Admin.user_permissions: (fields.E304) Reverse accessor for 'accounts.Admin.user_permissions' clashes with reverse accessor for 'accounts.Appraiser.user_permissions'. HINT: Add or change a related_name argument to the definition for 'accounts.Admin.user_permissions' or 'accounts.Appraiser.user_permissions'. Before … -
How to access list of dictionary in Django template
I am very new to Django and implemented a post-api call by watching couple of tutorials and one of the fields gets a list of dictionaries, want to access the key value pair in Django template, instead it is taking char by char, how to solve this problem? models.py class Leads(models.Model): Name = models.CharField(max_length=50) Mobile = models.CharField(max_length=13) Email = models.CharField(max_length=50) Message = models.CharField(max_length=300) created_on = models.DateTimeField(default=datetime.now()) modified_on = models.DateTimeField(default=datetime.now()) Example input for above api call will be: Name = rakesh Mobile = 1234567890 Email = email@mail.com Message = [{'key': 'some text', 'value': 'some value'}, {'key': 'some text', 'value': 'some value'}] template.html {%for user in users %} <tr> <td>{{user.Name}}</td> <td>{{user.Mobile}}</td> <td>{{user.Email}}</td> <td>{{user.Message}}</td> </tr> {%endfor%} If I try like above then the output is rakesh 1234567890 emaik@mail.com [{'key': 'some text', 'value': 'some value'}, {'key': 'some text', 'value': 'some value'}] If I add another loop for Message field then the Message field is not showing any output: {%for user in users %} <tr> <td>{{user.Name}}</td> <td>{{user.Mobile}}</td> <td>{{user.Email}}</td> {%for i in user.Message %} <td>{{i.key}}</td> <td>{{i.value}}</td> {%endfor%} </tr> {%endfor%} Output: displaying string by string rakesh 1234567890 emaik@mail.com If I try like this then: {%for user in users %} <tr> <td>{{user.Name}}</td> <td>{{user.Mobile}}</td> <td>{{user.Email}}</td> {%for i in user.Message … -
Template tags not working inside an included template
I include tags inside an included template. However, even though I extend the base template, in my templates (list.html) the tags are not rendered. Perhaps something I am missing? base.html: <div class="content-page"> <div class="content"> <div class="container-fluid"> {% include 'partials/pageTitle.html' %} </div> </div> </div> partials/pageTitle.html: <h4 class="page-title">{% block pageTitle %}{% endblock pageTitle %}</h4> list.html (tags not working) {% extends 'base.html' %} {% block pageTitle %} Basic Tables {% endblock pageTitle %} -
django IntegrityError for create object
I have this models . When i use One To One relation ship for real_estate field in Profile model and create new object i get this error => IntegrityError at /admin/users/profile/add/ NOT NULL constraint failed: users_profile.real_estate_id class Business(models.Model): name = models.CharField(max_length=200) image = models.ImageField() homes = models.ManyToManyField(Homes , related_name='home', blank=True) create = models.DateField(auto_now_add=True) number = models.IntegerField() class Profile(models.Model): CHOICES = ( ('RE', 'مشاور املاک'), ('S', 'فروشنده'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) real_estate = models.OneToOneField(Business , related_name='business' ,on_delete=models.CASCADE, blank=True) image = models.ImageField(blank=True) type_of_user = models.CharField(max_length=300, choices=CHOICES) phone_number = PhoneNumberField(unique = True, null = False, blank = False) -
Insert a python dictionary into postgres jsonb field
I'm looking to a postgresql query or function to replace the flowing python code def insert_data(pk, data) json_str = Employee.objects.filter(pk=pk).values_list('time_log', flat=True)[0] dt = data["date"] data.pop("date") if json_str.get(f"{dt}") == None: json_str[f"{dt}"] = [data] else: json_str[f"{dt}"].append(data) # time_log is a `jsonb field` Employee.objects.filter(pk=pk).update(time_log=json_str) The code works but not efficient and causes bottlenecks. Data is dictionary containing a date and two datetime objects like this: data = { '2021-08-13': [ { 'clock_in': '2021-08-15T04:16:41.307Z', 'clock_out': '2021-08-14T21:16:44.491-07:00' } ] } IF the key does not exist, make a new key value pair, the key is the date in data and value is a list containing the data dictionary. IF the key exists, append data into key of date from data dictionary.