Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Copying code using Dockerfile or mounting volume using docker-compose
I am following the official tutorial on the Docker website The docker file is FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ The docker-compose is: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code I do not understand why in the Dockerfile they are copying the code COPY . /code/ , but then again mounting it in the docker-compose - .:/code ? Is it not enough if I either copy or mount? -
How to pass a value from ajax to views
I have a selection box in my template and every time i change the value i have to press a button to submit the value. I know that ajax can solve it but and thats what im trying as follows: Views.py def check_state(request,n): if request.method=='POST': state= request.POST.get('thestate') dict1 = {'name':name} print(dict1) return JsonResponse(dict1, safe=False) template.html <select id="select_state" name="updated_state"> <option disabled="true" selected>{{current_state}}</option> {% for state in States %} <option>{{state}}</option> {% endfor %} <script> var state = document.getElementById( "select_state" ); var x=state.addEventListener( "change", output, true ); function output() { console.log ( state.value ); $.ajaxSetup({ beforeSend: function(xhr, settings) { function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { // Only send the token to relative URLs i.e. locally. xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } }); $.ajax({ url:'/req-3', # it will call check_state function in views.py method:'POST', data: {thestate:state.value}, dataType: "json", processData:false, csrfmiddlewaretoken:'{{ csrf_token }}', … -
nginx not loading my project from other server
I have three servers 10.77.12.54,10.77.12.55,10.77.12.56 my application on 54, Postgres on 55, and Nginx on 56 servers I created gunicorn.shock file and gunicorn.server file and I added app IP to Nginx config file and also create sites-available, sites-enabled but Nginx not fetching my application is there anything I have to do? server { listen 80; server_name 10.77.12.54; add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options nosniff always; add_header X-XSS-Protection "1; mode=block" always; proxy_cookie_path / "/; Secure"; access_log /var/log/nginx/access_rkvy.log main buffer=32k; location / { access_log /var/log/nginx/app54log.log main; proxy_pass http://loadblncer; proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504; proxy_buffering off; proxy_buffer_size 128k; proxy_buffers 100 128k; proxy_set_header X-Forwarded-For $http_x_forwarded_for; } -
def get_absolute_urls(self): not working ,Django
when I click the post title it is supposed to go to the post detail(detail.html) but it's not working, how do i fix this? Here is Model.py class Post(models.Model): ....... def get_absolute_urls(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) Urls.py urlpatterns= [ path('',views.post_list,name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.post_detail,name='post_detail'), ] Views.py def post_detail(request,year,month,day,post): post= get_object_or_404(Post,slug=post,status='published',publish_year= year,publish_month= month, publish_day= day) return render(request,'blog/detail.html',{'post':post}) list.html {% extends "blog/base.html" %} {% block title %} My Blog {% endblock title %} {% block content %} <h1>My Blog</h1> <p>this is working in list.html</p> {% for post in posts %} <h2> <a href="{{ post.get_absolute_url }}"> {{ post.title }} </a> </h2> <p class="date"> Published{{ post.publish }} by {{ post.author }} </p> {{ post.body| truncatewords:30|linebreaks }} {% endfor %} {% endblock content %} detail.html {% extends "blog/base.html" %} {% block content %} <h1>{{ post.title }}</h1> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body|linebreaks }} {% endblock content %} -
How to override get_object in DetailView Django
how can I override get_object in my situation? I've tried different variations but they weren't successful. For example if I try: return self.get_object(). There is RecursionError: maximum recursion depth exceeded model: class Shop(models.Model): name = models.CharField(max_length=100, verbose_name='Название магазина') description = models.TextField(blank=True, verbose_name='Описание магазина') def __str__(self): return self.name view: class ShopDetailView(DetailView): model = Shop template_name = 'shop/shop_detail.html' context_object_name = 'shop' def get_object(self, queryset=None): pass url: urlpatterns = [ path('shop/<str:name>', ShopDetailView.as_view(), name='shop') ] -
django formset, for each form a different data than a select
I have a formset and I would like the first data inside the select to be already selected one every formset, in my case I have two data so in the first formset there will be the first data and in the second the second data and if possible I would like to display them in text and not with a select or in any case no input to modify them. views.py def crea_gruppi(request): tot_gruppi = Gruppo.objects.all() gruppiFormSet = formset_factory(GruppiForm, extra = tot_gruppi.count()) # POST if request.method == 'POST': gruppi_formset = gruppiFormSet(request.POST, prefix='gruppi') # GET else: gruppi_formset = gruppiFormSet(prefix='gruppi') context = { 'gruppi_formset': gruppi_formset, 'tot_gruppi': tot_gruppi } return render(request, 'crea_gruppi.html', context) html <section class="mt-5"> <div class="container"> <div class="d-flex align-items-center justify-content-between"> <h2 class="m-0 text-light">crea gruppi</h2> </div> <hr class="bg-light"> <form method="post" autocomplete="off"> {% csrf_token %} {{ gruppi_formset.management_form }} <div class="raccoglitore-gruppi"> {% for gruppo in gruppi_formset %} <div class="gruppo mb-3" style="border: 2px solid red; padding: 20px; border-radius: 5px;"> <div style="color: #fff;"> <h6 class="m-0">test</h6> <hr> {{ gruppo.dati_gruppo|add_class:"form-control" }} <hr> {{ gruppo.giorni_settimana }} </div> </div> {% endfor %} </div> <div class="text-end"> <input type="submit" class="btn btn-warning" value="salva"> </div> </form> </div> </section> form class GruppiForm(forms.ModelForm): class Meta: model = models.DatiGruppi exclude = ['gruppi_scheda'] -
Import environ could not be resolved
im working in a django project but i cant import environ. I have tried reinstaling envirion, django-environ , tried select again my virtual enviroment import environ from store.settings.base import * env = environ.Env() DEBUG = env.bool("DEUBG", False) SECRET_KEY = env("SECRET_KEY") ALLOWED_HOSTS = env.list("ALLOWED_HOSTS") DATABASES = { "default": env.db(), } -
How can I filter out date created task in my task list
I'm trying to show the date-created tasks in my list in HTML. class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200) description = models.TextField(max_length=1000, blank=True, null=True) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) And this is my HTML in Django <div class="task-items wrapper"> {% for task in tasks %} <div class="task-wrapper"> {% if task.complete %} <div class="task-title"> <div class="task-complete-icon"></div> <i><s><a class="task" href="{% url 'update-task' task.id %}">{{task}}</a></s></i> <br></br> </div> <a class="delete-link" href="{% url 'delete-task' task.id %}"><i class="fa-solid fa-delete-left"></i></a> {% else %} <div class="task-title"> <div class="task-incomplete-icon"></div> <a href="{% url 'update-task' task.id %}">{{task}}</a> </div> <a class="delete-link" href="{% url 'delete-task' task.id %}"><i class="fa-solid fa-delete-left"></i></a> {% endif %} </div> <div class="emptylist"> {% empty %} <h3 style="text-align: center; line-height: 3;">No task in list! Let's create your task</h3> </div> {% endfor %} </div> For example, for each task I create, it must show the title with the date created, and doesn't matter if it is completeđ or incomplete. I just can show the title and how do I do that show the date? -
Django migrations - how to apply newly applied rules to previously saved model instances?
Let's say I have the following model and I have already some instances of the model saved in the database - class Comment(models.Model): comment_text = models.CharField(max_length=255) Now, if I want to change the max_length argument to 127 instead of 255 and apply the migrations, the older instances will still be in the database where some might have the length more than 127 which is not obeying the new migrations. What is the best approach to migrate all previous data along with the new migration rules? -
the pgAdmin4 save null value
I want to save the data of the textfiled that take the location name and other filed from the html and save it in pgadmin4 by using the def in my view when I enter the value in html it is add but it shows me null in pgAdmin this is my view def location(request): if request.method == 'POST': form = request.POST location_id = form.get(' location_id') location_name = form.get('location_name') location_address = form.get('location_address') lat = form.get('lat') lag_y = form.get('lag_y') user_id = request.session['user_id'] print(form) data_insert = MapModel.objects.create(location_id=location_id, location_name=location_name, location_address=location_address, lat_x=lat, lag_y=lag_y,) if data_insert: json_data = {'msg': " data added succssfully", 'id': data_insert.location_id } return JsonResponse(json_data) else: json_data = {'msg': " try agine", 'id': '', } return JsonResponse(json_data) else: return render(request, 'new_file.html') -
Bypass gunicorn worker timeout for specific endpoint
I have Django (3.2.4) app running on Gunicorn (20.1.0) and that app have one heavy endpoint. This endpoint returns csv report which may be very big: def _stream_serialized_data(): paginator = Paginator(MyModel.objects.filter(**filter), 5000) for page in paginator.page_range: yield from MySerializer(paginator.page(page).object_list, many=True).data renderer = CSVStreamingRenderer() return StreamingHttpResponse( renderer.render(_stream_serialized_data(), renderer_context={"header": MySerializer.Meta.fields}), content_type="text/csv", headers={"Content-Disposition": 'attachment; filename="report.csv"'}, ) The problem is that report loading may be aborted by gunicorn worker timeout despite loading starts immediately and there is very small delay between chunks. Is there a way to inform gunicorn that this worker is fine? May be call some function from _stream_serialized_data loop to reset timeout. I already found suggestions to increase timeout and to use gevent, but I don't want to do anything than affects other endpoints. -
Unable to Call the Django Function
def ravi(request): if request.method = "POST": entered_index = request.POST['index'] socket_opened = False def event_handler_quote_update(message): print(f"quote update {message}") def open_callback(): global socket_opened socket_opened = True alice.start_websocket(subscribe_callback=event_handler_quote_update, socket_open_callback=open_callback, run_in_background=True) while(socket_opened==False): pass alice.subscribe(alice.get_instrument_by_symbol('NSE','ONGC'),LiveFeedType.MARKET_DATA) form = trades() return render(request, "blog/box_breakout.html",{'form': form}) "When I call the function, the browser keeps on loading. It neither works nor giving me the error" . -
Using F function into annotate
i have a problem about using f function into annotating i use F function to retreive "user__id" and pass it to get_user_daynum that it should returns a number but it always returns a same number. after that i filter them by creating a lookup_field. i test the get_user_daynum many times and i get correct number but about using it in annotate i'm confused. for date, days in valid_date_days.items(): lookup_field = f'{date}__in' intended_user_workpattern = intended_user_workpattern.annotate( **{date: Value(get_user_daynum(date, F('user__id'), request_user_wp.work_pattern))} ) intended_user_workpattern = intended_user_workpattern.filter( **{lookup_field: list(days)} ) -
Django inlineformset_factory not displaying all initial data
I'm providing a list of dictionaries when instantiating an inlineformset to display some initial data, for example: initial_data = [{'form1': 'foo'}, {'form2': 'foo'}, {'form3': 'foo'}, {'form4': 'foo'}, {'form5': 'foo'}] I then supply this to my formset: MyInlineFormset(initial=initial_data) However it only shows three of the five forms: Displayed forms If I pass extra=5 when constructing the formset, it works no problem: Displayed forms when extra=5 I know the default is extra=3 but I thought it would override this based on the number of initial forms provided. Is that incorrect? -
How can i change this query to ORM? (JOIN without foreign key and order by second table)
Hi i have two models like this, class Sample(models.Model): name = models.CharField(max_length=256) ## processid = models.IntegerField(default=0) # class Process(models.Model): sample = models.ForeignKey(Sample, blank=False, null=True, on_delete=models.SET_NULL, related_name="process_set") end_at = models.DateTimeField(null=True, blank=True) and I want to join Sample and Process model. Because Sample is related to process and I want to get process information with sample . SELECT sample".id, sample.name, main_process.id, main_process.endstat FROM sample INNER JOIN process ON sample.processid = process.id ORDER BY process.endstat; How can i do with ORM like this SQL? -
i want to make an wallet that is linked with his phone number when a user register with the mobile number a wallet is automatically generated
There's two models in my application one is user which contains the details of user like mobile number and the other one is wallet model which contains the total balance, add amount etc. what i want is when a user register itself a wallet automatically gets generated associated with his phone number. i have done this models.py class User(models.Model): mobile = models.CharField(max_length=20) otp = models.CharField(max_length=6) name = models.CharField(max_length=200) username = models.CharField(max_length=200) #logo_path = models.CharField(max_length=200) logo = models.ImageField(null=True, blank=True) profile_id = models.CharField(max_length=200) class Wallet(models.Model): user = models.ForeignKey(User,null=True,related_name='wallet_mobile',on_delete=models.CASCADE) total_amount = models.DecimalField(_('total'), max_digits=10, decimal_places=2, default=10) add_amount = models.DecimalField(_('amount'), max_digits=10, decimal_places=2, default=0) win_amount = models.DecimalField( max_digits=10, decimal_places=2, default=0) deduct_amount = models.DecimalField( max_digits=10, decimal_places=2, default=0) serilalizers.py class walletserializer(serializers.ModelSerializer): wallet_mobile = serializers.StringRelatedField() class Meta: model = Wallet fields = ['user','total_amount','add_amount','win_amount','deposit_amount'] views.py @api_view(['GET']) def get_wallet(request,pk): snippet = Wallet.objects.get(pk=pk) if request.method == 'GET': serializer = walletserializer(snippet) return Response(serializer.data) i am getting the data base with user id i want the data with with associated phone number -
Navigate me to get set up a third party google login for my webpage using django rest framework and React JS
I was stuck on setting the google login authentication using django rest framework in the backend and react JS in the frontend. We have a email and passowrd custom login for the website and we need to implement the third party google login. I have tried many ways and it didn't worked for me, on one way it is getting username, password, clientID, clientsecret, and the grant type it is taking as password for a post call. Maybe what i need is when a user clicks google sign in the front end generates a access token and id token, and user email from the google and it comes to connect on backend where i need to give him the data of that user by approving the request. How can i able to do that? Please help me with any code or share me with a complete reference of setting up the google login. -
Pycharm cannot suggtest import for django.test
Not suggest any class in django.test, but worked in django.http. How to fix it ? -
Why i am getting Validation error even when input is correct in form
I was learning Django form validation from some online resource , was working on form validation , I created a validation error depicting the condition and passed it in form field , but the validation error is raising even if I am giving correct input. Similar to this happened when i raised a validation error for botcatcher without using validators, the error was not raised even i was giving input through inspect (its code is commented) ,Do help me out! forms.py from django import forms from django.core import validators def check_name(value): if value[0].lower() != 'K': raise forms.ValidationError('Name should start with K') class FormName(forms.Form): name = forms.CharField(validators=[check_name]) email = forms.EmailField() text = forms.CharField(widget=forms.Textarea) botcatcher = forms.CharField(required=False, widget=forms.HiddenInput, validators=[validators.MaxLengthValidator(0)]) # def cleaned_botcatcher(self): # botcatcher = self.cleaned_data['botcatcher'] # if len(botcatcher) > 0: # raise forms.ValidationError('CAUGHT THE BOT') # return botcatcher [webpage for same][1] views.py from django.shortcuts import render from . import forms # we can also use from basicapp import forms . refers to current directory # Create your views here. def index(request): return render(request, 'basicapp/index.html') def form_name_view(request): form = forms.FormName() if request.method == 'POST': form = forms.FormName(request.POST) if form.is_valid(): # DO something print("VALIDATION SUCCESS , POSTED") # Retreiving posted data print("NAME: " … -
Multiple user access to one primary account Django auth
I have already configured custom User authentication for my project, however, I would appreciate some advice on how to implement the following: Overview of requirements: My project requires that a customer be able to setup an account to use our online services. That same customer (as administrator of the account) would then be able to add sub-users to that account and also be able to configure permissions for each of those sub-users with respect to that account. My question: I am not sure how to begin to implement this and I would appreciate some practical guidance on where start. -
How to update and insert records after every 1 minute in sqlite?
I have created a django project which contains one table. I want to automatically update the records in sqlite databse after every minute. How can be this done? I have already used time.sleep(18000) library of python but it didn't worked. In if:else statement insert and update operations are performed. views.py: def index(request): while True: r1 = requests.get("http://127.0.0.1:2000/_nodes") script = r1.json() write = script['nodes']['data'] ts1 = script['nodes']['time'] print("write ",write) print("ts1 ",ts1) r2 = requests.get("http://127.0.0.1:2000/_nodes") script = r2.json() read = script['nodes']['total'] ts2 = script['nodes']['time'] print("read ",read) print("ts2 ",ts2) new_count = write+read new_t = (ts1+ts2)/2 print ("new count", new_count) print("new ts", new_t) q = data.objects.filter() if q.exists(): test1 = data.fetch() for row in test1: test1={ 'id':row.id, 'sum': row.sum, 'ts': row.ts, 'status': row.status } prev_t = test1['ts'] prev_count = test1['sum'] if(test1['id']==1): if(new_count < prev_count): test2 = data.objects.get(id=1) print("TEST2 Type", type(test2)) print(test2) test2 = data(id=1,sum=new_count,ts=new_t,status="restarted") test2.save() print(test2) print(type(test2)) else: test1 = data.fetch() test2 = data.objects.get(id=1) print("TEST2 Type", type(test2)) print(test2) test2 = data(id=1,sum=new_count,ts=new_t,status="updated") test2.save() print(test2) print(type(test2)) else: test2 = data(id=1,sum=new_count,ts=new_t,status="firstQuery") test2.save() print (test2) print("Fresh record created") test2 = data.fetch() for row2 in test2: test2={ 'id':row2.id, 'sum': row2.sum, 'ts': row2.ts, 'status': row2.status } print(test2) print(type(test2)) -
How to assemble a variable name in Django templating language?
I am trying to assemble a variable in Django template in that way: obj.length.forloop.counter where the foorloop.counter should return the number. for example obj.length.1 then obj.length.2 and so on... I tried the add filter: obj.length|add:forloop.counter but that returned nothing at all. Is there any way that I can assemble variable names like that in django templating language? -
Spinning Up a Staging Server for Testing a Django Web-Application
I have been following Harry J.W. Percival's Test-Driven Development with Python. In the chapter of "Testing Deployment Using a Staging Site", I am confused as to the course of action that I should take now to implement this: Spinning Up a Server I’m not going to dictate how you do this—whether you choose Amazon AWS, Rack‐space, Digital Ocean, your own server in your own data centre or a Raspberry Pi in a cupboard behind the stairs, any solution should be fine, as long as: Your server is running Ubuntu (13.04 or later). You have root access to it. It’s on the public Internet. You can SSH into it. I am a beginner with respect to the framework. Hence, the topic of Deployment and Staging is somewhat unnerving for me, owing to my inexperience. The author previously states that we may either run our own (possibly virtual) server or go for PaaS. So, my query is how do I accomplish the process of setting up a staging server for verification and validation testing purposes (links to sources explaining the process shall be greatly acknowledged)? Given the nature of my problem, I could not figure out how to move ahead. Should I … -
Django "fields" attribute of user forms (UserCreationForm and UserChangeForm)
According to Django docs: It is strongly recommended that you explicitly set all fields that should be edited in the form using the fields attribute. I have a custom user model, so I overrode UserCreationForm and UserChangeForm, but I'm not sure about the fields attribute of the Meta class. The admin site will be editing all fields of a user; so in UserChangeForm, do I have to include all fields in this attribute? like this: class Meta: model = User fields = ( "email", "password", "is_active", "is_staff", "is_superuser", "date_joined", "last_login", "groups", "user_permissions", # maybe there are others that I'm missing? ) Or in this case, it's safe to use the '__all__' shortcut? and does this mean I shouldn't use the UserChangeForm anywhere other than the admin site, because of the security issue mentioned in the docs? -
Django how to not comment some lines with makemessages
Problem I translate my group names in my Django application with the default translation tools. Since my group names are not hard-coded in my code, when I run makemessages, the lines corresponding to my group names are commented out. Example I have a group named management_product which is automatically created during migrations. I put these lines in django.po: msgid "management_product" msgstr "Gestion des produits" But if I run django-admin makemessages -l fr, they are commented out: #~ msgid "management_product" #~ msgstr "Gestion des produits" Question How can I disable this behaviour?