Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ReadOnlyError in Django apllication with Redis and DjangoCannels
I have a Django app using DgangoChannels, Djangochannelrestframework. It establishes a websocket connection with ReactJS frontend. As channel layers I use Redis like that CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("redis", 6379)], }, }, } Redis and Django runs in docker. My redis docker setup is redis: image: "redis:7.0.4-alpine" command: redis-server ports: - "6379:6379" networks: - nginx_network When I run my app on production server everything works for 5-8 hours. But after that period, if Django app trying to send a message via ws if falls with the error ReadOnlyError at /admin/operations/operation/add/ READONLY You can't write against a read only replica. Request Method: POST Request URL: http://62.84.123.168/admin/operations/operation/add/ Django Version: 3.2.12 Exception Type: ReadOnlyError Exception Value: READONLY You can't write against a read only replica. Exception Location: /usr/local/lib/python3.8/site-packages/channels_redis/core.py, line 673, in group_send Python Executable: /usr/local/bin/python Python Version: 3.8.13 Python Path: ['/opt/code', '/usr/local/bin', '/usr/local/lib/python38.zip', '/usr/local/lib/python3.8', '/usr/local/lib/python3.8/lib-dynload', '/usr/local/lib/python3.8/site-packages'] Server time: Tue, 02 Aug 2022 08:23:18 +0300 I understand that it somehow connected with Redis replication, but no idea why if falls after period of time and how to fix it -
Nested Serializer save post foreign key in django
In my project, the relationship between Product and Group is ManytoOne. When I tried to post a new product, it cannot work. I'm sure there are more issues with this code and I will appreciate a detailed answer, because I am new to Django and Python. Thank you in advance. models.py class Group(models.Model): productType = models.CharField(max_length=100) intervalTime = models.IntegerField() created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True,editable=False) def __str__(self): return self.productType class Product(models.Model): productName = models.CharField(max_length=255) color = models.CharField(max_length=255) group = models.ForeignKey(Group, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True,editable=False) def __str__(self): return self.productName serializers.py class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('id','productType','intervalTime') class ProductSerializer(serializers.ModelSerializer): group = GroupSerializer(many=False) class Meta: model = Product fields = ('id','productName','color','group') def create(self, validated_data): group = validated_data.pop('group') product = Product.objects.create(**validated_data) for group_instance in group: Group.objects.create(**group_instance, product=product) return product views.py @api_view(['POST']) def createProduct(request): serializer = ProductSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) -
Creating an object in nested serializer giving an error of bad request "owner is required"?
This is my first time dealing with nested serializers and it gives me an error "owner" is required while creating a post. Why is that? class CreatePostView(APIView): permission_classes = [IsAuthenticated] parser_classes = [MultiPartParser] def post(self, request, *args): user = request.user data = request.data data['owner'] = user print(data) serializer = PostSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) PostSerializer: class PostSerializer(serializers.ModelSerializer): owner = UserSerializer() comments = CommentSerializer(many=True, read_only=True) class Meta: model= Post fields = ("id", "img", "posted_at", "caption", "owner", "comments") Post model: class Post(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") img = models.ImageField(upload_to=post_img_url, default="default.jpg", max_length=200) caption = models.CharField(max_length=100, null=True, blank=True) posted_at = models.DateTimeField(auto_now_add=True, blank=True) objects = models.Manager() current_user_posts = CurrentUsersPosts.as_manager() class Meta: ordering = ("-posted_at",) def __str__(self): return f"{self.img} posted by {self.owner} at {self.posted_at}" console: <QueryDict: {'owner': ['9'], 'img': [<InMemoryUploadedFile: treeHouse.jpg (image/jpeg)>]}> Bad Request: /api/posts/upload/ [02/Aug/2022 11:14:01] "POST /api/posts/upload/ HTTP/1.1" 400 37 -
In Django templates, can I write a function or a custom tag to generate a dropdown, so I can reuse the same code in other templates?
I want my django templates models agnostic. Django view will massage the model data and send a list to the template ['item_1', 'item_2', 'item_3', .... 'item_n] In the template, I want to convert this list of items into a HTML dropdown. But since I shall be having this kind of behavior at many places I would like to reuse the code that is transforming the list into the dropdown. How may I do that? -
Django ImproperlyConfigured/ No Patterns / Circular Import Error
I have one base DJango code and recently written a separate Django code (search_me below). Both are working fine separately but while merged the two code then it is giving following Error: ERROR: "django.core.exceptions.ImproperlyConfigured: The included URLconf 'covid19.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import." Base urls.py: from django.conf.urls import url, include from django.contrib import admin from firstApp import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url('admin/', admin.site.urls), url('^$',views.homepage,name='homepage'), url(r'^covid19',views.indexPage,name='index'), url(r'^selectcountry',views.indicountrydata,name='index'), url(r'^segmentation/',include('segmentation.urls')), url(r'^search_me/',include('search_me.urls')), #url(r'^search_me/',views.search_view,name='search_view'), #path(r'^search_me',include('search_me.urls',namespace='search_me')) ] urlpatterns += staticfiles_urlpatterns() search_me urls.py # from django.urls import path from django.conf.urls import url, include from . import views app_name = 'search_me' # urlpatterns = [ # path('', views.search_view , name='search'), # ] urlpatterns = [ url(r'^$', views.search_view, name='search'), ] -
merge dictionary based of condition match
I have a list of multi dictionary currently looks like "results": [ { "message_code": 1002, "module": "Farm Added", "title": { "en": "Farm Added Successfully!" }, "message": { "en": "Time to add Crops to your farm!" }, "icon_link": { "en": null }, "image_link": { "en": null } }, { "message_code": 1002, "module": "Farm Added", "title": { "hi": "खेत सफलतापूर्वक जुड़ गया है!" }, "message": { "hi": "अभी अपने खेत में फसल जोड़ें|" }, "icon_link": { "hi": null }, "image_link": { "hi": null } }, { "message_code": 1003, "module": "Pending task today", "title": { "en": "Check out today's Tasks NOW!" }, "message": { "en": "Tasks are important for your crop health!" }, "icon_link": { "en": null }, "image_link": { "en": null } }, { "message_code": 1003, "module": "Pending task today", "title": { "hi": "आज का कार्य अभी देखें!" }, "message": { "hi": "आपकी फसल के स्वास्थ्य के लिए कार्य महत्वपूर्ण हैं!" }, "icon_link": { "hi": null }, "image_link": { "hi": null } }, I want to merge the dictionary "title", "image", "icon" and "message", columns based on the condition when the "message_code" matches with the other "message_code" and get the desired out as "results": [ { "message_code": 1002, "module": "Farm Added", "title": … -
Django in processing extra method in views.py
I am new to Django, and having a difficulty soting out a problem. My code is processing extra method in views.py even without being called.Below is an example:- When I am cliking on Home button on my page. Landing Page: I am being redirected to correct view method i.e., index. IndexMthod in views.py: After loading the page my code is hitting another method edit content, without being called with a param favicon.io Concern Method which is my concern. Though it is not affecting my django app, but still it's annoying to see extra method being called everytime. Please let me know, if I have done something wrong here or if any more info is required from my end. Thanks in advance. -
How to include a file in Django as a Background cover
So basically, I'm new to Django and I have been experimenting with Django in building my website portfolio. I decided to experiment with Django if I could use python, JS, Bootstrap, CSS and HTML at the same time, all went well till I came to an obstacle which has been a hassle to overcome. Initially, in my static folder, I have a folder called CSS that contains a file of CSS as main.css and another folder within the Static folder, called Images which contains some Jpg images. So after writing my code in my base folder as home.html, I then proceeded to the main.css folder and wrote: *{ margin: 0; padding:0; box-sizing: border-box; } main { font-family: Heebo,sans-serif; } .Landing { min-height: 100vh; background:url("./images/Laptop.jpg"); background-size: cover; } So basically where the initial problem is(Where I labeled #4), when I host my server I was expecting the image to come up in the background of the website, but it didn't. I then proceeded to think it should be a URL or calling problem, so instead of using a URL I tried: <img src="{% static 'images/Laptop.jpeg' %}" > But this at #4 didn't show up on the background of the page either, … -
Django fixture append to existing data
I have a table which contains some data already. Can a fixture be created with new data records and be appended to the existing data in the table, without specifying a pk explicitly? -
Autofill Models in Django
What I'm trying to implement is an invite system while I develop my website, but I'm new to how Django works. For now, I want to be able to create a random string in the admin panel, have those added to the database, and then be required for a user to register. Eventually I want to create a user group system on the front end website where I can generate the strings there versus the admin panel, and then be able to send them out that way, but I'll get to that later. I have the Model showing successfully in the admin panel, but I don't know how to make a text field that's automatically filled out anytime I create a new one and have the string be random each time. class randomString(models.Model): name = models.CharField(max_length=200) random = models.ManyToManyField(get_random_string(length=6)) This is my current code which is throwing out an error, but I assumed that it would, I did it this way just to check and see if it was this simple. I have found out that it's not. -
Django - Special characters in translations
I need to translate a string that contains a non-breaking space ("\xa0"), but I can't find a way to translate this string properly. The translation ignores the special character or doesn't translate the string at all. Eventually I came up with this solution: from django.utils.translation import gettext_lazy as _, pgettext_lazy return _("On {date} ({timesince} ago)")\ .replace(" ago)", "\xa0ago)")\ .replace("(לפני ", "(לפני\xa0")\ .format( date=formats.date_format(value=last_visit_date), timesince=timesince(d=last_visit_date, now=today), ) Which works, but I would prefer to translate the string properly and not replace the translated string after its translation. Notice that English returns the original string without any translation. (I tried to translate the string "On {date} ({timesince}\xa0ago)" but it didn't work) Any ideas? I think maybe I can use "{timesince} ago" as a separate string and then translate it, and then convert only spaces to "\xa0", and only then format {timesince} (which might contain spaces too). What do you think? -
Django Flexible form, how can I secure it?
I know that I make form in the foms.py, put it in the context, and send it to HTML. But I want to make it possible for the user to increase and decrease the form. If I operate with the code I uploaded now, I know that it is very vulnerable to security, so I wonder how I can secure it. def debate_create(request): if request.method == "POST": # validation ckeck # section dictionary for saving request.FILES section_id = dict() # save request.POST content content = request.POST.items() for k,v in content: if k == 'sup_title': sup_title = SuperTitle() sup_title.author = request.user sup_title.super_title = v sup_title.save() sup_title_id = sup_title.id elif 'img' not in k and 'opt' not in k and 'section' in k: sub_title = Subtitle() sub_title.super_title = get_object_or_404(SuperTitle, pk = sup_title_id) sub_title.sub_title = v sub_title.save() # saving subtitle.id to dictionary section_id[f'img_{k}'] = sub_title.id elif 'section' in k and 'opt' in k: opt = SelectOption() opt.sub_title = get_object_or_404(Subtitle, pk = sub_title.id) opt.option = v opt.save() # save request.FILES content for key,item in request.FILES.items(): for image in request.FILES.getlist(key): img = Images() img.images = image img.sub_title = get_object_or_404(Subtitle, pk = section_id[key]) img.save() return render(request, 'polls/test.html') else: # change HTML index.html to debate_form.html after make … -
Kaggle Dataset command returning wrong data
Hello guys please I am trying to download dataset off kaggle through my django app. In my utils, I have this code: def search_kaggle(search_term): search_results = os.popen("kaggle datasets list -s "+search_term).read().splitlines() return search_results On my view function, I have this: def search_dataset(request): context = { } print('search dataset reached') if request.method == "POST": searchkey = request.POST["searchkey"] dtsite = request.POST["dtsite"] dtsnum = request.POST["dtsnum"] if searchkey != "": if dtsite == "kaggle": results = search_kaggle(dtsite) context['results'] = results print("Kaggle reached") if dtsite == "datagov": print("datagov") if dtsite == "uci": print("UCI") if dtsite == "googlepd": print("googlepd") else: messages.error(request, " You must select a search keyword!") return render(request, 'datasetsearch/dataset_results.html', context) When I run the code, it actually returns some data from kaggle but this data is totally different from what I get when I run the same command in CLI using: kaggle datasets list -s 'fraud detection' In the code above, the search_term = 'fraud detection' so I believe it should return the same form of data but I am getting something different. The result of the command line is the correct result. See Command line result ref title size lastUpdated downloadCount v mlg-ulb/creditcardfraud Credit Card Fraud Detection 66MB 2018-03-23 01:17:27 430457 ealaxi/paysim1 Synthetic … -
HTMX Closest #ID
I'm trying to create a dynamic form where it has chained dropdowns using Django and HTMX. here is the form class WorkModelForm(ModelForm): system = forms.ModelChoiceField(queryset=System.objects.all(), widget=forms.Select(attrs={ 'hx-get': reverse_lazy('ajax_load_subsystem'), 'hx-include': "[name='subsystem']", 'hx-target': 'closest #id_subsystem', 'hx-trigger': 'load,change', 'hx-swap': 'innerHTML', })) startDate = DateField(widget=forms.SelectDateWidget(years=['2022', '2023']), label='Start Date', initial=datetime.date.today(), ) endDate = DateField(widget=forms.SelectDateWidget(), label='End Date', initial=datetime.date.today() + datetime.timedelta(days=1)) subsystem = forms.ModelChoiceField(queryset=SubSystem.objects.all(), widget=forms.Select(attrs={ 'hx-get': reverse_lazy('ajax_filter_user'), 'hx-target': '#id_assigned_to', 'hx-include': "[name='assigned_to'],[name='system']", 'hx-trigger': 'load,change', 'hx-swap': 'innerHTML', })) class Meta: model = ListOfItems fields = ( 'id', 'system', 'subsystem', 'assigned_to', 'issueCount', 'startDate', 'endDate', 'status', 'remarks', ) def clean_data(self): data = self.clean_data[ 'issueCount', 'assigned_to', 'system', 'subsystem', 'startDate', 'endDate', 'status', 'remarks', ] return data this is the form I'm using to create and update values <form method="POST" class="tr" hx-target="this" hx-swap="outerHTML"> {% csrf_token %} {% for field in form.visible_fields %} <div class="td">{{ field }}</div> {%endfor%} {%if projects%} <div class="td"><button type="submit" hx-post="{%url 'edit-work' projects.id%}">Save</button></div> {%else%} <div class="td"><button type="submit" hx-post="."> Submit </button></div> {%endif%} </form> Is there a way to create unique ID for subsystem and assigned_to in attributes. I have tried closest TD but it is replacing the original drop down. -
Django Meta class returning an invalid attribute error when setting up verbose_plural_name
I am new to django, I'm trying to create a a diary like project and currently trying to setup the models when encountered this error. 'class Meta' got invalid attribute(s): verbose_plural_name This is my model from django.db import models from django.contrib.auth.models import User from django.utils import timezone import datetime class Diary(models.Model): owner = models.ForeignKey(User, models.CASCADE) title = models.CharField(max_length=100) date_created = models.DateTimeField(default=timezone.now) class Meta: verbose_name = "diary" verbose_plural_name = "diaries" def __str__(self): return "{}'s diary".format(self.owner) -
change django upload folder based on queryset
Gday, I'm working on a section of my data management project where users will be able to upload premade data for it to be parsed and inputted into the database. I am currently stuck on uploading files. The upload field will be on the main page for the specific dataset, which is navigated to by using the dataset id. What I would like is for any files uploaded in on that page to be saved in a directory such as "/projectroot/uploads/dataset_name". is this possible? -
how to upload files in django backend?
I am trying to create an upload file function in my website. However , i keep getting the error The submitted data was not a file. Check the encoding type on the form. I tried to create a post function in views.py. Does this mean any files that i uploaded is not considered a file ? models.py class ClinicVisit(models.Model): upload_attachment = models.FileField(null=True , blank=True, upload_to='uploads/') views.py class ClinicVisitList(generics.ListCreateAPIView): serializer_class = ClinicVisitSerializer filter_backends = [DjangoFilterBackend, filters.OrderingFilter] filterset_class = ClinicVisitFilter permission_classes = [permissions.IsAuthenticated,] pagination_class = LargeResultsSetPagination ordering = ['-created_at'] parser_class = (FileUploadParser,) def get_queryset(self): return ClinicVisit.objects.based_on_access_level(self.request.user) def post(self, request, *args, **kwargs): file_serializer = ClinicVisitSerializer(data=request.data) print(request.data) if file_serializer.is_valid(): file_serializer.save() return response.Response(file_serializer.data, status=status.HTTP_200_OK) else: return response.Response(file_serializer.errors,status=status.HTTP_400_BAD_REQUEST) serializers.py class ClinicVisitSerializer(serializers.ModelSerializer): upload_attachment = serializers.FileField() class Meta: model = ClinicVisit exclude = clinicvisit_exclude extra_kwargs = { "staff_relationship": {"required": True}, "visit_type": {"required": True}, "visit_status": {"required": True}, } -
Accessing file size get error : An error occurred (404) when calling the HeadObject operation: Not Found
I am trying to access the size of file in my django template then I get the error : Traceback (most recent call last): File "D:\Project\Project 1\env\lib\site-packages\django\template\base.py", line 875, in _resolve_lookup current = current[bit] During handling of the above exception ('FieldFile' object is not subscriptable), another exception occurred: Exception Type: ClientError at /document/list-skai Exception Value: An error occurred (404) when calling the HeadObject operation: Not Found I am using S3 as my FileField Storage. I am trying to access the size in the template with {{file.size}}. Any help? -
Axios blocked by CORS policy with Django REST Framework: 'Access-Control-Allow-Origin' header in the response must not be wildcard
Using vuejs3 ans axios, I'm trying to make a API call out to a django project, and getting a CORS error on the chrome side. Not sure what setting I'm missing here... The preflight OPTIONS response returned is ok, but chrome is upset that the 'Access-Control-Allow-Origin' header is "*". I'm using django-rest-framework with django-cors-headers. django.settings: ALLOWED_HOSTS = ["*"] # CORS CORS_ALLOW_ALL_ORIGINS = False # was initially True CORS_ALLOW_HEADERS = "*" CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = ["https://mydomain", "http://localhost:8080", "http://127.0.0.1:8080"] # Application definition INSTALLED_APPS = [ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "corsheaders", ... ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", ... ] vuejs/axios side: axios.defaults.xsrfHeaderName = 'X-CSRFToken'; axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.withCredentials = true; const url = `https://mydomin/my/endpoint/`; response = axios.get(url); I thought setting CORS_ALLOW_ALL_ORIGINS to False and defining CORS_ALLOWED_ORIGINS values would resolve the issue, but the Access-Control-Allow-Origin header is still showing as "*". Am I missing a setting? -
How to redirect django url in off business hours
There is a requirement like app should be available in business hours 9 AM -6 PM and rest time, it should redirect to just one well defined page. Can someone explain me how to achieve this. -
Get Related Data from ManyToManyField in Django
Working with ManyToManyField I want to get data of all the users related to all the queried model object along with other field data in the model. For example for the below model, I have 2 users related to this "ChatRoom" class ChatRoomParticipants(models.Model): user = models.ManyToManyField(User, related_name='chatroom_users') room = models.ForeignKey(ChatRoom, on_delete=models.PROTECT) With the below query chatrooms = list(ChatRoomParticipants.objects.filter(user=user).values('user__user_uid', 'room__id', 'room__name')) I'm able to fetch [{'user__user_uid': UUID('f4253fbd-90d1-471f-b541-80813b51d610'), 'room__id': 4, 'room__name': 'f4253fbd-90d1-471f-b541-80813b51d610-872952bb-6c34-4e50-b6fd-7053dfa583de'}] But I'm expecting something like [{'user__user_uid': UUID('f4253fbd-90d1-471f-b541-80813b51d610'), 'user__user_uid': UUID('80813b51d610-872952bb-6c34-4e50-b6fd-7053dfa583de'), 'room__id': 4, 'room__name': 'f4253fbd-90d1-471f-b541-80813b51d610-872952bb-6c34-4e50-b6fd-7053dfa583de'}] I've searched and found I can do something like user_data = chatrooms.users.all().values('user_uid') But the above doesn't work well with filter and I would miss out data on room. Note: I know that's not a correct method to do what I'm trying to achieve, if anyone can enlighten with what's the correct way to achieve the same data. -
Django OAuth with Xero SDK can't access session for oauth2_token_getter and oauth2_token_saver as no request object can be passed
I am using Django with requests_oauthlib to access the Xero API using the xero-python SDK. Xero Starter Demo requests-oauthlib I am trying to use request.session to store the oauth token information. This works well on the initial call and callback, but in subsequent views when I want to load the correct token from the request.session I am hitting a problem. The Xero ApiClient (xero_python.api_client) wants me to configure two functions it can call to get and save the token in the future (oauth2_token_getter, oauth2_token_saver) (decorators are used in the demo). Those functions are called by the Xero API and take no parameters. I can create the functions no problem, and they get called correctly, but once inside the functions I have no request object so I can't access request.session to get or save the token to the session. The Xero demonstration projects use Flask which imports a root level session object (from flask import session) which can be accessed in any function, so this works fine for Flask. What is the correct way to solve this problem in Django? I have tried creating a SessionStore object but it was empty despite me knowing the data is in the request.session I … -
Django gmail api
I am working on a project that need to send out email to users. I am using google api since the less secure app in no longer available. I am following this post to set it up, at the finall stage that I need to grant access to google. python gmail.py is not does not generate token.picke file needed for the api to function. project folder layout Need help on how to go about it -
Django query getting row data based on user id that created
I need help with writing a query. A user signs up and creates a schema. I am trying to write a query that will get the schema from the user id that created it. I have two models one is named Client. models.py class Client(models.Model): name = models.CharField(max_length=100) created_on = models.DateField(auto_now_add=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) For example: user | name ------------- 1 | test1 2 | test2 3 | test3 I am able to get the User ID, but I am unsure of how to get the name the user created. Below is my current code: views.py user_id = request.user.id user = User.objects.get(id=user_id) getTenant = Client.objects.get('name') tenant = Client.objects.filter(name=getTenant).filter(created_by=user) How can I write a Django query that will say "get name from user 1" therefore the desired output would be "test1"? And if I did "get name from user 2" the desired output would be "test2" and so on. Any and all help is appreciated. -
How to add a breed to an animal from the available breeds in django rest framework
i am looking how i can assign a breed to an animal upon the creation of an animal for example i have added many breeds to my database and now i want to clean it and assign a breed to each animal for example dogs can have rottweiler, Abradore and more in the rest framework this is how I made my serializer but it makes me create a new breed each time instead of chosing the breed from the available breeds class AnimalBreedSerializer(serializers.ModelSerializer): class Meta: model = AnimalBreed fields = ("name",) class AnimalTypeSerializer(serializers.ModelSerializer): animal_breed = AnimalBreedSerializer(many=False, read_only=True) class Meta: model = AnimalBreed fields = ("name","animal_breed") these are my models class AnimalBreed(models.Model): name = models.CharField(max_length=256, unique=True, primary_key=True) class AnimalType(models.Model): name = models.CharField(max_length=256, unique=True, primary_key=True) breed = models.ForeignKey(AnimalBreed, on_delete=models.CASCADE)