Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using same methods in two models
i am customizing slug method for auto generating and i am using like this models.py class Category(TimeStamp): name = models.CharField(max_length=255) slug = models.SlugField(max_length=100, unique=True) def __str__(self): return self.name def _get_unique_slug(self): slug = slugify(self.name) unique_slug = slug num = 1 while Category.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 return unique_slug def save(self, *args, **kwargs): if not self.slug: self.slug = self._get_unique_slug() super().save(*args, **kwargs) I am using this _get_unique_slug method in another model. But I wander if there is beautiful way to right this in mixins. I mean without writing get_unique_slug for each model. How do I this? Thank you? -
how to return value from database using django and ajax
i have a dropdown list that display the data from the database. i need to make dynamic using jquery and ajax where it will hide some values based on the user input on another field. my question is how to hide the required option based on the returning ID. the error that i get is : Could not parse the remainder: '=="dep D"' from 'sources.source_name=="dep D"' views.py def getSource(request): sources = Source.objects.all() return render(request,'create_folder.html',{'sources':sources}) create_folder.html <div class="formSelect" id="mouresaleMasdarDiv"> <select id="mouresaleMasdar" name="gender" required> <option value="">-- soource--</option> {% for source in sources %} <option val="{{ source.source_name }}"> {{ source.source_name }} </option> {% endfor %} </select> </div> <script type="text/javascript"> $('#mouresaleMasdar option[value="{{sources.get(pk = 1)}}"]').hide() </script> It gives an error so how to make this value hidden based on the id. -
Right way to get CreateView with modelformset_factory with multi forms
I have a skill model whose instances belong to different categories (eventually around 10). I will use 2 categories to reduce the code. For example, 2 categories: frameworks: django, angular etc. language: python, java etc. I need the user to add all the information about himself on one page at once. I made two forms with different querysets that only give Skills instances belonging to a separate group and two Formset forms.py class SkillBaseCreateForm(forms.ModelForm): YEAR_CHOICES = [(r, r) for r in range(1, 11)] LAST_YEAR_CHOICES = [(r, r) for r in range(1980, datetime.datetime.now().year + 1)] year = forms.CharField( widget=forms.Select(choices=YEAR_CHOICES), ) last_year = forms.CharField(widget=forms.Select(choices=LAST_YEAR_CHOICES)) class Meta: model = Skill fields = ['technology', 'level', 'last_year', 'year'] class SkillCreatePLanguageForm(SkillBaseCreateForm): def __init__(self, *args, **kwargs): super(SkillCreatePLanguageForm, self).__init__(*args,**kwargs) self.fields['technology'].queryset = Technology.objects.filter(group_id='3') class SkillCreateFrameworkForm(SkillBaseCreateForm): def __init__(self, *args, **kwargs): super(SkillCreateFrameworkForm, self).__init__(*args,**kwargs) self.fields['technology'].queryset = Technology.objects.filter(group_id='2') formset SkillFrameworkFormSet = modelformset_factory(Skill, form=SkillCreateFrameworkForm, extra=4, max_num=4, can_delete=False) SkillPLanguageFormSet = modelformset_factory(Skill, form=SkillCreatePLanguageForm, extra=4, max_num=4, can_delete=False) views.py class SkillTestCreateView(AuthorizedMixin, CreateView): model = Skill form_class = SkillCreatePLanguageForm template_name = 'skill_create.html' def get_context_data(self, **kwargs): context = super(SkillTestCreateView, self).get_context_data(**kwargs) context['formset_framework'] = SkillFrameworkFormSet() context['formset_planguage'] = SkillPLanguageFormSet() return context def post(self, request, *args, **kwargs): self.object = None formset_framework = SkillFrameworkFormSet(request.POST) formset_planguage = SkillPLanguageFormSet(request.POST) if formset_framework.is_valid() and formset_planguage.is_valid(): return self.form_valid(formset_framework, formset_planguage) else: … -
Set model field set default to iterator
I'm trying to set reportNr field default to a number that iterates every time a report has been added. Is there any way to do this? In models.py: from django.db import models class RapportQuerySet(models.query.QuerySet): def active(self): return self.filter() class RapportManager(models.Manager): def get_queryset(self): return RapportQuerySet(self.model, using=self._db) def all(self): return self.get_queryset().active() class Rapport(models.Model): objects = RapportManager() reportNr = models.TextField(blank=True, default="?") avd = models.TextField(max_length=10, null=True, blank=True) ritningNr = models.TextField(max_length=20, null=True, blank=True) enhetsNr = models.TextField(max_length=40, null=True, blank=True) atgard = models.TextField(max_length=100,null=True, blank=True) namn = models.TextField(max_length=100,null=True, blank=True) anstNr = models.TextField(max_length=100,null=True, blank=True) date = models.DateTimeField() file = models.FileField(null=True, blank=True) def __str__(self): return self.reportNr -
Django APPEND_SLASH doesn't work properly
if i write example.com/example-example it is working. However if i write example.com/example-example/ it doesn't work APPEND_SLASH=True in settings.py path('<slug:slug>',post_detail,name="post_detail"), -
How can I troubleshoot issues with a circus socket?
Environment: NGINX Django Python Circus I have a website that was returning 504 errors on various pages. In the nginx error log I was getting the following errors: [error] 30117#0: *280231 upstream timed out (110: Connection timed out) while reading response header from upstream, client: xxx.xxx.xxx, server: www.website.com, request: "GET /en/path/page/ HTTP/1.1", upstream: "http://unix:/tmp/glp-circus.sock/en/path/page/", host: "www.website.com" I increased the execution timeout for the server and these pages appear to be loading, however they are very slow. According to the browser, the TTFB is over 2 minutes. Presumably the socket for GLP is still causing the issue. How can I go about troubleshooting sockets which are managed by Circus? I have checked that the GLP socket is active. https://circus.readthedocs.io/en/latest/ -
Django 2.2 admin actions not displaying after adding materialize css
i'm learning how to customize the admin interface , my problem now is that the action select form ( where u can select an action and perform it clicking "GO" button) is not displaying at all it is because i added materialize and it's not respecting materialize structure , i wanted to EDIT the html but it seems to be PRE-RENDERED somehow somewhere ( what i tried : i checked the docs , i searched inside the admin app ), any clue on how to make my custom SELECT FORM while keeping the default functionality? any suggestions are highly appreciated. -
Live refresh of data in the admin site
I am working with Django mostly in the admin site. I use a background thread to connect with an another application, which long story short, manages to make some changes in the database (periodically) so in some model fields as well. What I want is when there is a change to be updated in the admin page as well without having to manually refresh it. I am trying to use channels (v2) to do that but I don't seem to really understand how to do that. To be more precise I tried to follow this tutorial. What I have so far is: settings.py ASGI_APPLICATION = 'myapp.routing.channel_routing' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [('localhost', 6379)], }, } } routing.py channel_routing = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url(r"^myapp/mymodel/", MyConsumer), ] ) ) ) }) asgi.py os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings") django.setup() application = get_default_application() consumers.py class MyConsumer(AsyncConsumer): async def websocket_connect(self,event): await self.send({ "type": "websocket.accept" }) await self.send({ "type": "websocket.send", "text": "This is a test" }) async def websocket_receive(self, event): print("receive", event) async def websocket_disconnect(self, event): print("Disconnected", event) And finally my JS code in my template extension: {% extends 'admin/change_list.html' %} {% load i18n admin_urls %} {% block object-tools-items %} <script> … -
Refresh Django template while maintaining scroll position
I have a Django template where I call a view by clicking a button. The view function returns a HttpResponseRedirect to the same page. I want the page to return/refresh to the same scroll position as when the user clicked the button. Here's what I've tried so far: Attempt 1: Based on this and this, I added an onsubmit to the form as follows: <form action="{% url 'buy' market.id %}" method="post" onsubmit="return refreshToSameScroll()"> ...calling location.reload() through the following script: <script type="text/javascript"> function refreshToSameScroll() { location.reload(); } </script> But that didn't work. Attempt 2: I then tried the following combination, reworked from this: <form action="{% url 'buy' market.id %}" method="post" onsubmit="return saveScroll()"> ...with this script: <script type="text/javascript"> function saveScroll () { var page_y = document.getElementsByTagName("body")[0].scrollTop; window.location.href = window.location.href.split('?')[0] + '?page_y=' + page_y; } window.onload = function () { if ( window.location.href.indexOf('page_y') != -1 ) { var match = window.location.href.split('?')[1].split("&")[0].split("="); document.getElementsByTagName("body")[0].scrollTop = match[1]; } } </script> The idea here being that clicking the button saves the scroll position, which then gets picked back up once the page reloads/refreshes. But that didn't work either. Any idea what I'm doing wrong? -
Passing a jira object from django view method to another unique to that session
All in the Django Views I have a login method which takes the username/password and logs a user in using the python ldap method Also the same credentials authenticate and make a jira object (Can be done as both are based on the same Active Directory) in login method def login(request): .... conn = ldap.initialize(....) conn.simple_bind_s(username, password) <-- user params jira = JIRA('server' , basic_auth=(username,password)) this jira object needs to be sent to a different view unique to that logged in session where that object has work done to it and avoids the user having to put in the creds again I tried global variables but that isnt unique to the session I tried Django's session variable request.session['jira'] = jira but i get a non serializable error How would i get this object from the login method to the desired view method -
Retrieving answered (not empty/null) questions from one_to_one relationship
I created a website where a User can create a project. Once the project is created, the user can answer 10 macroquestions (named: Firstquestion, Secondquestion...). Each of this macroquestion, contains a sub question (named: first_one, first_two...). For example: Project.Firstquestion.first_one will result in the first answered subquestion for the macroquestion Firstquestion Project.Secondquestion.second_one will result in the first answered subquestion for the macroquestion Secondquestion The user is not obliged to answer any of the subquestion. It can leave them blank. I want to do some calculation on how many subquestions the user has answered over the total of subquestions. Therefore, to retrieve if the user answered the questions I tried the following: def project_first_questions(request, project_id): answered_first = 0 not_answered_first =0 project = get_object_or_404(Project, pk=project_id) projects = Project.objects.all() first_one = project.firstquestion.first_one first_two = project.firstquestion.first_two first_three = project.firstquestion.first_three first_four = project.firstquestion.first_four first_five = project.firstquestion.first_five first_six = project.firstquestion.first_six first_seven = project.firstquestion.first_seven first_questions = [first_one, first_two, first_three, first_four, first_five, first_six, first_seven] for answer in first_questions: if answer: answered_first = answered_first + 1 else: not_answered_first = not_answered_first + 1 percentage_answered_first = round(float(answered_first / len(first_questions)), 2) percentage_not_answered_first = round(float(not_answered_first / len(first_questions)),2) return percentage_answered_first, percentage_not_answered_first The above does work HOWEVER I think there is an easier way using the … -
Upon logout i m still able to access the page (which is after login) without login required (by typing URL)
Problem Description : - When i login (i m redirected to the page required page) and after that when i logout and then type the URL of the page (present after login) i m still able to access the page (present after login without login required) i tried deleting session, cookies, even set_expiry() and also i read the documentation that logout() does that but all in vain. here's the code i tried:- In views.py def login_view(request): context = {} if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user: login(request, user) return HttpResponseRedirect(reverse('IP form')) else: messages.error(request,'Please provide valid credentials') return render (request,"first_app/login.html", context) del request.set_session['username':username] del request.session['password':password] del request.delete_cookie['username': username] del request.delete_cookie['password':password] else: return render (request,"first_app/login.html", context) @login_required def user_logout(request): if request.method == "POST": logout(request) del request.session['username':username] del request.session['password':password] del request.delete_cookie['username': username] del request.delete_cookie['password':password] #auth.logout(request) return HttpResponseRedirect(reverse('login')) @login_required def form_name_view(request): if not request.user.is_authenticated: response = HttpResponseRedirect('') response.delete_cookie('username') response.delete_cookie('password') del response.session['username'] del response.session['password'] return response # del request.session['username'] # del request.session['password'] # return HttpResponseRedirect(reverse('login')) if request.method == "POST": form = CmdForm(request.POST) settings.py SESSION_EXPIRE_SECONDS = 2 SESSION_EXPIRE_AFTER_LAST_ACTIVITY = True thnx to those willing to help.! :-) -
Reloding <div> element without refreshing page
I'm working with Django. I have a voting app where people propose topics so the topics have to be automatically refreshed to every user every 5 seconds. I know I have to use an Ajax request to reload my div class = "topics" so I tryied many different codes: </script> <script type="text/javascript"> $('.topics').setTimeout(function(){ $.ajax( { type:"GET", url: "/mylogin/{{both.0.id}}/{{both.1.id}}", success: function( data ) { $("/mylogin/{{both.0.id}}/{{both.1.id}}" ).load(".topics"); $("todo.html" ).load(".topics"); $(".topics" ).load("todo.html"); $(".topics" ).load("/mylogin/{{both.0.id}}/{{both.1.id}}"); $("/mylogin/{{both.0.id}}/{{both.1.id}}" ).reload(".topics"); $("todo.html" ).reload(".topics"); $(".topics" ).reload("todo.html"); $(".topics" ).reload("/mylogin/{{both.0.id}}/{{both.1.id}}"); $('topics' ).load(); } }) }, 1000); And I have also tried this: window.setTimeout(function () { $(".topicos" ).load("/mylogin/{{both.0.id}}/{{both.1.id}}"); }, 1000); And also this: window.setTimeout(function () { $(".topicos" ).load("todo.html"); }, 1000); </script> none of these pieces of code reload anything and I can´t understand if maybe in django we need to code differently -
how to import import_module using importlib?
C:\Users\admin\Desktop\projects\quote>python manage.py runserver Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 2, in <module> from importlib import import_module ImportError: cannot import name import_module -
Django DRF - add a sub view/url?
I am wanting to create a sub view (if this is the right term?) under a view that alters the query set for example parent URL mysite.com/api/sites Child URL mystic.com/apit/sites/open and also each one of those URLS could be searched so parent URL mysite.com/api/sites/search=London Child URL mystic.com/api/sites/open/search=London my parent View, serialiser, and URL already exists class SiteROView(viewsets.ReadOnlyModelViewSet): queryset = Site.objects.all() serializer_class = SiteSerializer permission_classes = (IsAdminUser,) filter_class = Site filter_backends = (filters.SearchFilter,) search_fields = ('location','postcode','state') so I think I need to somehow add the suburl to that class SiteROView(viewsets.ReadOnlyModelViewSet): queryset = Site.objects.all() serializer_class = SiteSerializer permission_classes = (IsAdminUser,) filter_class = Site filter_backends = (filters.SearchFilter,) search_fields = ('location','postcode','state') def url_open: queryset = Site.objects.filter(state='open') Is this possible, and how would I achieve it? Thanks -
I need help in designing a database (and signup and login on base of their role )in which there are three user
I want make sign up and login on the base of their role there admin can add users and approved the request of other two user so that they can login.When user click on the sign up the user see sign up page accorading to their roll and same for login . -
how to get rid off RecursionError: maximum recursion depth exceeded in comparison
I have written code for a user feedback form, but i get error called "RecursionError: maximum recursion depth exceeded in comparison". I have tried to add "import sys" in order to increase the default recursion depth limit by changing the number of limit in "sys.setrecursionlimit(1000)" but still I get the same error. views.py def ContactForm(request): submitted = False if request.method == 'POST': query_form = ContactForm(request.POST) if form.is_valid(): cd = query_form.cleaned_data # assert False return HttpResponseRedirect('/ContactForm?submitted=True') else: form = ContactForm(request) if 'submitted' in request.GET: submitted = True return render(request, 'ContactForm/contact.html', {'query_form': query_form, 'submitted': submitted}) -
When accessing a resource on website a forward slash gets removed from url when redirecting to https
I have an Nginx serving my django application. When I try to access example.com/resource it should redirect to https://example.com/resource but in my case it redirects to https://example.comresource (removing the / before resource) I have a very minimal Nginx configuration (as you'll see below). I don't know where to start to figure out what's wrong. server{ listen 443; listen [::]:443 ssl; ssl on; ssl_certificate /etc/ssl/example_com.crt; ssl_certificate_key /etc/ssl/example_com.key; server_name example.com; location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } location /static/ { autoindex on; alias /home/administrator/example/collectedstatic/; } location /media { alias /home/administrator/example/store; } } server { listen 8000; server_name localhost; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { autoindex on; alias /home/administrator/example/collectedstatic/; } location /media { alias /home/administrator/example/store; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } There are no error messages, just a webpage not found. -
Django: How to get setUpTestData to run once for all tests?
I am running django + django_tenants + django_restframework. In the mulit-tenant environment, there needs to be an instance in the tenants table for each schema - in my testing, that means "public", "test", and "test2". Creating those tenants, and their corresponding schemas, need to be created for all tests. The data in those instances will not change, so I want to do this once at the beginning of the test run, and not have it repeated again for the duration. The things I've learned from my research: setUp() runs before each individual test setUpClass() runs before each test case setUpTestData() runs before each test case The problem I've run into is, when my second set of tests run, I get exceptions when trying to create the tenants/schemas because they already exist. I've also found setup_databases() in the Django advanced testing doc and am wondering if that is the place for this... i.e. can it be subclassed? This is my base class that all tests subclass from... class TenantTestCase(APITestCase): public_tenant = None test_tenant = None test2_tenant = None @classmethod def setUpClass(cls): cls.add_allowed_test_domain() cls.setUpTestData() @classmethod def setUpTestData(cls): print('run setUpTestData') cls.public_tenant = Tenant.create_tenant('Public') cls.test_tenant = Tenant.create_tenant('Test') cls.test2_tenant = Tenant.create_tenant('Test2') connection.set_tenant(cls.public_tenant) I read that … -
RichTextUploadingField does not save html tags
I'm using a RichTextUploadingField, but it does not save tags. # from ckeditor_uploader.fields import RichTextUploadingField used # in first line text = RichTextUploadingField(verbose_name='text', blank=True) after using this code it will show an editing box for text. but if I set a text to be some tag like , next time I try to edit entered text, it's not set to be also in my website it does not show it as an . -
subclass model auto increment does not with inheritmodel with autofiled in django
I defined a base class in django model like below class BaseModel(models.Model): id = models.AutoField(primary_key=True) timestamp = models.DateTimeField(auto_now_add=True) class Meta: abstract = True and I defined another class for actual model class Destination(BaseModel): city = models.CharField(max_length=100) I thought that when i create a Destination obeject dest = Destination(city='New York') dest.save() It'll automatically create an id, but apparently not. I got following error: NOT NULL constraint failed: tripmatch_trip.destination_id So how to use model inheritance and autofield correctly in django Thanks -
Validation of a Django model using a foreign key set after saving the form
I'm trying to do validate a Model based on a value that I set after save(commit=False). How can I achieve this? I have multiple Forms (Item, Listing, Price) that I combine in one view and then create one instance after the other while saving. # models.py ... class Category(models.Model): ... class Item(models.Model): category = models.ForeignKey(Category, ...) class Listing(models.Model): for_item = models.ForeignKey(Item, ...) class Price(models.Model): for_listing = models.ForeignKey(Listing, ...) amount = MoneyField(...) class MinPriceForCategory(models.Model): category = models.ForeignKey(Category, ...) amount = MoneyField(...) # views.py ... def add_item(self): ... # create form instances from request.POST etc ... item = form_item.save() listing = form_listing.save(commit=False) listing.for_item = item listing.save() # validation happens in the first call to save() price = form_price.save(commit=False) price.for_listing = listing # I need the validation to happen here so the instance of Listing is available price.save() -
Adding an InlineField to a ClusterableModel does not work
I have a Page class called EventDetail which in turn holds several messages (to be sent out via a cronjob). This is done as shown in the docs here: https://docs.wagtail.io/en/v2.5.1/reference/pages/panels.html?highlight=available%20panel%20types#inline-panels The thing is that I also want to be able to append several files to each message. But now I am not on a Page class any more, and I cant get it to work. I read on other forum posts, that it is possible to to this by making the model that should hold the InlinePanel into a ClusterableModel, but I cant get it to work. When doing this I get the following when accessing the page: FieldError at /admin/message/eventdetailmessage/create/ Unknown field(s) (files) specified for EventDetailMessage My code: class Message(models.Model): """ An abstract model of messages connected to an eventdetail """ title = models.CharField(max_length=255, blank=True) content = models.TextField() send_time = models.DateTimeField(verbose_name=_("Message send time")) sent = models.BooleanField(default=False) @property def edit_link(self): return self.url_helper.get_action_url("edit", self.id) @property def delete_link(self): return self.url_helper.get_action_url("delete", self.id) @property def create_link(self): return f"{self.url_helper.get_action_url('create')}?id={self.event_detail.id}" panels = [FieldPanel("title"), FieldPanel("content"), FieldPanel("send_time")] class Meta: abstract = True class EventDetailMessage(ClusterableModel, Orderable, Message): """ The actual implementation. Done like this in case we want do use wagtails built in functionality for creating on the fly. … -
how to get the value from the database based on the id
i have a dropdown list that display the data from the database. i need to make dynamic using jquery and ajax where it will hide some values based on the user input on another field. my question is how to hide the required option based on the returning ID. views.py def getSource(request): sources = Source.objects.all() return render(request,'create_folder.html',{'sources':sources}) create_folder.html <div class="formSelect" id="mouresaleMasdarDiv"> <select id="mouresaleMasdar" name="gender" required> <option value="">-- soource--</option> {% for source in sources %} <option val="{{ source.source_name }}"> {{ source.source_name }} </option> {% endfor %} </select> </div> <script type="text/javascript"> $('#mouresaleMasdar option[value="{{sources.get(pk = 1)}}"]').hide() </script> It gives an error so how to make this value hidden based on the id. -
Django - FileFields are not saved in db
I'm trying to create a form where admins could upload some file with FileField. Here is what I currently have: models.py class PhytoFile(models.Model): date = models.DateTimeField("Date", default = datetime.datetime.now) general_treatment = models.FileField("Traitements généraux", upload_to='fichiers_phyto/', blank=True, null=True) other = models.FileField("Autres traitements", upload_to='fichiers_phyto/', blank=True, null=True) class Meta: verbose_name = "Liste - Fichier phyto" verbose_name_plural = "Liste - Fichiers phyto" def __str__(self): return str(self.date) views.py class AdminFichiersPhyto(CreateView): template_name = 'phyto/phyto_admin_fichiers.html' model = models.PhytoFile fields = ['general_treatment', 'other'] def form_valid(self, form): form.save() if self.request.POST.get('autre'): # gonna add some code to read the 'other' file print("autre") if self.request.POST.get('trtm_gen'): # gonna add some code to read the 'general_treatment' file print("traitement généraux") return HttpResponseRedirect(self.request.path_info) When I click on the Submit button created in a template, in the admin page I got a new line in my table, but the file I targeted with the FileField hasn't been saved. Do any of you have any idea of where it could come ?