Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make sequential signup pages with Django allauth?
I currently have a single page signup form implemented with allauth from django.contrib.auth.models import AbstractUser class User(AbstractUser): email = models.EmailField(_('Professional email address'), unique=True) username = models.CharField(_("User Name"), blank=False, max_length=255, unique=True) first_name = models.CharField(_("First Name"), null=True, max_length=255, default='') last_name = models.CharField(_("Last Name"), null=True, max_length=255, default='') country = CountryField(_("Country of Practice"), blank_label='(Country of Practice)', blank = False, default='GB') terms = models.BooleanField(verbose_name=_('I have read and agree to the terms and conditions'), default=False) def get_absolute_url(self): return reverse( "users:detail", kwargs={"username": self.username} ) objects = UserManager() And this is the forms.py class UserCreationForm(forms.UserCreationForm): error_message = forms.UserCreationForm.error_messages.update( {"duplicate_username": _("This username has already been taken.")} ) username = CharField(label='User Name', widget=TextInput(attrs={'placeholder': 'User Name'})) class Meta(forms.UserCreationForm.Meta): model = User fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2', 'terms'] field_order = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2', 'terms'] def clean_terms(self): is_filled = self.cleaned_data['terms'] if not is_filled: raise forms.ValidationError('This field is required') return is_filled def clean_username(self): username = self.cleaned_data["username"] if self.instance.username == username: return username try: User._default_manager.get(username=username) except User.DoesNotExist: return username raise ValidationError( self.error_messages["duplicate_username"] ) I would like however for the first sign up page to have a ‘next’ button at the bottom and then there would be a second page where the user input separate details (the data input here … -
How can i calculate bmi , protien , carb , calorie , body fat in django
enter image description here I want to calculate all of them return results below submit button -
KeyError: REQUEST_METHOD with Django + uWSGI + nginx + docker
I've built a django REST-API and I want to deploy it on my server. Everything works fine in local dev environment. But on my server I have an error with nginx doesn't pass uwsgi_params correctly (I think). The error It seems to me that my configs work fine, since when I access my domain name, the logs appear on the server. However, the error seems to me that nginx doesn't pass the reqeust_method to wsgi in django. I did found another post here which had the same error, however, I double checked the uwsgi_params file and it's not empty. So I have no clue. simuzones_server_web | Traceback (most recent call last): simuzones_server_web | File "/home/tx7093/.local/lib/python3.8/site-packages/django/core/handlers/wsgi.py", line 130, in __call__ simuzones_server_web | request = self.request_class(environ) simuzones_server_web | File "/home/tx7093/.local/lib/python3.8/site-packages/django/core/handlers/wsgi.py", line 78, in __init__ simuzones_server_web | self.method = environ["REQUEST_METHOD"].upper() simuzones_server_web | KeyError: 'REQUEST_METHOD' simuzones_server_web | [pid: 11|app: 0|req: 1/1] () {48 vars in 977 bytes} [Sun Jan 22 13:28:53 2023] => generated 0 bytes in 5 msecs ( 500) 0 headers in 0 bytes (0 switches on core 0) simuzones_server_web | Traceback (most recent call last): simuzones_server_web | File "/home/tx7093/.local/lib/python3.8/site-packages/django/core/handlers/wsgi.py", line 130, in __call__ simuzones_server_web | request = self.request_class(environ) simuzones_server_web | File … -
How to fix csrf token problem after deployment on railway of django project
Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: Origin checking failed - https//:webiste does not match any trusted origins. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template’s render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login. I added csrf_token_origin but it didn't worked for me and currently i am using python 3.11.0 -
How do I reference a path (URL) in Django? But this path is not in the base app, but in another app
In the base app, which I call it "mywebsite" (the one that contains the settings of the django project), has the urls.py file. But I do not want to reference this file, I want to reference a urls.py in another app, which I call it "account". For the base file, I would reference as {% url'login' %}, for example. How do I reference to the other one? Maybe {% account.url 'login' %}? I tried {% account.url 'login' %} and {% account/url 'login' %} -
How to write permissions in a viewset with conditional statements in DRF?
I have a viewset written in DRF: class MyViewSet(ModelViewSet): serializer_class = MySerializer queryset = models.MyClass.objects.all() def get_serializer_class(self): permission = self.request.user.permission if permission=='owner' or permission=='admin': return self.serializer_class else: return OtherSerializer def perform_create(self, serializer): permission = self.request.user.permission if permission=='owner' or permission=='admin': serializer.save() else: employee = models.Employee.objects.get(user=self.request.user) serializer.save(employee=employee) Here, I am using the following statements in both get_serializer_class and perform_create which looks like a repetitive code: permission = self.request.user.permission if permission=='owner' or permission=='admin': Is there any way to write it once and then use it as a permission_class somehow? -
How to add products to cart using sessions as a guest in django
settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'my_cache_table', } } SESSION_ENGINE = "django.contrib.sessions.backends.cache" models.py class Product(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(default='-') description = models.TextField() unit_price = models.FloatField() inventory = models.IntegerField() last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT) promotions = models.ManyToManyField(Promotion) class Cart(models.Model): created_at = models.DateTimeField(auto_now_add=True) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() I want to add the products in the cart using session through cache. how can I make a key named as 'cart' in request.session and add those product's id in it. I initially tried to set 'cart' key using request.session.setdefault('cart', list()) but then I read the django documentation and it says that the items should be in the form of dictionaries(according to conventions). So what can I do to store the products in the cart for guest users? -
Raise conditional permission error in get_queryset DRF
I want to get all users of an organization by uuid. I am following REST standards so I want my url to look like 'organizations/uuid/users/'. If super admin hits this API, it should be allowed but If an admin user tries using this API, then it should only allow if the admin belongs to the same organization for which users are requested. I used ListAPIView generic view class and I was able to get list of all users in an organization from admin of different organization but it still returns info when it should return 403 error. urls.py path('organizations/<uuid:pk>/users/', OrganizationUsersView.as_view()), views.py class OrganizationUsersView(ListAPIView): serializer_class = UserSerializer permission_classes = (IsAuthenticated, IsSuperAdmin|IsAdmin,) def get_queryset(self): uuid = self.kwargs['pk'] if self.request.user.role == 'admin': if self.request.user.org.id != uuid: return IsOrganizationAdmin() org = Organization.objects.get(id=uuid) return User.objects.filter(org=org) models.py class Organization(models.Model): name = models.CharField(max_length=255, null=False) class User(AbstractBaseUser): .... other fields .... org = models.ForeignKey(Organization, on_delete=models.CASCADE, null=False, related_name='users') -
How to create a nested list of parent/child objects using a function?
everyone! I'm new to Python and Django and I've encountered a problem I can't solve on my own for quite a long time. I have a database that consists of a number objects and each object has one parent (except the first, the 'root' object) and no / one / several children. I need to create a fuction that takes some object and returns this object and recursively its descendants like this: arr = ['States', ['Kansas', ['Lawrence', 'Topeka', ['Some Topeka Street', ['Some House on Some Topeka Street']]], 'Illinois', ['Chicago', 'Springfield']]] I want to get this kind of data structure and use it on Django's unordered list filter. As far as I know about algorithms I should make up a function that somehow should work like this: def make_nested_list(item): if not item.children: # basic case # do something else: for child in item.children: # recursive case # do something make_nested_list(child) # function calls itself # maybe do something here # and finally return self-nested list return result Everything I try turns out to be a mess. How can I do that? -
Django celery-beat dont restart beat
There is a site parsing service that sends several requests to a url with parameters, and this process lasts 30 minutes, if at that time when the request to restart the beat is sent, then the task disappears (stops) and you have to send it again and manually start the process, how can this be avoided so that the request is sent and I create new tasks and safely restart the beat. -
Stripe payment do something when payment is successfull Django
I have an app about posting an advertises and by default i made an expiration date for every advertise (30 days) now i wanna use stripe to extend the expiration date. what i have so far is the checkout but i want when the payment i success i update the database. my checkout view : class StripeCheckoutView(APIView): def post(self, request, *args, **kwargs): adv_id = self.kwargs["pk"] adv = Advertise.objects.get(id = adv_id) try: adv = Advertise.objects.get(id = adv_id) checkout_session = stripe.checkout.Session.create( line_items=[ { 'price_data': { 'currency':'usd', 'unit_amount': 50 * 100, 'product_data':{ 'name':adv.description, } }, 'quantity': 1, }, ], metadata={ "product_id":adv.id }, mode='payment', success_url=settings.SITE_URL + '?success=true', cancel_url=settings.SITE_URL + '?canceled=true', ) return redirect(checkout_session.url) except Exception as e: return Response({'msg':'something went wrong while creating stripe session','error':str(e)}, status=500) Models: # Create your models here. class Advertise(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="advertise") category = models.CharField(max_length= 200, choices = CATEGORY) location = models.CharField(max_length= 200, choices = LOCATIONS) description = models.TextField(max_length=600) price = models.FloatField(max_length=100) expiration_date = models.DateField(default = Expire_date, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) #is_active class Meta: ordering = ['created_at'] def __str__(self): return self.category So what i want to do is check if the payment is successful nad if so i extend … -
how to connect to a sql server database remotely via internet in pythonConnect to a database not on the same network with python/django
I would like to connect to a server on a machine located on a different network from mine in order to connect to its database. How to do? Until now I only worked with databases located on the same local network but now I have to interact with those located on another server. I develop with django/python. The image I added below is the connection to several databases but on a local network, but as I said I want to interact with other databases located in another city. -
Django: How do I create a form of model A for each instance of model B
I am trying to create an app, where the user fills out forms (model B). The forms are based on variables (model A), which are defined by the admin. The form should save the input in model B (i.e. input values) and therefore show the name/label of model A (i.e. the variable name) for each instance of A and the corresponding fields of B (the input value). I am stuck with showing each input form separately. Technically this works, but creates a terrible user experience. How do I render all input forms for each variable on one page? I would appreciate any help greatly! Model A (variables): class Variable(models.Model): visit = models.ForeignKey(Visit, on_delete=models.CASCADE, default="") var_id = models.CharField(max_length=20, default="") var_label = models.CharField(max_length=20, default="") NUM = 'NUM' INT = 'INT' CHAR = 'CHA' DATE = 'DAT' BOOL = 'BOO' DATA_TYPES = [ (NUM, 'Numeric'), (INT, 'Integer'), (CHAR, 'Character'), (DATE, 'Date'), (BOOL, 'Boolean'), ] widget_type = models.CharField( max_length=3, choices=DATA_TYPES, default=CHAR, ) max = models.FloatField(max_length=20, default=0) min = models.FloatField(max_length=20, default=10) pub_date = models.DateTimeField('date published', default=timezone.now) description = models.CharField(max_length=200, default="") def __str__(self): return self.var_id Model B (input values): class InputValue(models.Model): submission = models.ForeignKey(Submission, on_delete=models.CASCADE, default="") variable = models.ForeignKey(Variable, on_delete=models.CASCADE, default="") value_char = models.CharField(max_length=128, default="NA") value_numeric … -
Updating the URLField of model with JavaScript
I have a page that displays some information about website admins such as username, skills, Instagram profile and bio. The admins are able to edit their profile information and the update is being saved using JavaScript fetch. When I click on the save button everything except the Instagram profile which is a URLField gets updated. For Instagram element to be updated I need to reload the page. How can I make it get updated without reloading the page? Everything is correct in the console log. about.js: document.addEventListener("DOMContentLoaded", function(){ const button = document.querySelectorAll("#edit_profile") button.forEach(function(button){ button.onclick = function(){ const username = document.getElementById(`username_${memberID}`); const skills = document.getElementById(`skills_${memberID}`); const bio = document.getElementById(`bio_${memberID}`); var instagram = document.getElementById(`instagram_${memberID}`).href; let edit_username = document.createElement("textarea"); edit_username.setAttribute("rows", "1"); edit_username.innerHTML = username.innerHTML edit_username.id = `edit_username_${memberID}`; edit_username.className = `form-control username ${usernameID}`; let edit_skills = document.createElement("textarea"); ... let edit_instagram = document.createElement("textarea"); edit_instagram.setAttribute("rows","1"); edit_instagram.innerHTML = instagram; edit_instagram.id = `edit_instagram_${memberID}`; edit_instagram.className = "form-control social-media"; const saveButton = document.createElement("button"); saveButton.innerHTML = "Save"; saveButton.id = `saveButton_${memberID}`; saveButton.className = "btn btn-success col-3"; saveButton.style.margin = "10px"; document.getElementById(`edit_${memberID}`).append(edit_username); ... document.getElementById(`edit_${memberID}`).append(edit_instagram); document.getElementById(`edit_${memberID}`).append(saveButton); // When the save button is clicked saveButton.addEventListener("click", function(){ edit_username = document.getElementById(`edit_username_${memberID}`); ... edit_instagram = document.getElementById(`edit_instagram_${memberID}`); fetch(`/edit_profile/${memberID}`,{ method: "POST", body: JSON.stringify({ username: edit_username.value, skills: edit_skills.value, instagram: edit_instagram.value, bio: edit_bio.value, … -
Django static and media files + DigitalOcean Spaces
Hy everyone! This is my first time trying to connect a Django project (which is in DigitalOcean App Platform) with DigitalOcean Spaces. I created 3 folders inside Spaces: static, media and staticfiles. I noticed however that when I run 'collectstatic', all static files are copied not to the 'staticfiles' folder but to the root-level. If I visit the domain name, the static files are visible: both the images and the css and javascript files. Conversely, media files are not displayed. Inspecting the code via google developer tools I noticed that the src attributes of the img tags try to find both static and media files at the root level. This is what I tried to do. I installed 'django-storages', included it in 'INSTALLED_APPS' and then put this code in settings.py: AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') # AWS_S3_CUSTOM_DOMAIN = os.getenv('AWS_S3_CUSTOM_DOMAIN') AWS_S3_REGION_NAME = '<REGION_NAME>' AWS_S3_ENDPOINT_URL = os.getenv('AWS_S3_ENDPOINT_URL') DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_DIRS = [BASE_DIR / "static"] MEDIA_URL = 'https://<REGION_NAME>.digitaloceanspaces.com/<BUCKET_NAME>/media/' STATIC_URL = 'https://<REGION_NAME>.digitaloceanspaces.com/<BUCKET_NAME>/static/' MEDIA_ROOT = 's3://<REGION_NAME>.digitaloceanspaces.com/<BUCKET_NAME>/media' STATIC_ROOT = 's3://<REGION_NAME>.digitaloceanspaces.com/<BUCKET_NAME>/staticfiles' In 'django-storages' docs I saw that STATICFILES_STORAGE should be like this: STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' but this way the static files were not loaded (css, images, js ecc.) -
While adding my project to GitHub, do I also have to add the virtual environment folder and subsequently commit and push it or I can skip it?
I just finished with my project and was going to put it on GitHub but I have this doubt regarding the venv folder. Below is the screenshot of my folder-structure; Please guide me as this is my first time using GitHub and this is my first project too. -
Nginx with Django and Gunicorn working with IP but not with domain name
I have been trying to setup my Django backend since 2days but i can't get it to work with my domain name. I have the Next Frontend on Nginx(Port :80) too but it seems to work fine with domain name. But i did the same setup in backend with port 8000 i can't access it using the domain name but works fine with IP. I have tried everything found on the internet but nothing seems to work. Config for the frontend (Working with domain) server{ listen 80; listen [::]:80; listen 443 ssl; include snippets/snakeoil.conf; server_name {domainName}; location = /favicon.ico { access_log off; log_not_found off; } location / { # reverse proxy for next server proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_headers_hash_max_size 512; proxy_headers_hash_bucket_size 128; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } } Config for backend (Not working with domain name) server { listen 8000; listen [::]:8000; server_name dev.liqd.fi ipaddress; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/backend/lithexBackEnd; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Allowed Hosts ALLOWED_HOSTS = ['localhost','127.0.0.1','ip address','*.domain.com','domain.com'] The Gunicorn has been setup and tested and seems to be working fine . The error log of … -
How to make forms which users can add | Django
I want to make something like google forms which users can make themselfs. I want just simple html string forms which can reveal answer and check is it right instantly. No matter how users will create forms, but only using webpage. Without additional connecton to DB. Using only one field in column in DB. Maybe forms can be like this using just html (best variation) -
Optimise django manytomany relation
I was wondering if there is a way to make this more optimised. class AppTopic(models.Model): topic = models.CharField(max_length=20) # lowercase (cookies) class UserTopic(models.Model): topic = models.CharField(max_length=20) # Any case (cOoKiEs) app_topic = models.ForeignKey(AppTopic) # related to (cookies -> lowercase version of cOoKiEs) class User(models.Model): topics = models.ManyToManyField(UserTopic) # AppTopic stored with any case The goal is to have all AppTopics be lowercase on the lowest level, but I want to allow users to chose what capitalisation they want. In doing so I still want to keep the relation with it's lowercase version. The topic on the lowest level could be cookies, the user might pick cOoKiEs which should still be related to the orignal cookies. My current solution works, but requires an entirely new table with almost no use. I will continue using this if there isn't really a smarter way to do it. -
django query: stuck trying to display only one instance of the model per id
I am writing a conversation module for a django app and I am failing desperately at buildin g a side menu that shows for each conversation: the name of the recipient the last message in the conversation the timestamp of that last message I am struggling to write an accurate query. conversations = ChatRoom.objects.filter(building=building.building_id, participants__in=[user]).prefetch_related( 'participants','chat_set').order_by('-chat__timestamp') the issue with this query is that it returns one chatroom object per message, and therefore in template the following code: <ul class="flex flex-col space-y-1 mt-4 -mx-2 overflow-y-auto" style="height:300px"> <h2 class="my-2 mb-2 ml-2 text-lg text-gray-600">Chats</h2> {% for convo in conversations %} <li> {% if convo.chat_set.last.content %} {% for participant in convo.participants.all %} {% if participant.id != request.user.id %} <a href="{% url 'room' room_id=convo.id %}" class="flex items-center px-3 py-2 text-sm transition duration-150 ease-in-out border-b border-gray-300 cursor-pointer hover:bg-gray-100 focus:outline-none"> <div class="w-10 h-10 rounded-full border-2 border-black flex justify-center items-center m-2"> <span> {{ participant.username|first|upper }}</span> </div> <div class="w-full pb-2"> <div class="flex justify-between"> <span class="block ml-2 font-semibold text-gray-600"> {{ participant.username }}</span> <span class="block ml-2 text-sm text-gray-600">{{ convo.chat_set.last.timestamp}}</span> </div> <span class="block ml-2 text-sm text-gray-600">{{ convo.chat_set.last.content }}</span> </div> </a> {% endif %} {% endfor %} </li> {% for %} {% endfor %} </ul> shows one line per message sent, instead of … -
Case sensitves django
I tried to put this code to deactivate the sensitivity of the characters when logging in, but it does not work. What is the problem with it? It still appears to me. Please consider the sensitivity of the characters I want to use this method. I do not want to use the backend method Please help me find the problem class CustomUserManager(UserManager): def get_by_natural_key(self, username): return self.get(username__iexact=username) class User(AbstractBaseUser): """ Decapolis main User model """ username = models.CharField(max_length=40, unique=True) email = models.CharField(max_length=40, unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) company = models.ForeignKey(settings.COMPANY_MODEL, on_delete=models.CASCADE, related_name='user_company', null=True, blank=True) roles = models.ManyToManyField(Role, blank=True) objects = CustomUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def has_role(self, role_name): """ Check user has role :param role_name: role name to check :type role_name: str :return: True or False :rtype: bool """ return True if role_name in self.roles else False def has_perm(self, perm, obj=None): """ Does the user have a specific permission? Not implemented yet :param perm: permission to check :type perm: str :param obj: object to check :type obj: :return: :rtype: """ # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): … -
I can't create another custom user model to override the one I had created before, when I do and perform migrations it is clashing with the new one
I had created a customer user model to override the already existing one Django provides, but I want to make a lot of changes on it including changing the name, like completely starting over in another app but in the same project but looks like I'm getting errors while trying to do migrations. Thought that if I changed the database and performed migrations it would work but it didn't, they say this: ERRORS: user.UserAccountModel.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'user.UserAccountModel.groups' clashes with reverse accessor for 'userAccount.UserModel.groups'. HINT: Add or change a related_name argument to the definition for 'user.UserAccountModel.groups' or 'userAccount.UserModel.groups'. user.UserAccountModel.user_permissions: (fields.E304) Reverse accessor 'Permission.user_set' for 'user.UserAccountModel.user_permissions' clashes with reverse accessor for 'userAccount.UserModel.user_permissions'. HINT: Add or change a related_name argument to the definition for 'user.UserAccountModel.user_permissions' or 'userAccount.UserModel.user_permissions'. userAccount.UserModel.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'userAccount.UserModel.groups' clashes with reverse accessor for 'user.UserAccountModel.groups'. HINT: Add or change a related_name argument to the definition for 'userAccount.UserModel.groups' or 'user.UserAccountModel.groups'. userAccount.UserModel.user_permissions: (fields.E304) Reverse accessor 'Permission.user_set' for 'userAccount.UserModel.user_permissions' clashes with reverse accessor for 'user.UserAccountModel.user_permissions'. HINT: Add or change a related_name argument to the definition for 'userAccount.UserModel.user_permissions' or 'user.UserAccountModel.user_permissions'. Hint: My first custom model was 'UserModel' in userAccount app and now i changed it to 'UserAccountModel' in user … -
Django Rest Framework fail on setting a new context to the serializer
Django time: I am facing an issue with providing a context to the serializer: class CommentSerializer(serializers.ModelSerializer): likes = CustomUserSerializer(many=True,source='likes.all') class Meta: fields = 'likes', model = models.Comment def get_user_like(self,obj): for i in obj.likes.all(): if self.context['user'] in i.values(): return self.context['user'] in the view: class CommentView(viewsets.ModelViewSet): serializer_class = serializer.CommentSerializer def get_serializer_context(self): #adding request.user as an extra context context = super(CommentView,self).get_serializer_context() context.update({'user':self.request.user}) return context as you can see, i have overridded get_serializer_context to add user as a context however, in the serializer side, i am getting KeyError:'user' means the key does not exist, any idea how to set a context? -
How can I change titles in action section in Django admin panel?
I want to change titles in action section in Django admin. How can I do that? -
Is it database level or related to programming
Hello all of my friends I was in a job interview and the interviewer asked me this question "Suppose we have to get all the members of a database table and not all of them fit in RAM, what would you do?" .I didn't know the exact answer and the only answer that came to my mind was to use a generator and I would like to know the answer of the people who worked in this field. So the following are my questions. 1)What is the answer to the interviewer's question (please explain a bit) 2)Is Generator in python use just for Put and Post Method or is used to for Get method in Django (i mean generator just use for write and change database or used for get a list of items too )(When I was reading about the topic of the generator, it was always said that instead of bringing the items to the RAM at once, the generator brings and changes the items one by one and stores them in the database and goes to the next item, and i thought that whenever we want change or update go to the generator)