Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Skype API connection issue
I try to develop an django app that collect everything in skype and pass to mysql. I deployed my app and mysql db on to azure. The app run perfectly fine locally, i can login to skype, retrieve messages etc. also pass all of those into mysql that i setup in azure. But the app on azure is unable to connect to skype though skpy(skype api for python). Do anyone know how to solve it? Or know the problems? -
How can I start Gunicorn without disabling SELinux?
I'm trying to make a tiny website with Django + Gunicorn + Nginx on CentOs. But the only problem is that I can't start Gunicorn without changing SELinux to disabled or permissive mode. Many articles say that I'd rather to turn off the SELinux, but I'm worried about some security problems that can happen as I'm almost new to Django and Gunicorn. Is there a way to use Gunicorn with SELinux successfully? -
When React requests to Django API, net::ERR_SSL_PROTOCOL_ERROR is occured
Stack : AWS Lightsail, React, DRF, Django, Gunicorn, NGINX I created certificate using Let's Encrypt. ※ I followed this site : https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-16-04 So, I can access https://mydomain without error. But when React calls Django API, net::ERR_SSL_PROTOCOL_ERROR is occured. I think there's something I need to set up in React, DRF, Django. Cause no error logged in syslog and /var/log/nginx/error.log. I googled but couldn't find what I wanted. Can I ask for advice? Thank you. -
Modal form initial field
In my app a have form to update item. User updates it using dropdown fields. If there is no required value on dropdown he can add his own. It is done through the popup bootstrap modal form. Problem is that if the modal form is submitted user is redirected to form view but all values that we had already entered disappears. I'm not looking for ready solution but a hint how to make it, because I am learning and I would like to now how it should be done properly. Clicking "new person" opens the modal form. I don't want to make use choose subsidiary twice as a person belongs to the subsidiary. If the new user is added all values filled by user disappears because I'm redirecting from modal to the point where the user is starting the update. The modal form opens when the user chooses a new person form dropdown list: jquey: $("#id_salesPersonDistributor").change(function () { var url = $("#subsidiaryForm").attr("data-salesPersonsDistributorContact-url"); var salesPersonDistributorId = $(this).val(); var id_sales = $(this).children(":selected").attr("id"); if (id_sales == "new") { $("#id_salesPersonDistributor").modalForm({ formURL: "{% url 'new_sales_person_distibutor' VCIUpdate %}" }); } else { $.ajax({ url: url, data: { 'salesPersonDistributor': salesPersonDistributorId }, success: function (data) { $("#salesPersonsDistributorContact").html(data); } … -
Django {% translate "Log out" %} does not follow translation literally
I am internationalizing my app and need to translate the string "Log out". However, Django does not follow my translation literally but translates "Log out" in its own way. In my specific example, I am trying to translate "Log out" to "Esci", its Italian equivalent. However, when I render the templates I get the translation "Annulla accesso", which roughly translates to "Undo access" in English. Additionally, I found that if I use {% translate "Logout" %} or even {% translate "Log Out" %} everything works as I would expect. Is there something particular about the string "Log out" that I should know? How can I override this behavior? Here is my HTML: {% load i18n %} {% block body %} <h1>{% translate "Hello" %}, {{ user.username }}</h1> <ul> <li>{% translate "Currently logged in as" %}: {{ user.username }}</li> <li><a href="{% url 'users:logout' %}">{% translate "Log out" %}</a></li> </ul> {% endblock %} And here is my .po file: #: users/templates/users/user.html:9 msgid "Log out" msgstr "Esci" Again, despite this, when rendered, "Log out" is translated "Annulla accesso". -
How to choose which web hosting service to use?
I am building an e-learning platform with Django, but I am not sure how and where to host it when finished. I don't fully understand the difference between the hosting services offered by Hostinger and AWS, and why Heroku is so popular in the Django community. How can I decide what is the best service to use? And, if the topic is too complex, where can I learn it? -
Django doesn't save on db with Crispy Forms
I'm trying to save on db but it doesn't work. Here's my Models.py from django.db import models # Create your models here. class Persona(models.Model): name = models.CharField(max_length=50) birth_date = models.DateTimeField() reg_date = models.DateTimeField(auto_now_add=True, blank=True) address = models.CharField(max_length=30) phone_number = models.CharField(max_length=10) email = models.EmailField(max_length=254) Here's my Views.py from django.shortcuts import render, redirect from .forms import insert_values from .models import Persona from django.views.generic import TemplateView # Create your views here. class HomeView(TemplateView): def post(self, request, *args, **kwargs): try: form = insert_values(request.POST) if form.is_valid(): p = Persona( name=form.cleaned_data['name'], birth_date=form.cleaned_data['birth_date'], address=form.cleaned_data['address'], phone_number=form.cleaned_data['phone_number'], email=form.cleaned_data['email'], ) p.save() return redirect('home') except Exception as err: errore = err.__str__() The post call works and the request is redirected, but in the object p I got the exception "AttributeError: Manager isn't accessible via 'Persona' instances". How can I solve this? -
Django Background Tasks : Set Max Run Time To Infinity
How to set max run time of django background tasks to infinity. -
How to display Data in Ascending and Descending Order in Django?
I am creating my custom admin panel in Django, i don't want to use django default admin panel, But i want sorting filters in dajngo, If a user click on email then email should be in ascending order, and if the user click again on email then the emails will be in descending order, Please let me know how i can do it. Here is my models.py file... class Model1(models.Model): email= models.Charfield(blank=True) phone= models.Charfield(blank=True) here is my views.py file... def display_data(request, id): test_display=Model1.objects.all() return render(request, 'page.html', {'test_display':test_display}) here is my page.html file <th><a href="javascript:void()">Email (CLick on this field)</a></th> {% for i in test_display %} <tr> <td> {{i.email}} </td> </tr> {% endfor %} -
I don't understand how to host a Django and React Web App
I am Using Django Rest Framework as an independent backend and ReactJS as the independent frontend, how will i go about hosting this kind of web application and what web hosting service would you recommend that fits this technology stack? Most Tutorial use webpack to embed react into django but i want to use them independently -
Django:how to render template and send context to template with ajax?
(sorry for my bad english) Hello.I know partly how ajax is used with django.but I have some problems.Some of them are: how to render template with ajax? How to send django to template with ajax? I searched the internet but I couldn't find exactly what I wanted. I would be glad if you could also recommend a detailed resource on the use of ajax and django. (free:( ).please help me guy.thanks now. -
Serialize an annotated and aggregated queryset to GeoJSON
I am trying to use Django ORM (or any other way using Django) to execute this query (PostgreSQL) AND send the result back to the front end in GeoJSON format. SELECT string_agg(name, '; ' ORDER BY name), geom FROM appname_gis_observation where sp_order = 'order1' GROUP BY geom; The model looks like this: class gis_observation(models.Model): name = models.CharField(max_length=100,null=True) sp_order = models.CharField(max_length=100,null=True) geom = models.MultiPointField(srid=4326) So I thought this would work: results = gis_observation.objects.values('geom').filter(sp_order='order1').annotate(newname=StringAgg('name', delimiter='; ')) data_geojson = serialize('geojson', results, geometry_field='geom', fields=('newname',)) return render(request, "visualize.html", {"obs" : data_geojson}) The ORM query works fine in the Django shell. In the view, Django complains at the serialize step: 'dict' object has no attribute '_meta' . Apparently because it is expecting a queryset and not a Valuesqueryset. Even if the serialize step worked, I suspect it would skip my annotated field (by reading other posts) Apparently I am not the only one who met that same problem but I could not find a definitive solution to solve this. Here is what I tried after reading other posts: converting 'ValuesQueryset' to a 'dict' (but then the problem is that json cannot serialize the 'Multipoint' geom field) def ValuesQuerySetToDict(vqs): return [item for item in vqs] ... data_dict … -
How to hide default label Django Model forms?
My Model class. When I use the model forms, with {{form}} tag, I get a default label filed, for each element. Can I remove that from meta class defination? class message(models.Model): name = models.CharField(max_length=30) email = models.EmailField(max_length=40) contact = models.IntegerField(max_length=15) message = models.CharField(max_length=1000,blank=True, null=True) My form class. class MessageForm(forms.ModelForm): class Meta: model = message fields = '__all__' widgets = { 'name' : forms.TextInput(attrs={"value":"Name", "onfocus":"this.value = '';","onblur":"if (this.value == '')","required":""}), 'email' : forms.TextInput(attrs={"value":"email", "onfocus":"this.value = '';","onblur":"if (this.value == '')","required":""}), 'contact' : forms.TextInput(attrs={"value":"contact", "onfocus":"this.value = '';","onblur":"if (this.value == '')","required":""}), 'message' : forms.Textarea(attrs={"value":"emmessage", "onfocus":"this.value = '';","onblur":"if (this.value == '')","required":""}) } HTML Code: <div class="col-md-6 mail_right"> <form action="" method="post" > {% csrf_token %} {{form}} </form> </div> -
ImportError: cannot import name 'passUser' from 'userUpdate.models'
Hello everyone I am trying to build a website with django that gets info from the form and makes api calls using those parameters. I am very newby on django and I build a model for this but i cannot import this model it says ImportError: cannot import name 'passUser' from 'userUpdate.models' (C:\Users\berat.berkol\SystemConsole\userUpdate\models.py) on Windows cmd. I tried this without making a model but if I don't use models i can't render the form to the template. Here is my home.html <div class="u-form u-form-1"> <form action="{% url 'userPassreset' %}" method="post" class="u-clearfix u-form-spacing-15 u-form-vertical u-inner-form" style="padding: 15px;" source="custom" name="send"> {% csrf_token %} <div class="u-form-group u-form-name u-form-group-1"> {{form.as_p}} {{form.username}} </div> <div class="u-align-right u-form-group u-form-submit u-form-group-6"> <input type="submit" value="Sadece Mesaj Gönder" class="u-active-white u-border-0 u-border-radius-10 u-btn u-btn-round u-btn-submit u-button-style u-palette-2-base u-btn-1" name="sendmessage"> </div> </form> </div> urls.py (App) app_name='userUpdate' urlpatterns = [ path('', views.userUpdate, name='home'), path('login/', LoginView.as_view( template_name='login.html'), name="login"), path('userPassreset',views.passResetView.as_view(),name='userPassreset'),] urls.py (Project) app_name='userUpdate' urlpatterns = [ path('admin/', admin.site.urls), path('login/',include('django.contrib.auth.urls')), path('', TemplateView.as_view(template_name='home.html'), name='home'),] models.py class passUser(models.Model): username = models.CharField(blank=False,max_length=100) password = models.CharField(blank=False,max_length=100) number = models.CharField(blank=False,max_length=100) message = models.CharField(blank=True,max_length=300) class Meta: verbose_name = "passUser" forms.py class userPassResetForm(forms.ModelForm): class Meta: model = passUser fields = "__all__" views.py @csrf_protect class passResetView(View): def get(self,request): form=userPassResetForm() return render('home.html') def post(self,request): passResetuser=self.model.objects.get(pk=2) … -
django oscar signals and receiver
oscar has some signals like post_checkout and order_status_changed that haven't any connection to receivers or I can't find them. can you help me where do you use them or where is their receiver functions? and if they are haven't receiver why do you implement that -
Prometheus + Django + gunicorn with --preload and multiple processes publishing just one port
I'm running django+prometheus+gunicorn, exporting /metrics using multiple processes per process, as described in django-prometheus documentation. When I run gunicorn with --reload and two workers, I can see how ports 8001 and 8002 are opened serving prometheus metrics, one per process. But when I run gunicorn with --preload, only port 8001 is opened. What do I need to do to get one prometheus endpoint per process while using --preload? djago-prometheus settings: PROMETHEUS_METRICS_EXPORT_PORT_RANGE = range(8001, 8020) PROMETHEUS_METRICS_EXPORT_ADDRESS = '' PROMETHEUS_EXPORT_MIGRATIONS = False Versions: django==3.1.0 prometheus_client==0.8.0 django-prometheus==2.1.0 gunicorn==20.0.4 -
Convert Python string to variable name in python[field_name = "status", value ="Completed"]
I have One String in python field_name = "status" value = "joined" I want to convert this string to some variable name like, status = "joined" Here am reffered this URL Convert string to variable name in python but here it happend only integer. not working string type of values any one help me -
Run an additional script after django server is started
I have a simple Django API that runs via docker-compose and I want to run a script bot.py after the server starts. How I can do this using docker? My Dockerfile FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install --upgrade pip RUN pip install -r requirements.txt COPY . /code/ And docker-compose.yml: version: '3' services: web: build: . command: bash -c 'python3 network/manage.py makemigrations && python3 network/manage.py migrate && python3 network/manage.py runserver 0.0.0.0:8000' volumes: - .:/code ports: - "8000:8000" I tried to add CMD [ "python", "./bot_new/bot.py" ] but it doesn't work actually -
Django: app-specific URL patterns translation
I am trying to internationalize a Django dictionary application using the Django translation system. I have successfully translated most of the content on the site but I am having problems translating URL patterns, with the exception of the admin page. My goal is to change the language of both content and URL based on prefix language code in the URL. For example: www.example.com/en/dictionary/define // (content in English) www.example.com/it/dizionario/definisci // (content in Italian) www.example.com/fr/dictionnaire/définis // (content in French) ... I checked the Django documentation on this (https://docs.djangoproject.com/en/3.1/topics/i18n/translation/#translating-url-patterns) but found it quite vague and could not really understand it. project-level urls.py: from django.conf.urls.i18n import i18n_patterns from django.utils.translation import gettext_lazy as _ from dictionary import views as dictionary_views urlpatterns = [ path('admin/', admin.site.urls), ] dictionary_patterns = ([ path('', dictionary_views.index, name='index'), path(_('define/'), dictionary_views.define, name='define'), path(_('define/<slug:headword_slug>'), dictionary_views.headword, name='headword'), ], 'dictionary') urlpatterns += i18n_patterns( path(_('dictionary/'), include(dictionary_patterns, namespace='dictionary')), ) app-specific urls.py (this code is probably incorrect, I have no clue on what to do here): app_name = "dictionary" urlpatterns = [ path("", views.index, name="index"), path("define", views.define, name="define"), path("define/<slug:headword_slug>", views.headword, name="headword"), ] Should I import the dictionary_patterns variable from the project's urls.py and add it to the app's urlpatterns list? Should I delete the app's urls.py file altogether? … -
how to map user model to customer model in django
I was working on an e-commerce website using Django for which I created a customer model in models.py class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200) def __str__(self): return self.name and when I register a new user on my site using this view: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('store') else: form = SignUpForm() return render(request, 'store/signup.html', {'form': form}) The user gets created but I get the error RelatedObjectDoesNotExist: User has no Customer I know it's because the User model is created but not Customer, I'm new to Django and want to know a way to map these two models at the time of registration. -
DJANGO: How to get multiple inputs from multiple forms in views together?
In html,opening one form first by clicking on it and then it will open another form where I take user inputs. Finally I need both the inputs...which form user click first and then inputs from the second form in views. But first form information getting erased and only second form information passing to views. FORM1: <form method="post" enctype="multipart/form-data" > {% csrf_token %} {% for node in tuples %} <button class="open-button" onclick="openForm()" name="html_node_number" value= {{node.list1|safe}} type="button"> </button> </form> FORM2: <form class="form-container" method="post"> {% csrf_token %} <button type="submit" class="btn" onclick="closeForm()" name="edit_nd_decision" value=1> Prune Back </button> </form> VIEWS: if request.method == 'POST': html_node_number=request.POST.get('html_node_number') edit_nd_decision=request.POST.get('edit_nd_decision') if edit_nd_decision == '1': m_editnd_no = int(html_node_number) -
Cannot resolve keyword 'blg' into field. Choices are: content, email, id, name, post, post_id
there are similar questions but still i am not able to figure out my mistake.. i am trying to make a comment system.. the comment model is working fine.. but when i try to edit my post detail view from this .. def detailview(request, id=None): blg = get_object_or_404(BlogPost, id=id) context = {'blg': blg, 'comments': comments, } to this def detailview(request, id=None): blg = get_object_or_404(BlogPost, id=id) comments = Comment.objects.filter(blg = blg).order_by('-id') context = {'blg': blg, 'comments': comments, } i am getting this error Cannot resolve keyword 'blg' into field. Choices are: content, email, id, name, post, post_id here are my other files... models.. class BlogPost(models.Model): title = models.CharField(max_length=500) writer = models.CharField(max_length=150,default='my dept') category =models.CharField(max_length=150) image = models.ImageField(upload_to='images') post = models.TextField(max_length=2000) Date = models.DateField( default=datetime.date.today) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(BlogPost , on_delete=models.CASCADE) name = models.CharField (max_length = 150) email = models.CharField (max_length = 150) content = models.TextField () def __str__(self): return self.email forms.py from django import forms from.models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('content',) views.py def detailview(request, id=None): blg = get_object_or_404(BlogPost, id=id) comments = Comment.objects.filter(blg = blg).order_by('-id') context = {'blg': blg, 'comments': comments, } -
Can't add user into ManytoManyField in Django?
I have a model called Class which has ManyToManyField with Student. Student model has a OnetoOneField with CustomUser model. When the CustomUser is created, the Student object is also created but why I got error with Student instance expected? I don't know where is my mistake. Can u spot me the mistake? When the Class object is created, it will generates a code and student has to enter that code to join the Class via ManyToManyField. I got error on this line class_code.student.add(user) in forms.py and return super().form_valid(form) in views.py. Error I got TypeError: 'Student' instance expected, models.py class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) class Class(models.Model): teacher = models.ForeignKey(CustomUser, on_delete=models.CASCADE) student = models.ManyToManyField(Student) random_code = models.CharField(max_length=250, default=uuid.uuid4().hex[:6]) class EnterCode(models.Model): student = models.ForeignKey(CustomUser, on_delete=models.CASCADE) code = models.CharField(max_length=50) forms.py class EnterCodeForm(forms.ModelForm): class Meta: model = EnterCode fields = ['code', ] def save(self): user = super().save(commit=False) user.save() code = str(self.cleaned_data.get('code')) class_code = Class.objects.get(random_code=code) class_code.student.add(user) class_code.save() return (user, class_code) the view for join class class JoinClass(LoginRequiredMixin, CreateView): template_name = "attendance/content/student/enter_code.html" login_url = '/' form_class = EnterCodeForm success_url = '/home/' def form_valid(self, form): form.instance.student = self.request.user return super().form_valid(form) here is the forms how I create User class StudentRegisterForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields … -
How do I get the loop to show up in the form? Django
Now I can loop to display the date information of the item. I wrote it to an HTML file. I want to show the data that I looped in the form. How can I do it? My requirement is to display the date information in a format with the forms.RadioSelect date format so that it can be selected for confirmation on the form. My fils.html <div class="p-4"> <ul> {% for item in order.items.all %} <li> <span>{{ item }}</span><span>฿{{ item.price }}</span> </li> {% for i in item.meal.meal.dates_available %} {{i}}<br> {% endfor %}<br> {% endfor %} </ul> </div> <form method="post" class="pt-2"> {% csrf_token %} {{ form.non_field_errors }} <div class="py-2"> {{ form.note.errors }} <label for="{{ form.delivery_date.id_for_label }}">delivery date</label> <div> {{ form.delivery_date }} </div> </div> <div> {{ form.address.errors }} <label for="{{ form.address.id_for_label }}">Address</label> <div> {{ form.address }} </div> </div> <input type="submit" value="Order"> </form> </div> From the code it returns something like this: Young Coconut by Lunia ฿120.00 8 September 2020 9 September 2020 -------------------------------------------------- delivery date o ............. o ............. example: date 08/09/2020 o ............. Address | | text area Order <-- Submit button I need the date information of the item Show in the Delivery Date forms. My forms.py from django import forms … -
Retreaving data from postgresql by pg_trgm
I'm developing Django app. This app retrieves data from postgresql by pg_trgm to make it faster. In local environment, it works well and fast, but ec2 environment, it takes a long time to get data and display on the result page. below are the performance of the two environments. Local PC Sort (cost=283.37..283.52 rows=58 width=1413) Sort Key: image_amount DESC -> Bitmap Heap Scan on test_eu (cost=52.86..281.67 rows=58 width=1413) Recheck Cond: (eng_discription ~ '.*remote controller.*'::text) -> Bitmap Index Scan on text_index (cost=0.00..52.84 rows=58 width=0) Index Cond: (eng_discription ~ '.*remote controller.*'::text) ec2 Sort (cost=283.27..283.41 rows=58 width=1410) Sort Key: image_amount DESC -> Bitmap Heap Scan on test_eu (cost=52.86..281.57 rows=58 width=1410) Recheck Cond: (eng_discription ~ '.*remote controller.*'::text) -> Bitmap Index Scan on text_index (cost=0.00..52.84 rows=58 width=0) Index Cond: (eng_discription ~ '.*remote controller.*'::text) Results are close, so I wonder why ec2 environment is slow. Please teach me where should I check? PS. My local PC's memory is 8GB and ec2 uses instance type of "t2.micro" it means memory is 1GB.Does it related to this problem??