Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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?? -
How is the super method to be used in Django?
I don't want you to think I would be lazy. I already read about the super method to override pre-existing methods in Django (and possibly also in Python in general). Still I must admit that I did not really understand everything. So, instead of asking for a particular application of the method, I wanted to ask how this method can be applied. Sounds weird or too broad? Perhaps it helps, if I describe my problem. Let's say I want to enhance a class-based view. My experience with them is also limited. Very often, pages on the web just say, "yeah, you have to override this or that method." Me, "Ehm, how do I actually know about the existence of this or that method?" So far, I have to come to know a few like get, post and form_valid, but I do not know in general which are available or where I have to read them up, as I guess that they are in subclasses of subclasses of subclasses in some general files and I don't even know where those are. So, imagine I have found the corresponding method, then I do not know how to handle that. Here is an … -
Activate or De-Activate Status in database through Ajax-JavaScript using Django (help)
I am trying to implement a function using Ajax-JavaScript in which when I click on Activate Option, the value in my Django database for this field changes to 'Active' and is displayed on the HTML page as active with Activate Message. If De-Activate is clicked, the text changes to De-Active along with it's value in the django database and show De-Activated message HTML page: <div class="col-sm-5"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">Job activation status</h3> </div> <div class="panel-body"> <td> Campus Name </td> <td> hod_name </td> <td> <select name="status" class="form-control"> <option value="1">Active</option> <option value="2">Disabled</option> </select> </td> </div> </div> </div> Model: class Campus(models.Model): STATUS = ( ('Active', 'Active'), ('Disabled', 'Disabled'), ) campus_name = models.CharField(blank=True, max_length=30) hod_name = models.CharField(blank=True, max_length=25) status = models.CharField(max_length=10, choices=STATUS, default='Disabled', blank=True) def __str__(self): return self.campus_name View: def status_update(request, pk): campus_status = get_object_or_404(Campus, pk=pk) campus_status.status = 'Active' if campus_status.status == 'Disabled' else 'Disabled' campus_status.save(update_fields=['status']) messages.success(request, '{} Status: {} successfully'.format(campus_status.campus_name, campus_status.status)) return redirect('/dashboard/create_campus/') -
Version control with lightsail
I've uploaded the code on amazon lightsail with cloning from github It's a django My question is the code works but if i change and commit changes to the repo will i have to re upload and recreate the lightsail instance? -
Django-tenants Schema, need to create centralized authentication (django.contrib.auth)
My purpose is to create a multitenant application able to serve several companies. The requirements that I need are to have centralized authentication (django.contrib.auth) in order to have a central login page where after the user has correctly logged in, it will be redirected to the correct subdomain/schema. Each company will manage its own users but I want them to be stored in the public schema because I need to access also remotely using Web services to a centralized and fixed URL. In addition to that, I've to extend the User Model to add additional information. So in my public tenant, I want to have: Company User (django.contrib.auth) please help me out in this with your suggestion or any documents will be helpful for me. -
UpdateView define primary key
I am trying to set my primary key in a class based view to a unique value from my models. models.py from django.db import models from django.forms import model_to_dict class Stuff(models.Model): thing = models.CharField(max_length=100, verbose_name="Thing", unique=True) item = models.CharField(max_length=100, verbose_name="Item") def __str__(self): return self.thing def toJSON(self): item = model_to_dict(self) return item views.py from django.urls import reverse_lazy from django.views.generic import CreateView, UpdateView class NewStuff(CreateView): model = Stuff form_class = NewStuffForm template_name = 'stuff.html' success_url = reverse_lazy('search_stuff') def post(self, request, *args, **kwargs): data = {} try: action = request.POST['action'] if action == 'add': form = self.get_form() data = form.save() else: data['error'] = "No option has been selected" except Exception as e: data['error'] = str(e) return JsonResponse(data) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'New Stuff' context['stuff_url'] = reverse_lazy('search_stuff') context['action'] = 'add' return context class EditStuff(UpdateView): model = Stuff form_class = NewStuffForm template_name = 'stuff.html' success_url = reverse_lazy('search_stuff') def dispatch(self, request, *args, **kwargs): self.object = self.get_object() return super().dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): data = {} try: action = request.POST['action'] if action == 'edit': form = self.get_form() data = form.save() else: data['error'] = '"No option has been selected" except Exception as e: data['error'] = str(e) return JsonResponse(data) def get_context_data(self, **kwargs): … -
how to create side nav in djnago and load without reloading?
I am trying to create a sidenav in djnago and load menu in same page without reloading page. example ( about , contact , work load in same page ) Search a lot but and found AJAX but at last i cant figure out how to do this. can any one help me on this with code. I want to create something like this -
Which database design is better for django follow/unfollow?
I've been looking for a good database design for a twitter like social network site in my django project and I found two possibilities: This one down here class Following(models.Model): follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name='following') following = models.ForeignKey(User, on_delete=models.CASCADE, related_name='followers') And this other one class User(AbstractUser): follows = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followed_by') pass Are these the same? Is there any difference here? Which one should I choose? I'm kind of new to this so I can`t figure out which one is the best option. I find the first one easier to understand.