Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: where is mark_safe located
The mark_safe function is located in django.utils.safestring and as far I could check always has been. Why are the different import locations examples on internet (Displaying HTML fields in django admin change list, https://books.google.sk/books?id=cuh1DwAAQBAJ&pg=PA260&lpg=PA260&dq=%22from+django.utils.text+import+mark_safe%22&source=bl&ots=uf4DbswGc_&sig=ACfU3U05BQVbH83g9GrvVmOWbMJqDivrkQ&hl=sk&sa=X&ved=2ahUKEwiovu67qpHlAhVHQMAKHRnnCZ4Q6AEwAnoECAcQAQ#v=onepage&q=%22from%20django.utils.text%20import%20mark_safe%22&f=false). More importantly why are these other imports (django.utils.html and django.utils.text) working. I have some in my project and until Django version bump to 2.2 my project was working fine. -
Trouble with an if statement in Django template : two equal string are not equal
I'm trying to build a table on my Django Website that will show all the client of a consultant company and for each company how many contract they still have to date My code seems to work but it show me two identical string and work as if they're not equal I tried to do this logic : I DO a for loop on every client to build my table (a row for each client) On my template for every client i'll do a forloop of every contrat to check if the contract-client is the client : if so i increment a var and at the end of this sub forloop i can show how much mission exist for each client Here's the code piece of my template : <table class="contenu"> <thead> <th>Nom client</th> <th>Domaine</th> <th> Missions en cours </th> <th>Modification </th> </thead> <tbody> {% for client in listeClients %} <tr> <td>{{ client.nomClient }}</td> <td>{{ client.domaineClient }}</td> {% with compteur=0 %} {% for mission in missionsEnCours %} {% if client.nomClient == mission.client %} {{compteur|augment}} <script>alert("Ca incrémente")</script> {% else %} <script>alert("{{ client.nomClient }} ---et--- {{ mission.client }}")</script> {% endif %} {% endfor %} <td>{{ compteur }}</td> <td><a href="">MODIFIER</a></td> </tr> {% endwith … -
How Can I Get ManyToMany Field Objects in ListView
I'm trying to use ListView for listing my videos. I have two table one is called Videos and other is Thumbnails. I've managed to list my videos successfully but I couldn't get the thumbnails. Here is my codes: My Model: class Thumbnails(models.Model): src = models.URLField() class Meta: verbose_name = "Thumb" verbose_name_plural = "Thumbs" def __str__(self): return self.src class Videos(models.Model): title = models.CharField(max_length=200) duration = models.CharField(max_length=10) views = models.IntegerField() rating = models.CharField(max_length=10) video_id = models.CharField(max_length=25) slug = models.SlugField(unique=True) tags = TaggableManager() thumbnails = models.ManyToManyField(Thumbnails,null=True,blank=True) class Meta: verbose_name = "Video" verbose_name_plural = "Videos" def __str__(self): return self.title My Views: class HomePage(ListView): model = Videos template_name = "home/main.html" ordering = ['-pk'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context My template: {% for obj in object_list %} <li> <div class="thumb"> <div class="thumb-content"> <a href="#"> {% for thum in obj.thumbnail %} <img src="{{ thum }}"> {% endfor %} <span class="duration"><i class="fa fa-clock-o"></i> {{ obj.duration }}</span> </a> </div> <div class="thumb-header" style="height: 45px;"> <h3>{{ obj.title }}</h3> </div> <div class="thumb-footer"> <span class="views"><i class="fa fa-eye"></i> {{ obj.views }}</span> <span class="like"><i class="fa fa-thumbs-o-up"></i> {{ obj.rating|floatformat:2 }}%</span> </div> </div> </li> {% endfor %} And the output is like this: <li> <div class="thumb"> <div class="thumb-content"> <a href="#"> <span class="duration"><i class="fa fa-clock-o"></i> … -
django request.session.clear() 和request.session.flush() difference?
django request.session.clear() 和request.session.flush() difference? What environment is used separately? request.session.clear() or request.session.flush() -
Django_apscheduler the same task is executed repeatedly
When I dynamically create a timed task with Django_apscheduler, the same task will be executed multiple times, temporarily locating the reason to uwsgi starting multiple processes, each process has established a scheduler, and multiple schedulers simultaneously execute the same timed task. How can I solve this problem I tried to use database fields as locks and database row locks when querying and modifying fields, but the requests were so frequent that an exception occurred. with transaction.atomic(): iLockStep = Timed_Task.objects.select_for_update().get(id=aTimeTask.id).lock_step if (iLockStep != 0): return aTimeTask.state = GOING aTimeTask.lock_step = 1 aTimeTask.save() -
submit button in django refreshes the page without saving
I am trying to save data in ORM via a form but when I click on the submit button all it does is refresh the page with the same data HTML <div class="form-group col-md-12 mb-0"> <button type="submit" class="btn btn-success">Save</button> <a href="{% url 'employee:warehouse_table' %}" class="btn btn-outline-secondary" role="button">Nevermind</a> </div> Views.py @method_decorator([login_required, employee_required], name='dispatch') class WarehouseFormView(CreateView): model = Warehouse fields = "__all__" template_name = 'packsapp/employee/warehouseForm.html' def form_valid (self, form): product = form.save(commit=False) product.save() messages.success(self.request, 'The Warehouse was created with success!') return redirect('employee:warehouse_table') -
Which method is better: Python SDK (server side) or JavaScript SDK (client-side) to add to and update cloud firestore?
I have a Django web application with a postgresql database on an AWS server. I want to keep this database in sync with a nosql cloud firestore database. We're using cloud firestore as the backend for a mobile app. This means that every form update or new object that is added to the web app needs to be in sync with cloud firestore. I'm able to update cloud firestore using the Python SDK when each form is submitted via the web app. However, I want to know if this is the best method to keep these two databases in sync. Each time a form is submitted, I have to import the firebase SDK, and then use the methods to update cloud firestore. Obviously, this will take time, but I'm unsure if this method is better, or if using the JavaScript SDK will be better. In essence, which method will perform better? -
Insert or update on table violates foreign key constraint (error)
I am trying to save form data into a postgres table 'Student_Events' that is linked via foreign key to the 'Student_INFO table' but keep on receiving an integrity error: 'insert or update on table "entry_student_event" violates foreign key constraint "entry_student_event_nsn_id_2499e7fd_fk_entry_student_info_id" DETAIL: Key (nsn_id)=(123556789) is not present in table "entry_student_info".' There is one student in Student_INFO that has the nsn '123556789' so I am unsure to why it "is not present" in that table. Any help would be greatly appreciated as I am quite new to Django and PostgresSQL, thanks Views.py: def Grouplist(request): student_list = Student_INFO.objects.order_by('name') for student in student_list: if request.method == 'POST': form = EntryForm(request.POST) context = { 'student_list':student_list, 'form': form } if form.is_valid(): event_save = form.save(commit=False) event_save.nsn_id = student.nsn event_save.save() return redirect('grouplist') else: form = EntryForm() context = { 'student_list':student_list, 'form': form } return render(request, 'grouplist.html', context) Models.py: class Student_INFO(models.Model): nsn = models.IntegerField(blank = False) birthdate = models.DateField("BirthDate", blank = False) name = models.CharField(max_length=30, blank = False) age_catagory = models.CharField(max_length=8, blank = True, default = '') grouproom = models.CharField(max_length=3, blank = False) year_lvl = models.IntegerField(blank = False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Student_Event(models.Model): nsn = models.ForeignKey(Student_INFO, on_delete=models.CASCADE) event1 = models.CharField(max_length=15, blank=False, default … -
Django admin precompile a field with current logged in user in add form
In my django app i have a model like thisone: class temp_case(models.Model): id = models.AutoField(primary_key=True) main_id = models.ForeignKey(temp_main, related_name="tm_tc", on_delete=models.CASCADE, verbose_name="Main Template") descr = models.CharField(max_length=200, verbose_name="Case description") dt = models.DateTimeField(auto_now=True, verbose_name="Created") owner = models.ForeignKey('auth.User', related_name='tcase_owner', on_delete=models.CASCADE, verbose_name="API Owner") well, when i go in my admin interface ad add a row, i would that field owner (models.ForeignKey('auth.User', related_name='tcase_owner', on_delete=models.CASCADE, verbose_name="API Owner") would automatically default populated with the current logged in user instead select it manually every time. I have to manage my admin.py file? or directly into model? so many thanks in advance -
Django: Model instance, whenever a datetime object is passed it is stored as tuple. Not happens always
I am experiencing a strange behaviour in my views.py file: in my user model i have date_something = models.DateTimeField(blank=True, null=True) The below is the code related in views.py match = User.objects.get(email='test@test.com') match.date_something = datetime.datetime.now(tz=pytz.timezone("UTC")) or timezone.now() # just want to check whats is stored from above line check = match.date_something locals()['check'] output: in the runserver console (datetime.datetime(2019, 10, 10, 8, 20, 10, 787399, tzinfo=<UTC>),) So here we see that the check is a tuple. Because of this when i am trying to save the model match.save() it says TypeError: expected string or bytes-like object I checked this code in dango Shell_plus and it gives the right results. In [2]: import datetime ...: import pytz ...: ...: match = User.objects.get(email='test@test.com') ...: match.date_something = datetime.datetime.now(tz=pytz.timezone("UTC")) ...: check = match.date_something ...: ...: locals()['check'] Out[2]: datetime.datetime(2019, 10, 10, 8, 25, 59, 533597, tzinfo=<UTC>) -
Django 2.2 : Integrity Error: Foreign Key Constraint Failed
While submitting a Complaint Form, I am trying to set the value of the grievant to the user logged in, but I am getting a Foreign key Constraint error. I am setting the initial value of grievant using form.inital. Please help. models.py class User(AbstractUser): is_grievant = models.BooleanField(default=False) is_department = models.BooleanField(default=False) class Grievant(models.Model): student = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) Registeration = models.IntegerField(default=0000) Room = models.CharField(max_length=50) Hostel = models.CharField(max_length=100) def __str__(self): return self.student.username class Complaint(models.Model): grievant = models.ForeignKey('grievance_app.Grievant',on_delete=models.CASCADE,related_name='complaintee',primary_key=True) department = models.ForeignKey('grievance_app.Department',on_delete=models.CASCADE) text = models.TextField() heading = models.CharField(max_length=200,blank=False,null=False,default='Problem') media = models.ImageField(upload_to='media/',blank=True) created_date = models.DateTimeField(default=timezone.now()) status_choices = [('D','Done'),('P','Pending'),('N','Not Accepted')] status = models.CharField(choices=status_choices,max_length=1,default='N') class Meta(): verbose_name_plural = 'Complaints' def change_status(self,choice): self.status = choice self.save() def __str__(self): return self.heading def get_absolute_url(self): return reverse("complaint_detail",kwargs={'pk':self.pk}) forms.py class ComplaintForm(forms.ModelForm): class Meta(): model = Complaint fields = ('department','heading','text','media',) views.py @method_decorator([login_required, grievant_required], name='dispatch') class CreateComplaintView(CreateView): login_url = '/login/' redirect_field_name = 'complaint_detail.html' template_name = 'create_complaint.html' form_class = ComplaintForm model = Complaint def set_grievant(self): ComplaintForm(initial={'grievant':self.request.user.is_active.username}) form.save() -
Questions about the use of 2D arrays in django templates
I want to draw a histogram (dynamic data generation) with echarts. I pass two-dimensional array data from view.py to the template, but I found that the array generated by django's templating language is a bit different from the "array" in html. view.py def get(self, request, param1): ... express = PerRnaExpression.objects.get(transcript_id="MSTRG.12393.2") x_indica_tissues = [["V2"], ["V4"]] return render(request, "Transcript_Content.html", {"express": express, "x_indica_tissues": x_indica_tissues, }) PS:express is two-dimensional array, such as [[15.7667285, 9.452281, 12.95694325, 14.987118, 12.264012], [13.0935945, 10.0311545, 12.2275855, 19.301165, 18.359003]] Transcript_Content.html <script type="text/javascript"> var myChart = echarts.init(document.getElementById('chart-express')); var option = { title: { text: "indica tissues" }, tooltip: {}, dataset: { source: [ ['product', 'glume', 'leaf', 'panicle', 'root', 'stem'], {{ x_indica_tissues.0|add:express.indica_tissues.0 }}, {{ x_indica_tissues.1|add:express.indica_tissues.1 }} ], }, xAxis: {type: 'category'}, yAxis: {}, series: [ { type: 'bar', }, { type: 'bar', }, ] }; myChart.setOption(option); </script> The value of {{ x_indica_tissues.0|add:express.indica_tissues.0 }} is ['V2', 15.7667285, 9.452281, 12.95694325, 14.987118, 12.264012]. The result of the above is that I can't see any graphics. If I replace the expression with the value of the expression, the histogram can display normally. Can't I use a two-dimensional array, do I have to pass the data to the template after all the operations are completed in view.py?Can I … -
Python django annotate count always 1
I have a problem with Django, i run this django request, but the annotation seems to be incorrect. def find_team_from_match_request(match_request: MatchRequest) -> Optional[Team]: """Find a team from a MatchRequest""" sport: Sport = match_request.criteria.sport rank_group: int = match_request.group.get_rank(sport) max_users: int = sport.playerPerTeam - match_request.group.count_users() interval: int = match_request.get_rank_interval() team: Team = Team.objects.annotate( num_users=Count('groups__users'), num_groups=Count('groups'), rank=Round('groups__users__sportsStats__rank'), rank_sum=Sum('groups__users__sportsStats__rank'), rank_distance=Func(Abs('rank') - rank_group, function='ABS') ).filter( match_id__isnull=True, sport=sport, num_users__lte=max_users, rank__lte=(rank_group + interval), rank__gt=(rank_group - interval), rank_distance__lte=interval ).order_by( 'rank_distance', 'rank' ).first() if team is not None: print('team from match request', team) print('max_users', max_users) print('num_users', team.num_users) print('num_groups', team.num_groups) print('rank', team.rank) print('rank_sum', team.rank_sum) print('rank_distance', team.rank_distance) print('num users all', team.count_users()) return team For an example, running this function I have these outpout max_users 4 num_users 1 num_groups 1 rank 1360 rank_sum 1360 rank_distance 240 num users all 3 team from match request Team object (1) So, when i use the function to count the users in a team (count_users) i get num_users == 3, but the count found by django is 1, i don't understand why. And here is my models: class Team(models.Model): """Team model""" sport = models.ForeignKey(Sport, on_delete=models.DO_NOTHING, related_name='teams') groups = models.ManyToManyField(Group, related_name='teams') match = models.ForeignKey(Match, on_delete=models.DO_NOTHING, related_name='teams', null=True, blank=True) def count_users(self) -> int: """Count the associated users of … -
'NoneType' object is not iterable after explicit check
I get this error even if i explicitly check if it is not none. def to_representation(self, instance): representation = super(UserSerializer, self).to_representation(instance) representation['companies'] = [] #return representation if instance.companies.all() is not None: for entry in instance.companies.all(): company = UserCompanySerializer(entry).data representation['companies'].append(company) return representation -
Django save QuerySet into session
I'm trying to save filtered QuerySet data into request.session. I try do this with pickle but i need to serialize QuerySet before putting data into request.session Is there a easy way to save QuerySet object inside session? My attempts: with pickle: pickle without pickle [output is string]: # save data product_data = Product.objects.filter(Q(title__icontains=search_sequence)) product_data = serializers.serialize('json',product_data) request.session['product_data'] = product_data # recieve data if 'product_data' in request.session: product_data = request.session['product_data'] Thanks for all suggestions. -
A way to test methods with multiple database connections
How can I test a method (e.g. a serializer) which accesses two databases in Django? One is a default postgresql database and the other is a database with personal information. From the existent answers (for example Test isolation broken with multiple databases in Django. How to fix it?) I see that I can use TestCase, but the problem is that TestCase doesn't create separate databases in each test and uses existent ones that doesn't fit my needs. So actually I want to use APITestCase, but according to the docs it has no support for multiple database connections. Could you please help me to come up with any workaround? -
How to run a group of celery tasks? Apps aren't loaded yet
For example, I have a two tasks: a and b. I need to run them in parallel. I create a group of tasks and try run it. But I get error proj/app/tasks.py @app.tasks def a(): pass @app.tasks def b(): pass django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Application app is registered in INSTALLED_APPS and all migration complited proj/proj/__init__.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) proj/proj/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) from celery import group from app.tasks import a, b run_group = group(a.s(), b.s()) run_group() Traceback File "/home/m0nte-cr1st0/test_projects/oddsportal/oddsportal/__init__.py", line 5, in <module> from .celery import app as celery_app File "/home/m0nte-cr1st0/test_projects/oddsportal/oddsportal/celery.py", line 26, in <module> from app.tasks import a, b File "/home/m0nte-cr1st0/test_projects/oddsportal/app/tasks.py", line 14, in <module> from .models import Link, Prediction, PredictionBK File "/home/m0nte-cr1st0/test_projects/oddsportal/app/models.py", line 2, in <module> from django.contrib.auth.models import AbstractUser -
I changed codes in the running django project on the aws but changes are not reflecting
i have running django project on aws server with website hosted on same server i changed some coding and uploaded it to the server using sftp server but changes are not reflecting on the website and uploaded file is not working -
How to safely send large files using Django REST API?
I'm trying to automate a file transfer service where I use a simple bash script to upload video files from a remote client to a local server using a Django REST API when clients put a video in their local folder. Problem is, these videos are large and sometimes their internet connection isn't stable. What would be the best way to ensure my files are safely getting sent over and possibly resend the files if an error occurs? I know there are many ways to check if original and transferred files are similar and if internet connection is problematic but are there better more robust practices out there? -
A custom decorator to be called before every view using middleware
I have a custom decorator in a file and I need that every api call this decorator. I don't want to write @decorator_name before every view. I think this can be done using middleware but I am not sure how to do it/ I have tried middleware like this class DefaultAccountMiddleware(MiddlewareMixin): def process_view(self, request, view_func, view_args, view_kwargs): return update_latest_account(view_func)(self, request, *view_args, **view_kwargs) This is the decorator: def update_latest_account(f): @wraps(f) def decorator(self, request, *args, **kwargs): user_id = request.user.id print('hi') user = User.objects.filter(id = user_id).first() if user is not None: account_id = request.META.get("HTTP_ACCOUNT_ID", None) user.latest_account_id = account_id user.save() return f(self, request, *args, **kwargs) return decorator -
Mezzanine project structure - virtual env in project folder?
So I'm attempting to deploy my mezzanine site, but I have run into some issues with settings not being installed properly on the digitalocean server. After checking some videos, like this one: https://www.youtube.com/watch?v=RIOUwi-1DCg I notice that he and others have their virtual env inside the project folder, next to the mezzanine project. Is this the correct way to structure the project? In my case, the virtual env is in a seperate Env folder with my other virtualenvs under my main directory on Windows 7. If someone could clarify what the structure should look like, and perhaps why, I would be grateful. -
How to configure wsgi for gunicorn?
Django version: 2.2.4 Python version: 3.6 When I try to run "gunicorn --bind 127.0.0.1:9000 config.wsgi:appname", I get following error: [2019-10-10 12:00:12 +0530] [9398] [INFO] Starting gunicorn 19.9.0 [2019-10-10 12:00:12 +0530] [9398] [INFO] Listening at: http://127.0.0.1:9000 (9398) [2019-10-10 12:00:12 +0530] [9398] [INFO] Using worker: sync [2019-10-10 12:00:12 +0530] [9401] [INFO] Booting worker with pid: 9401 Failed to find application object 'appname' in 'config.wsgi' [2019-10-10 12:00:12 +0530] [9401] [INFO] Worker exiting (pid: 9401) [2019-10-10 12:00:12 +0530] [9398] [INFO] Shutting down: Master [2019-10-10 12:00:12 +0530] [9398] [INFO] Reason: App failed to load. My WSGI file looks like this: import os import sys from django.core.wsgi import get_wsgi_application app_path = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir) ) sys.path.append(os.path.join(app_path, "appname")) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") application = get_wsgi_application() I set up this Django project using cookiecutter Django. As I am new to this kindly let me know of any newbie mistakes. -
Gunicorn not forwarding reason phrase from Django Response
I am hosting my Django app with Gunicorn. What happen is as follow A sample response from Django would be as follow @require_http_methods(['POST']) def register(request): body = json.loads(request.body.decode('utf-8')) try: email = body['email'] except: return HttpResponse(status=400, reason="Email must be provided.") During the development, the Django app are run with command python manage.py runserver and have no issue at all with it. It always response with 400 Email must be provided However, in the production environment, it is hosted as follow Procfile web: gunicorn app.wsgi release: python manage.py migrate wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') application = get_wsgi_application() Yet, when making a request, the response left as below. 400 What am I missing out to not letting the reason being forwarded properly? -
Django 'FloatField' is not callable
I keep getting these annoying highlights in my model field declarations When I hover mouse over it, it say 'FloatField' is no callable. This is happening for all field types except for CharField. The project runs fine and I'm able to migrate the model to DB but these highlights are annoying. Hoe can I get rid of them? Please advise. from django.db import models class ProjectModel(models.Model): name = models.CharField(max_length=50) project_id = models.IntegerField(blank=True) discipline_id = models.IntegerField(blank=True) demo_field = models.FloatField(verbose_name='flow(kg/s)', null=True, blank=True) def __str__(self): return str(self.id) -
"Album.singer" must be a "Singer" instance
Tracebck Please refer this link for trace back 2.Even I changed the lable name in forms.py it is taking default name I tried This code to make it fix but not solved.name = forms.CharField(label='Singer') forms.py class AlbumForm(forms.ModelForm): title = forms.CharField(max_length=50,label='Album title') class Meta: model=Album exclude = ['singer'] class SingerForm(forms.ModelForm): class Meta: model = Singer fields = ['name'] label = {'name':'Singer'} views.py class AlbumSinger(View): def get(self,request,pk=None): singer_form = SingerForm(instance=Singer()) album_form = AlbumForm(instance=Album()) context = { 'singer_form':singer_form, 'album_form':album_form } return render(request, 'album/multi_form.html', context) def post(self,request,pk=None): context = {} singer_form = SingerForm(request.POST,instance=Singer()) album_form = AlbumForm(request.POST,instance=Album()) if singer_form.is_valid and album_form.is_valid: singer_form.save() new_album = album_form.save(commit=False) new_album.singer = singer_form new_album.save() return HttpResponseRedirect('/album/') context = { 'singer_form' : singer_form, 'album_form' : album_form } return render(request, 'album/multi_form.html', context)