Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
save many to many update form - (forms.form) - django
i can't save new data set to the field (branch) which is many to many relation with another model named 'branch' that i need to save on my current model 'Products' note: every thing works fine except for saving the new branches added to update form model class Product(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category, related_name='product_category', on_delete=models.PROTECT) image = models.ImageField(upload_to='images', null=True, blank=True) branch = models.ManyToManyField(Branch, related_name='product_branch') views.py def product_update(request, pk): current_product = get_object_or_404(models.Product, pk=pk) initial_dict = { "branch": current_product.branch.all(), "name": current_product.name, "category": current_product.category, } edit_product_form = forms.EditProductForm(request.POST, request.FILES, initial=initial_dict) if request.method == 'POST': if edit_product_form.is_valid(): try: name = edit_product_form.cleaned_data['name'] category = edit_product_form.cleaned_data['category'] image = edit_product_form.cleaned_data['image'] if models.Product.objects.filter(Q(name=name) & ~Q(id=current_product.id)).exists(): messages.add_message(request, messages.INFO, _('إسم المنتج مضاف من قبل بالفعل')) else: current_product.name = name current_product.category = category current_product.image = image current_product.save() messages.add_message(request, messages.INFO, _('تم تعديل المنتج بنجاح')) return redirect('product_details', pk=current_product.id) except ImageSizeError: messages.add_message(request, messages.INFO, _('حجم الصورة اصغر من المطلوب')) return redirect('product_details', pk=current_product.id) else: edit_product_form = forms.EditProductForm( initial=initial_dict) context = { 'current_product': current_product, 'edit_product_form': edit_product_form, } return render(request, 'product_update.html', context) forms.py class EditProductForm(forms.Form): name = forms.CharField(widget=forms.TextInput) category = forms.ModelChoiceField(queryset=models.Category.objects.all()) image = forms.ImageField(widget=forms.FileInput()) branch = forms.ModelMultipleChoiceField(queryset=models.Branch.objects.all(), widget=forms.SelectMultiple) -
Foriegn key shown as a drop down. Any way to show it as a text value ? (django)
In my application, on page1, I create a Project object and then on page 2, I create a batch object. The "batch" object has a many-to-one relationship with "Project". It therefore needs to display the Project object when batch form is called. I can show the Project object on a batch form but it is shown as a drop down. I would like it to be shown as a field value but it doesnt work. Can you please help. Thanks. models.py Class Project name = models.CharField() Class Batch name = models.CharField() project = models.ForeignKey('Project', on_delete=models.CASCADE) template.py <a href="{% url 'create_batch_url' pk=project.id %}" role="button" >Link to Batch</a> passing the foreign key from urls.py path('batch/new/<int:pk>', batch_views.review_batch, name='create_batch_url'), views.py simple view which calls the model form forms.py class BatchForm(ModelForm): class Meta: model = Batch fields = ('name', 'project',) def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") project_id = kwargs.pop("project_id") #Only show the project where the request came from self.fields['project'].queryset = Project.objects.filter(id=project_id) -
How to use a single PostGreSQL while having two Django Apps accessing in Google App Engine and Google App Engine Flex
I have a Django Application (first application) running on Google App Engine. There is another time consuming application (second application) running in Google App Engine Flex. Both applications are connected to the same PostGreSQL Database. When the second application finishes its execution it needs to write the results to the database and first application can access the data. What should be the correct way to do this ? Should I use exact same models and expect everything to be straightforward ? -
Why the object is not deleted?
I am new to SO and Programming. And i found this SO question: How to dynamically delete object using django formset The author says here - https://stackoverflow.com/a/48075686/11523612 that when the user refreshes the page the item is still in the cart. But i dont understand why still stays in the cart when the ajax view is called and the object is deleted? -
How can I create form comatible with my user models in django and how can I convert my admimin page to contain these types of users?
models.py file: from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save from django.dispatch import receiver class User(AbstractUser): is_taxpayer = models.BooleanField(default=False) is_official = models.BooleanField(default=False) username = models.CharField(max_length=200, unique=True) email = models.EmailField(max_length=200, unique=True) class TaxpayerProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='taxpayer_profile') aadhar = models.DecimalField(max_digits=12, decimal_places=0) class OfficialProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='official_profile') aadhar = models.DecimalField(max_digits=12, decimal_places=0) uid = models.CharField(max_length=200) USERNAME_FIELD = 'uid' @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): print('****', created) if instance.is_taxpayer: TaxpayerProfile.objects.get_or_create(user = instance) else: OfficialProfile.objects.get_or_create(user = instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): print('_-----') # print(instance.internprofile.bio, instance.internprofile.location) if instance.is_taxpayer: instance.taxpayer_profile.save() else: OfficialProfile.objects.get_or_create(user = instance) Here is the forms.py file: from django import forms from .models import User, TaxpayerProfile, OfficialProfile class UserForm(forms.ModelForm): class Meta: model = User fields = ['username', 'email'] class TaxpayerProfileForm(forms.ModelForm): class Meta: model = TaxpayerProfile fields = ['aadhar'] class OfficialProfileForm(forms.ModelForm): class Meta: model = OfficialProfile fields = ['aadhar', 'uid'] Here is the views.py file: from django.contrib.auth import login from django.shortcuts import redirect, render from django.http import HttpResponse, HttpResponseRedirect from django.views.generic import CreateView from .forms import OfficialProfileForm, TaxpayerProfileForm, UserForm from .models import User, TaxpayerProfile, OfficialProfile def taxpayer_profile_view(request): if request.method == 'POST': user_form = UserForm(request.POST) taxpayer_profile_form = TaxpayerProfileForm(request.POST) if user_form.is_valid() and taxpayer_profile_form.is_valid(): user = user_form.save(commit=False) … -
Configure Django application(deployed on GKE) and Google Cloud Storage
I am writing an API ( endpoint: IP/create/user ) which has to upload image files to Google Cloud Storage Bucket. So, I have created a Multi-region and Standard : Storage Class bucket with name eitan_data_storage. While running the application on localhost the endpoint copy the image from source to specified directory. I created docker image and deployed on GKE. The api is working perfectly fine here. But my requirement is to store the media files of the system users to google cloud storage. models.py class Users(AbstractBaseUser, PermissionsMixin): """ This model is used to store user login credential and profile information. It's a custome user model but used for Django's default authentication. """ email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255, blank=False, null=False) last_name = models.CharField(max_length=255, blank=False, null=False) profile_picture = models.ImageField(upload_to='profile_pictures/', max_length=None, null=True, blank=True) is_active = models.BooleanField(default=True) # defing a custome user manager class for the custome user model. objects = managers.UserManager() # using email a unique identity for the user and it will also allow user to use email while logging in. USERNAME_FIELD = 'email' view.py class UserAPIViews(APIView): """ This is a create user api view class. """ parser_classes = (FormParser, MultiPartParser) def post(self, request, format=None): serialized_data = serializers.UserSerializer(data=request.data) if serialized_data.is_valid(): … -
DRF TypeError, you may need to make the field read_only
First of all, I have this project structure. foo_project - foo_project - __init__.py - asgi.py - settings.py - urls.py - wsgi.py - apps - board - __init__.py - admin.py - apps.py - models.py - serializers.py - tests.py - urls.py - views.py - accounts - __init__.py - admin.py - apps.py - models.py - serializers.py - tests.py - urls.py - views.py Board, # models.py class Board(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='boards') title = models.CharField(blank=False, max_length=255) body = models.TextField(blank=False) image = models.ImageField(upload_to='time_line_photo') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) class Meta: ordering = ['-created'] # serializers.py from rest_framework import serializers from .models import Board from django.contrib.auth.models import User class BoardSerializer(serializers.ModelSerializer): class Meta: model = Board fields = ('id', 'author', 'title', 'body', 'image', 'created','updated') # views.py from django.contrib.auth.models import User from django.shortcuts import render from rest_framework import generics from .models import Board from .serializers import BoardSerializer class BoardList(generics.ListCreateAPIView): queryset = Board.objects.all() serializer_class = BoardSerializer user = serializers.PrimaryKeyRelatedField(read_only=True,) def perform_create(self, serializer): serializer.save(user=self.request.user) class BoardDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Board.objects.all() serializer_class = BoardSerialize Accounts, # serializers.py from rest_framework import serializers from django.contrib.auth.models import User from ..board.models import Board class UserSerializer(serializers.ModelSerializer): boards = serializers.PrimaryKeyRelatedField( many=True, queryset=Board.objects.all() ) class Meta: model = … -
How to keep adding divs while there are objects to loop in Django?
I am creating a blog homepage. I basically have two divs. One the first one I only want to show the latest post added. On the second I want to show all other posts. So, I created this template: <div class="row"> {% for post in post_list %} {% if forloop.counter == 1 %} <div class="col-lg-10 mx-auto"> <div class="card card-blog card-background"> <div class="full-background" style="background-image: url('{{post.image.url}}"></div> <a href="{% url 'post_detail' post.slug %}"> <div class="card-body"> <div class="content-bottom"> <h6 class="card-category text-white opacity-8">{{post.created_on}}</h6> <h5 class="card-title">{{post.title}}</h5> </div> </div> </a> </div> </div> </div> <div class="row justify-content-center"> {% else %} <div class="col-lg-5"> <div class="card card-blog card-background"> <div class="full-background" style="background-image: url('{{post.image.url}}')"></div> <a href="{% url 'post_detail' post.slug %}"> <div class="card-body"> <div class="content-bottom"> <h6 class="card-category text-white opacity-8">{{post.created_on}}</h6> <h5 class="card-title">{{post.title}}</h5> </div> </div> </a> </div> </div> {% endif %} {% endfor %} My problem is that, right, after the {% else %}, it will loop two posts and stop. How can I make it continue to loop as long as there are posts? -
How to style TextField() model in django
I have got a field in my table: description = models.TextField() I would like to be able to decide how the text is display. For example I have a main description of a product and then I want to display some information like that: data1: data1 data2: data2 When I am adding a description in django admin page everything is connected with each other data1: data1 data2: data2 Is there a way to organize it in a different way? Can I choose what text would be bold? -
How do I form a Django query with an arbitrary number of OR clauses?
I'm using Django 2.0 with Python 3.7. I want to write a query that returns results if the fields contains at least one of the strings in an array, so I want to set up an OR query. I have tried this class CoopManager(models.Manager): ... # Meant to look up coops case-insensitively by part of a type def contains_type(self, types_arr): queryset = Coop.objects.all() for type in types_arr: queryset = queryset.filter(type__name__icontains=type) print(queryset.query) return queryset However, this produces a query that ANDs the clauses together. How do I perform the above but join all the clauses with an OR instead of an AND? I'm using MySql 5.7 but I'd like to know a db independent solution if one exists. -
How to improve problem solving skills in python/Django
I can say I am an intermediate programmer in python Django. I am trying to find a website (documents; anything) which hosts good puzzles (or similar) for python. My objective is to experience mind teasers kind of things for python. And certainly not any interview kind of questions. I would want to improve my techniques in python/Django, during a situation to solve a problem, or during implementation of an algorithm, etc. Second, I am also looking into new, simple and innovative problems (just problems, to improve problem solving) which can be practiced in python. For example, implementing shift rotate functionality (this is very basic, but will teach you in-depth bit handling), and to a advanced level like graphs; etc. -
Reset password after first successful login in Django python
I am building an web application using existing Auth features in Django where admin create user profile with username and password. Admin created user name and password will be given to user to login. So for security reasons I need to ask user to reset password (given by admin) after user's first successful login. To reset password, I will be displaying template where user should be entering only new password and new password again for confirmation. This new password will be updated in sqlite database. So whenever admin changes the users password. I need to ask users to reset password after first successful login. I know this if off topic for stacoverflow and for reasons I couldnt post a question in StackExchange. Please refer me or help will be appreciated. -
How to Setup Divio CLI using WSL 2 for Windows 10?
So I just tried to setup Divio CLI via WSL 2 Terminal. My WSL 2 setup I'm using is based on Ubuntu 18.04.4 LTS, bionic. So everything was working well initially: I typed divio login and add my access token in the CLI, worked well. Then, I typed divio doctor, all checks out: Login, Git, Docker Client, Docker Machine (I installed it separately via the WSL terminal), Docker Compose, Docker Engine Connectivity, Docker Engine Internet Connectivity, and Docker Engine DNS Connectivity until I typed this command divio -d project setup sample-djangocms-project and got this error: Error: Resource not found. You are logged in as '#########@#####.com', please check if you have permissions to access the ressource Can someone tell me why this happened? I am kinda stuck. And what should I do next? -
User provided email over the landing page is not showing in the database in Django
I am trying to put a subscribe email form on my landing page, however, I am not able to see the input email addresses on my admin(backend). Why it's not writing user-provided email input to my database? base.html <form method="post" > {% csrf_token %} <label >Your Email: </label> <input type="text"> <input type="submit" value="Submit"> </form> models.py from django.db import models from django.urls import reverse # Create your models here. class EmailSubmit(models.Model): email_name=models.EmailField(max_length=30) forms.py from django import forms from .models import EmailSubmit class EmailForm(forms.ModelForm): class Meta: model=EmailSubmit fields=[ 'email_name', ] views.py from django.shortcuts import render from .forms import EmailForm def index(request): return render(request, 'base.html') def email_post(request): form = EmialForm(request.POST or None) if form.is_valid(): form.save() context={ 'form':form } return render(request, 'base.html', {'form': form}) so when the user puts the email and submit, the page refreshes but nothing shows up on the backend. What is wrong with my code here? -
AJAX form submission to Django Class View
I'm trying to submit data to model using Ajax, its gives a 403 (Forbidden), view I'm using is a Class View. Things works fine without Ajax. How to do the same with ajax ? My Url : path('add_to_cart/<slug>', views.AddToCartView.as_view(), name='add_to_cart'), My View : class AddToCartView(LoginRequiredMixin, View): model = Wishlist @method_decorator(csrf_exempt) def get(self, request, *args, **kwargs): print(self.request.user) print(self.kwargs['slug']) wished_product = get_object_or_404(Product, slug=self.kwargs['slug']) product,created = self.model.objects.get_or_create(product=wished_product, customer = self.request.user) return HttpResponse(status=201) and ajax call $('.buy').click(function(e){ e.preventDefault(); let _this = $(this); var slug = _this.data('id'); $.ajax({ type : 'POST', url : 'add_to_cart/'+ slug +'/', success: function(data){ if(data.success = true){ _this.addClass('clicked'); } }, async : false, error : function(data){ alert(data); } }) }); When i use 'POST' instead of 'GET' in Ajax type it gives 404 (Not Found) -
WebSocket server refusing all connections in Django Channels
I was doing a chat with django (backend) and react (frontend). I use Django Channels to create the WebSocket server, but it isn't working : when trying to connect with React, it throws Forums.jsx:61 WebSocket connection to 'ws://localhost:8000/forums/divers/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET in the navigator console. This morning it was working, but this afternoon, after having closed and reopened the 2 servers, it isn't working. I only started a system to store the messages in the database during this time. The consumer: from channels.generic.websocket import WebsocketConsumer import json from .models import Message class ChatConsumer(WebsocketConsumer): async def connect(self): self.forum = self.scope["url_route"]["kwargs"]["forum"] # Join room group await self.channel_layer.group_add( self.forum, self.channel_name ) print("connect func") self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.forum, self.channel_name ) async def receive(self, text_data=None, bytes_data=None): text_data_json = json.loads(text_data) message = text_data_json['message'] print(message) await self.channel_layer.group_send( self.forum, { 'type': 'chat_message', 'message': message } ) async def chat_message(self, event): message = event['message'] #await sync_to_async(Message.objects.create)(message=message["message"], ) # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) opening of WebSocket client: class Forum extends Component { constructor(props) { super(props) ... this.URL = constants.BACKEND_WS + "/forums/" + this.state.forum + "/"; this.ws = new WebSocket(this.URL) } componentDidMount() { console.log("didmount"); this.ws.onopen = () => { … -
One to One vs field in same models django
I have created two templates I have the extended template De user (AbsctractUser) and the template (Score) with the field total_score. From what I could understand about the django cache with redis is that as long as the line is not modified, redis keeps the information in cache. The total_score field will be updated regularly, like 100 times every 10 minutes if it is added in the AbstractUser template, this one will force redis to regularly update the user's cache at each page change (view), whereas if I create a second Score template with a OnetoOne relationship, this one will be updated only on the 2 pages concerned or the view loads the Score model. Or I can put directly the field total_score in my abstract user and update it regularly. But for me I lose the efficiency of redis for the Abstract User model. I'd like to know if my reasoning is correct... What I could read is that a OnetoOne is useful to extend an already existing table, but for the creation of a new project it is necessary to avoid the OnetoOne, and to add directly the field in the model. so I'm in a fog. Thank … -
custom.methods.wrap didn't return an HttpResponse object. It returned None instead
What's wrong in my code.. ? I'm returning an HttpResponse conditionally, yet I keep getting an error decorators.py def has_permission_view(): def decorator(view_func): def wrap(request, *args, **kwargs): if request.user.role == 'admin': if not hasattr(request.user, 'institute'): messages.add_message( request, messages.WARNING, "Please Add Your Institute Information") return HttpResponseRedirect(reverse('accounts:add_institute')) elif not hasattr(request.user.institute, 'device'): messages.add_message( request, messages.WARNING, "Please Add Your Attendance Device Information") return HttpResponseRedirect(reverse('accounts:device')) elif request.user.role == 'employee': return HttpResponseRedirect(reverse('accounts:profile')) return wrap return decorator views.py @login_required @has_permission_view() def index(request): context = {} d = request.user.institute.device zk = ZK(d.ip, d.port, timeout=5, password=0, force_udp=False, ommit_ping=False) try: conn = zk.connect() context['object'] = conn except Exception as e: messages.add_message(request, messages.WARNING, e) return render(request, 'index.html', context) I Got This Error Message The view custom.methods.wrap didn't return an HttpResponse object. It returned None instead. -
Can I do work after the Django request cycle?
I have a SLO to return responses from my django app in 3 seconds, but occasionally the work that I'm doing within a request takes longer than this. The extra work can be done asynchronously, so I'm looking into celery. BUT, the work logically belongs with the request and it would be nice if I didn't have to go to all the extra work of setting up a celery queue. I don't have much traffic and I don't mind taking up just a little more time with my uwsgi worker. Is there any condoned way (or perhaps even un-condoned way) to do work after the response has been returned but before leaving the request cycle? -
Django - exclude elasticsearch objects from search view on bool change
I want to exclude specific elements out of my (elastic)search results view. Imagin you have a onlineshop only with unique items out of diffrent models which getting sold and if smb. buys the object the sold boolan field changes to true at the database. At the moment the objects becomes sold it should get excluded from the search results. this is how far a came till now but I dont know how I can filter e.g. "z = ZDocument" for the field "sold" and only show objects where sold=False views.py example def search(request): if request.method == "GET": searchquery = request.GET.get('searchquery') page = request.GET.get('page') if searchquery: x = XDocument.search().query("multi_match", query=searchquery, fields=["title", "content", "tag"]).to_queryset() y = YDocument.search().query("multi_match", query=searchquery, fields=["title", "content", "tag"]).to_queryset() z = ZDocument.search().query("multi_match", query=searchquery, fields=["title", "content", "tag"]).to_queryset() searchquery = list( sorted( chain(x, y, z), key=lambda objects: objects.pk )) else: searchquery = '' ... return render... thanks for reading -
Django, how do i compare leftovers
I have two models, warehouse and products. Subcategories are Hotdog value and There are two values in the warehouse, sausage and bun, I indicated the quantity to them I connected them using ManyToMany, now I need to make it show how many pieces there are. Example models.py class Stock(models.Model): title = models.CharField(max_length=255) limit = models.IntegerField() def __str__(self): return self.title class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=255) price = models.IntegerField() stock = models.ManyToManyField(Stock) def __str__(self): return self.title views.py {% for item in subcategories %} <a href="#" class="c-item"> <h2>{{ item.title }}</h2> <h4> {{ item.price }} сом <span class="badge badge-danger">20 pieces</span> </h4> </a> {% endfor %} -
Why does this API request work in Postman but it raises an error in Django test?
I post to my API to create an account from Postman { "email": "snifter@gmail.com", "display_name": "outrageous canteloupe", "password": "GramDaddyff!!5" } It works, and a new account is registered in the databse. Then I try to make the same request from a Django test. class AccountAPITestCase(TestCase): def setUp(self): pass def test_create_account(self): c = Client() response = c.post('/accounts/', { "email": "snifter@gmail.com", "display_name": "outrageous canteloupe", "password": "GramDaddyff!!5", }) account = Account.objects.get(display_name='big_ouch') self.assertTrue(account) And I get the following error. ====================================================================== ERROR: test_create_account (accounts.tests.AccountAPITestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/mcm66103/Documents/python/photo-contest-BE/accounts/tests.py", line 28, in test_create_account "password": "use_in_migrationsDaddyff!!5", File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/django/test/client.py", line 526, in post response = super().post(path, data=data, content_type=content_type, secure=secure, **extra) File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/django/test/client.py", line 356, in post secure=secure, **extra) File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/django/test/client.py", line 421, in generic return self.request(**r) File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/django/test/client.py", line 496, in request raise exc_value File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/rest_framework/viewsets.py", line 114, in view return self.dispatch(request, *args, **kwargs) File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/Users/mcm66103/.envs/photo-contest-BE/lib/python3.7/site-packages/rest_framework/views.py", line 476, in … -
Unrecognized day of week error in python-Cron tab
I am working on a Django app. I was using crontab for jobs in background. Here is an example of my code from crontab import cronTab pddays=[1,2,3,4] cron = CronTab(user=username) job = cron.new(command=“curl http://***********”) job.dow.on(str(pddays)[1:-1]) cron.write() But when I execute it I get the error - ValueError: Unrecognized Day off week ‘1,2,3,4’ -
Can't show variables inside Django blocks
I have a simple parent template like this that uses Django blocks //base.html <!doctype html> <body> {% block content %} {% endblock %} </body> </html> But whenever I try to print the variables passed by views.py inside the block nothing is neither displayed nor received, when I put all the html code together in a single file without a parent template it works perfect. This is the basic idea of the block //block.html {% extends 'folder/base.html'%} {% block content %} <h1> {{data}} </h1> {% endblock %} And this is the content of the views.py function: def function(request): return render(request,'folder/block.html',{'data':'someRandomString'}) -
Django signals not working inspite of putting everything in place
My Case In my case User is the default django user model and I've created a Profile to add more details to the User model. To achieve Now what i want is that whenever I create a new User a Profile for that user should automatically get created. I've done I have checked my signals.py file and also imported the signals in apps.py file but still nw Profile is not being created for each new user being created :( Code below I have provided the code in my signals.py and apps.py file below. Please ask me if you need some more code and thanks in advance :) Here is my signals.py file #This is the signal that will be sent from django.db.models.signals import post_save #This is the object which will send the signal from django.contrib.auth.models import User #This will receive the signal from django.dispatch import receiver #We need this to perform operations on profiles table from .models import Profile #This function creates new profile for each user created @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) #This function saves those newly created profiles @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() Here is my apps.py file from django.apps import …