Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add new record if record exists
I Have a Form where id is hidden field from a model UserFileUploadModel. when I submit the form I save this info to other Model DecryptRequestModel. But here the id used is from UserFileUploadModel, So when i submit the form second time I get error, <ul class="errorlist"><li>id<ul class="errorlist"><li>Decrypt request model with this Id already exists.</li></ul></li></ul> So how can I, Let Django handle the id's for DecryptRequestModel, which will get incremented with each submission. OR Directly update the previous entry, where only one field will change. HTML Form:- <form method="post" action="{% url 'decrypt' %}" enctype="multipart/form-data"> {% csrf_token %} {% for i in objects %} <input type="hidden" name="id" value="{{i.id}}" readonly> # ID from other table <input type="text" name="email" value="{{i.filename}}" readonly> <input type="hidden" name="algorithms" value="{{i.algorithms}}"> {% if i.algorithms == 'BLOWFISH' or i.algorithms == 'AES-256' %} <input type="text" name="key" required="True" placeholder="Enter the Secret Key"> {% else %} <input type="file" name="private_key" required/> {% endif %} <input type="submit" id="redirect" name="decrypt" value="Download"> {% endfor %} </form> View.py :- def DecryptFile(request): if 'isloggedin' in request.session: if request.method == 'POST': id = request.POST.get('id') # instance = DecryptRequestModel.objects.get(id=id) form = DecryptRequestForm(request.POST,request.FILES) if form.is_valid(): algorithm = form.cleaned_data['algorithms'] print(algorithm) form.save() Models: class DecryptRequestModel(models.Model): id = models.IntegerField(primary_key=True) file_name = models.CharField(max_length=200) algorithms = models.CharField(max_length=200) … -
Django Rest Framework pagination and filtering
Hi guys i am trying to make filtering with pagination but i cannot get the result i want. This is my function in views.py. class OyunlarList(generics.ListAPIView): # queryset = Oyunlar.objects.all() pagination_class = StandardPagesPagination filter_backends = [DjangoFilterBackend] filterset_fields = ['categories__name', 'platform'] # serializer_class = OyunlarSerializer def get_queryset(self): queryset=Oyunlar.objects.all() oyunlar=OyunlarSerializer.setup_eager_loading(queryset) return oyunlar def get(self,request,*args,**kwargs): queryset = self.get_queryset() serializer=OyunlarSerializer(queryset,many=True) page=self.paginate_queryset(serializer.data) return self.get_paginated_response(page) This is my pagination class. class StandardPagesPagination(PageNumberPagination): page_size = 10 And this is the json i got but when i write localhost/api/games?platform=pc or localhost/api/games?categories=Action it is not working. { "count": 18105, "next": "http://127.0.0.1:8000/api/oyunlar?categories__name=&page=2&platform=pc", "previous": null, "results": [ { "game_id": 3, "title": "The Savior's Gang", "platform": "ps4", "image": "https://store.playstation.com/store/api/chihiro/00_09_000/container/TR/en/999/EP3729-CUSA23817_00-THESAVIORSGANG00/1599234859000/image?w=240&h=240&bg_color=000000&opacity=100&_version=00_09_000", "categories": [], "release_date": null }, { "game_id": 8, "title": "Spellbreak", "platform": "ps4", "image": "https://store.playstation.com/store/api/chihiro/00_09_000/container/TR/en/999/EP0795-CUSA18527_00-SPELLBREAK000000/1599612713000/image?w=240&h=240&bg_color=000000&opacity=100&_version=00_09_000", "categories": [], "release_date": null }, { "game_id": 11, "title": "Marvel's Avengers", "platform": "ps4", "image": "https://store.playstation.com/store/api/chihiro/00_09_000/container/TR/en/999/EP0082-CUSA14030_00-BASEGAME0001SIEE/1599653581000/image?w=240&h=240&bg_color=000000&opacity=100&_version=00_09_000", "categories": [], "release_date": null }, { "game_id": 24, "title": "The Suicide of Rachel Foster", "platform": "ps4", "image": "https://store.playstation.com/store/api/chihiro/00_09_000/container/TR/en/999/EP8923-CUSA19152_00-DAEEUTSORF000001/1599610166000/image?w=240&h=240&bg_color=000000&opacity=100&_version=00_09_000", "categories": [ { "category_id": 2, "name": "Casual" }, { "category_id": 5, "name": "İndie" }, { "category_id": 8, "name": "Adventure" } ], "release_date": "2020-09-09" }, { "game_id": 25, "title": "Takotan", "platform": "ps4", "image": "https://store.playstation.com/store/api/chihiro/00_09_000/container/TR/en/999/EP2005-CUSA24716_00-TKTN000000000000/1599610166000/image?w=240&h=240&bg_color=000000&opacity=100&_version=00_09_000", "categories": [ { "category_id": 1, "name": "Action" }, { "category_id": 12, "name": "Arcade" … -
elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x7fc1cad35390>:
I have this in my docker-compose.yml elastic: image: docker.elastic.co/elasticsearch/elasticsearch:7.5.1 ports: - 9260:9200 environment: http.host: 0.0.0.0 transport.host: 127.0.0.1 volumes: - ./config/elastic/elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml - elasticsearch:/usr/share/elasticsearch/data and in my staging.py ELASTICSEARCH_DSL={ 'default': { 'hosts': '127.0.0.1:9260' }, } in my jenkins when it tries to deploy to staging, it fails with the following error elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x7fc1cad35390>: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7fc1cad35390>: Failed to establish a new connection: [Errno 111] Connection refused) I got the same error when I tried to run my test scripts in my local with python manage.py test In my settings/test.py I replaced ELASTICSEARCH_DSL={ 'default': { 'hosts': 'elastic:9200' }, } with ELASTICSEARCH_DSL={ 'default': { 'hosts': 'elastic:9260' }, } and the error was gone. Any help will be greatly appreciated. Thank you in advance. -
What exactly is "is_paginated" ? Django Documentation
I've been learning Django for the past couple of months and have found out that the documentation is not very good, or maybe I don't know how to use, but in many occasions I find myself doubtful when looking where every thing comes from. As long as I know, is_paginated is a boolean in the context that returns True if the results are paginated, I found this information here: https://docs.djangoproject.com/en/3.1/ref/class-based-views/mixins-multiple-object/ But in that link from the documentation says it is from the Multiple Object Mixin, and in a Django youtube tuorial I've seen he uses it within a generic class-based DetaiView template, so I've tried to look in the documentation for it and I could not find anything so satisfice my curiosity, maybe I'm not seeing something but I don't like just copying code without knowing where exactly it comes from and what does it do. -
i was heroku run python manage.py migrate but programmingerror is continue
enter image description hereenter image description hereenter image description hereJiQ.png 내가 생각하기에 아무런 문제도 없어야 한다. 나는 migrate도 진행했으며, sqlmigrate, showmigrations로 확인 하였을 때, 정상 적으로 model이 만들어 져 있다는 것도 확인 하였다. 그러나 여전히 heroku는 해당 모델을 찾지 못하고 있다. 어떻게 해야 하는가? -
Getting background-image from GCP storage bucket using django static
I am using django-storages GCP storage backend to serve static to my site from a storage bucket. However, I'm encountering an issue with using the background-image CSS property in conjunction with django's {% static %} tag. In particular, I have the following CSS embedded into the page: <style> .my-background { background-image: url({% static 'foo/bar/example.jpg' %}); } </style> And then if I include the following in the HTML for the page: <div class="my-background"></div> <img src="{% static 'foo/bar/example.jpg' %}"> The <img> tag retrieves the image just fine, but the background-image gets a 403 error with AccessDenied returned from the storage bucket call. I can't figure out why they should be treated differently, any help much appreciated. -
Why django debug tool calculate different CPU time for same functions in different runs?
I am using Django debug tool to calculate the CPU time used by my Django app. Each time I run a particular page in my app, I get different CPU times(difference of 100MS). Why the CPU time fluctuates for the same function in the Django app? -
Get User Details from database in Django
I am working in site which display the details of a contact registered in my app, the error I have is when retrieving the data does not show and cannot find the Ajax request, any help would be appreciated urls.py from django.urls import path from app_2 import views as app2 urlpatterns = [ #app_2 path('user', app2.userPanel), path('get_user_info', app2.getUserInfo, name = 'get_user_info'), ] Script in user.html <script type="text/javascript"> $(document).ready(function(){ $("#users").change(function(e){ e.preventDefault(); var username = $(this).val(); var data = {username}; $.ajax({ type : 'GET', url : "{% url 'get_user_inf' %}", data : data, success : function(response){ $("#user_info table tbody").html(`<tr> <td>${response.user_info.first_name || "-"}</td> <td>${response.user_info.last_name || "-"}</td> <td>${response.user_info.email || "-"}</td> <td>${response.user_info.is_active}</td> <td>${response.user_info.joined}</td> </tr>`) }, error : function(response){ console.log(response) } }) }) }) </script> -
Django class UpdateView
I have this view and I use this code class post_Wells(UserPassesTestMixin, LoginRequiredMixin, UpdateView): model = Wellinfo template_name = 'Home/WELLINFO/detailw2.html' form_class = NewWells def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user== post.author: return True else: return True everything works good, but I want to send other data from this class for example I want to render this text: context ={ 'Mytext': 'This well is Open'} how to do it inside this class? -
Django - best way to use 2 forms in one view ? MultiFormsView or request
I've a view (post chat / request.user / goal:add form for activation of channel ) and I'd like to know what's the best way to add another form? MultiFormsView or request ? -
How to trigger file download in Django?
I have a basic webapp deployed on Heroku which has couple of information stored about students i.e. their names, IDs, and graduation date. Instead of storing a certificate for every student in the server which takes more space, I have stored a blank certificate in the server. Every time a user enters the ID, if the student with that ID exists, I want to overlay their name and graduation date on the blank certificate and make it available for download. I have a function that does the overlaying but the file download is not working! Can anyone guide? Views.py ## shows a form where user enters an ID (CNIC) number. def index (request): if request.method == "POST": form = SearchForm(request.POST) if form.is_valid(): cnic = form.cleaned_data["cnic"] if Fellow.objects.filter(CNIC=cnic): fellow = Fellow.objects.get(CNIC=cnic) return success(request, fellow) else: return fail(request, cnic) else: return render(request, "certificates/index.html", { "form": form }) else: search = SearchForm() return render (request, "certificates/index.html", { "form": search }) ## if student with given CNIC exists, success function is called def success (request, fellow): name = fellow.name.title() program = fellow.program cnic = fellow.CNIC cnic = fellow.CNIC[:5]+ "-" + fellow.CNIC[5:12] + "-" + fellow.CNIC [-1] if "Dr." not in name: name = "Dr. … -
Can anyone help me out this? [closed]
>>> django.setup() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\django\__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Users\HP\AppData\Local\Programs\Python\Python35\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) -
my default python3 is 3.5 , how to install django for python 3.6 on Ubuntu?
used pip method(pip3) I used pip3. But it installs django for default python3 version i.e,3.5. -
{% csrf_token %} printing as text from js file django
{% csrf_token %} printing as text from js file in Django the code is working if use it in script tag but when I try to use from an external js file it doesn't work {% csrf_token %} printing as text from js file in Django the code is working if use it in script tag but when I try to use from an external js file it doesn't work {% csrf_token %} printing as text from js file in Django the code is working if use it in script tag but when I try to use from an external js file it doesn't work HTML <div class="box container" id="box2"> <div class="skillbox"> <div class="workquestion"> How Many work Exprience you wanted <br> to add in your resume ? </div> <div class="row" id="butt"> <div class="form-group col-md-2"> <button type="button" class="btn btn-success" onclick="updateform(1)" id="butt1">1</button> </div> <div class="form-group col-md-2"> <button type="button" class="btn btn-success" onclick="updateform(2)" id="butt2">2</button> </div> <div class="form-group col-md-2"> <button type="button" class="btn btn-success" onclick="updateform(3)" id="butt3">3</button> </div> <div class="form-group col-md-2"> <button type="button" class="btn btn-success" onclick="updateform(4)" id="butt4">4</button> </div> <div class="form-group col-md-2"> <button type="button" class="btn btn-success" onclick="updateform(5)" id="butt5">5</button> </div> <div class="workquestion" style="color: red;"> Maximum </div> </div> <div class="row" > <div class="form-group col-md-2"> <button type="button" class="btn btn-success" onclick="updateform(6)" id="butt6">6</button> … -
Django get total count and count by unique value in queryset
I have models Software and Domain described loosely as: class Software(models.Model) id = models.BigInteger(primary_key=True, db_index=True, null=False) company = models.ForeignKey('Company') domain = models.ForeignKey('Domain') type = models.CharField(null=False) vendor = models.CharField(null=False) name = models.CharField(null=False) class Domain(models.Model): id = models.BigInteger(primary_key=True, db_index=True, null=False) type = models.CharField() importance = models.DecimalField(max_digits=11, decimal_places=10, null=False) And I get a Software queryset with: qs = Software.objects.filter(company=c).order_by('vendor') The desired output should have an aggregated Domain importance with total count for each unique Software, i.e. [ { 'type': 'type_1', \ 'vendor': 'ajwr', | - unique together 'name': 'nginx', / 'domains': { 'total_count': 4, 'importance_counts': [0.1: 1, 0.5: 2, 0.9: 1] # sum of counts = total_count }, }, { ... }, ] I feel like the first step here should be to just group the type, vendor, name by Domain so each Software object has a list of Domains instead of just one but I'm not sure how to do that. Doing this in memory would make it a lot easier but it seems like it would be a lot slower than using querysets / SQL. -
how to create a navigation menu system with Django?
I want to create a dynamic menu for my weblog made by Django. but I don't know where to start the menu should be able to define url for every object in the database (posts, pages, tags, ... ). how can I do that ? the menus of Joomla and wordpress system are good examples for what I expect. -
Can't type password in my PyCharm terminal (for Django admin)
I am new to Python and Django. I was trying to create an admin user for the first time. But for some reason, I can't type anything in my password section. Whatever I type, I can't see any output in PyCharm terminal: https://prnt.sc/uhnyp5 (Same goes for windows cmd). Would you please help me to solve this? Regards. -
Sharing domains with 2 different sites
I have a a pre-existing square-space blog with a domain hosted by square-space and I wish to share the domain name with a new django application that is hosted on linode, is it possible? -
Exporting to mdb file formats using django admin
I'm new to both python and Django. I've been working on a task using Django import export. If possible I'm looking for a way to export models into the .mdb format using Django. Any help would be much appreciated, thank you. -
Django: TemplateSyntaxError: Could not parse the remainder (extends tag)
I'm getting this error when I go to http://127.0.0.1:8000/ I've gone through other similar threads and have tried playing around with spaces as well as single and double quotation marks but with no luck. I'm trying to have the index.html file inherit the code in master.html, which is contained in a folder structure that looks like this. Here are a few snippets of some of the files that I think are causing this error: from settings.py: BASE_DIR = Path(__file__).resolve().parent.parent INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tracker', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] from index.html (this is the only line in this file) {% extends ‘layouts/master.html’ %} from views.py # Create your views here. from django.shortcuts import render def index(request): return render(request, 'index.html') Error traceback: Exception Type: TemplateSyntaxError at / Exception Value: Could not parse the remainder: '‘layouts/master.html’' from '‘layouts/master.html’' What seems to be causing the syntax error? Thanks in advance -
Django format `Available user permissions`, i.e. make Title case
So Django docs recommend setting model's verbose_name and verbose_name_plural in lowercase, and then capitalizing it when required. However in the djangop admin under Home › Authentication and Authorization › Users › username It uses the lowercase verbose name. How does one capitalize the app labels and model names. E.g. For the row selecting, and it would become: Auth - Group | Can add group -
django social auth does not create user profile
I have profile with django social-auth, when users using social auth, their data is only avaiable in social auth(a), not default django profile (b). screenshot from django admin-panel What I should do? -
Throttling users based on their groups
I'd like to limit form requests for users based on their group for a Saas application (Free, Paid), so if a free user hit their limit, they get redirected to another page or show a pop-up I tried using throttling but I can't figure out how to implement the conditions settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication'], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.UserRateThrottle', 'contact.throttling.FreeDailyRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'user': '5/second', 'Free': '200/day' } } views.py class FreeDailyRateThrottle(UserRateThrottle): scope = 'Free' user = request.user if user.groups.filter(name=Free).exists() : #i'm not sure what to do here! else : #redirect to a different page @login_required(login_url='login') @api_view(['POST']) @throttle_classes([FreeDailyRateThrottle]) def ad_gen(request): context ={} if request.method!="POST": return render(request , 'Ad Gen.html' , context) else: // some logic return render(request , 'Ad result.html' ,context) -
How to create settings like AUTH_USER_MODEL for own model in django?
Suppose i've model called class A(models.Model): name = .... age = .... Now I want to access this model using settings file. for example, we can access User model using django settings file like this from django.conf.settings import AUTH_USER_MODEL Now I wan't to achieve same behavior for my custom model. I'm not sure this is possible or not. -
Django, How to update image
I hope the title is enough to understand my problem, as you can see in the image below, i can get the pciture from my database, the problem is when I update the data and I didnt change the picture displayed, it makes an error, the cause of the error is I didnt get any data from html <label for="myfile3"> <img id="output3" src="{{selectbanner.image.url}}" style="height:225px;width:250px;" class="subimage"/><br> <input type="file" accept="myfile" id="myfile3" name="image" value="{{selectbanner.image.url}}" onchange="loadFile3(event)" > </label> <script> var loadFile3 = function(event) { var reader = new FileReader(); reader.onload = function(){ var output3 = document.getElementById('output3'); output3.src = reader.result; }; reader.readAsDataURL(event.target.files[0]); }; </script> this is my views.py image = request.FILES.get('image') print(image) update = Banner.objects.get(id=banner_id) update.image = image update.title = Title update.sub_title = Sub update.description = Description update.save() return redirect('Banners')