Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django "Deadlock found" with transaction.atomic
I have a function that updates a model or creates a new entry if it doesnt already exists: try: obj=model.objects.get(id=id) setattr(obj, 'completed', True) obj.save() except: model.objects.create(id=x, user=y, completed=True) In a specific case this function is called twice so fast that it was creating two entries on the database, because of that, I included a unique constraint to make sure it wont ever happen. But then I started getting this error: Duplicate entry '1-13' for key 'x_y_z_uniq' So I tried using lock like: with transaction.atomic(): try: obj=model.objects.select_for_update().get(id=id) setattr(obj, 'completed', True) obj.save() except: model.objects.create(id=x, user=y, completed=True) But now is raising this error: (Deadlock found when trying to get lock; try restarting transaction) I wanted a way that the first call of the function would create a new entry and the second one would update that entry, but the second call simply fails due to the deadlock, how can I make it so the second call will wait for the first one to finish? -
How to apply pagination to a filtered queryset in Django
I'm currently stuck with applying pagination to my Django view codes. Basically, paginate_by seems automatically to work with quryset attirubte in CBV. But, in my case, I'm not just using queryset attribute. I'm using filtered queryset on my own. How can I apply pagination to my codes? class SearchListView(ListView): model = Store template_name = 'boutique/search.html' paginate_by = 5 def get(self, request, *args, **kwargs): search_text = request.GET.get('search_text') sorter = request.GET.get('sorter') if not sorter: sorter = 'popularity' if search_text: search_stores = Store.objects.filter(Q(businessName__icontains=search_text) | Q(mKey__icontains=search_text)) if sorter == 'businessName': search_stores = search_stores.order_by(sorter) else: search_stores = search_stores.order_by(sorter).reverse() else: search_stores = '' for store in search_stores: store.mKey = store.mKey.split(' ') return render(request, self.template_name, { 'search_stores': search_stores, 'search_text': search_text, 'sorter': sorter, }) -
How can I upload files into django database
I want to upload files to the database that Django use, I know that I can do it through forms, but I want to read the files in my files system get the path of the docx or pdf and uploaded it into the database, how can I do that Here is the code that i use to get the path of the files in my filedsystem for dir_, _, files in os.walk(superpath): for fileName in files: print fileName if fileName.find('~$')==-1: relDir = os.path.relpath(dir_, superpath) if relDir=='.': relFile =os.path.join(superpath, fileName) else: relFile = os.path.join(superpath,os.path.join(relDir, fileName)) path.append(relFile) -
Django objects.filter in template
I have django project with three below models: models.py from django.db import models from django.contrib.auth.models import User class Album(models.Model): owner = models.ForeignKey(User) title = models.CharField(max_length=127) artist = models.CharField(max_length=63) release_date = models.DateField() logo = models.ImageField(blank=True, upload_to='album_logos', default='album_logos/no-image.jpeg') t_added = models.DateTimeField(auto_now_add=True) slug = models.SlugField(null=True, blank=True, max_length=63) class Meta: ordering = ['-release_date'] def __str__(self): return self.title class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) name = models.CharField(max_length=255) # is_favorite = models.BooleanField(default=False) favorites = models.IntegerField(default=0) song_file = models.FileField(blank=True, null=True, upload_to='song_files', default='song_files/mektub.mp3') class Meta: ordering = ['name'] def __str__(self): return self.name class Favorite(models.Model): user = models.ForeignKey(User) song = models.ForeignKey(Song) created = models.DateTimeField(auto_now_add=True) As you can see from these models many users can favorite many songs. In template, I want to add class to songs which are favorited by authenticated user: template <span {% if authenticated user favorited this song %}class="favorited" {% endif %}></span> My problem is, I don't know how to write "if authenticated user favorited this song" in template. In terminal, I can get this information by this code: user_favorited_this = song.favorite_set.filter(user=sample_user) and True or False I couldn't do the same thing in template, since it doesn't support passing argument to filter method. How can I overcome this problem? -
Simulate delay in django's view by sleep
In my django app, users are able to define some delays (in seconds) on particular actions - its being used to simulate network delays. It is possible that I will end up with hundreds of such events. What I've implemented so far, in my django's view, I simply do: class NetworkDelayView(View): def dispatch(self, request, *args, **kwargs): obj = Event.objects.get(short_uuid=kwargs.get('uuid')) if obj.enable_delay: sleep(obj.delay) return super().dispatch(request, *args, **kwargs) I am not sure if its a best way to do this from a few reasons: threads - as far as I understand, it will block all requests I run my django/python apps on production on shared hosting, using passenger Any suggestions if its a proper way of doing this? Maybe there is a better way. -
Replace values in dictionary with values from constants
I'm working with Django and I have a class to define some constants (I use this in my models) class ArticleStatus: OPEN = 'open' CLOSED = 'closed' BLOCKED = 'blocked' CHOICES = ( (OPEN, 'Open'), (CLOSED, 'Closed'), (BLOCKED, 'Blocked') ) In my view I have a queryset which gives me this result: context['total'] = [ {'status': 'open', 'total': 102}, {'status': 'closed', 'total': 150}, {'status': 'blocked', 'total': 24} ] My goal is to convert the status values to the more readable values from the constants. I did this with the following code for i in range(0, len(context['total'])): status = context['total'][i]['status'] for status_const in ArticleStatus.CHOICES: if status == status_const[0]: context['total'][i]['status'] = status_const[1] And the converted result is: context['total'] = [ {'status': 'Open', 'total': 102}, {'status': 'Closed', 'total': 150}, {'status': 'Blocked', 'total': 24} ] Working example This doesn't look so nice and I wanted to ask if anyone has a better solution? -
django - prefetch only the newest record?
I am trying to prefetch only the latest record against the parent record. my models are as such class LinkTargets(models.Model): device_circuit_subnet = models.ForeignKey(DeviceCircuitSubnets, verbose_name="Device", on_delete=models.PROTECT) interface_index = models.CharField(max_length=100, verbose_name='Interface index (SNMP)', blank=True, null=True) get_bgp = models.BooleanField(default=False, verbose_name="get BGP Data?") dashboard = models.BooleanField(default=False, verbose_name="Display on monitoring dashboard?") class LinkData(models.Model): link_target = models.ForeignKey(LinkTargets, verbose_name="Link Target", on_delete=models.PROTECT) interface_description = models.CharField(max_length=200, verbose_name='Interface Description', blank=True, null=True) ... The below query fails with the error AttributeError: 'LinkData' object has no attribute '_iterable_class' Query: link_data = LinkTargets.objects.filter(dashboard=True) \ .prefetch_related( Prefetch( 'linkdata_set', queryset=LinkData.objects.all().order_by('-id')[0] ) ) I thought about getting LinkData instead and doing a select related but ive no idea how to get only 1 record for each link_target_id link_data = LinkData.objects.filter(link_target__dashboard=True) \ .select_related('link_target')..? -
How do I override id_valid() method of Django admin-created form?
I'm working on a Django app for a research project, and came across an issue where I needed to change the way a TabularInline was rendered, which fixed slow loading speeds but removed functionality from the Django Admin form. I believe that I can fix the loss in functionality if I can override how the form is validated. However this is a form that I don't believe to be written, and was created by Django. It's called SourceMaterial_peopleForm, which corresponds to and intermediate table in the database. I was wondering if it was possible to override the methods of this automatically created form, and if so how would I go about doing that? Thanks. -
How to get latest records
I have a table looks like this: +--------+-------------+----------+---------+ | PK(id) | FK(user_id) | ctime | comment | +--------+-------------+----------+---------+ | 1 | 1 | 20170101 | "Haha" | +--------+-------------+----------+---------+ | 2 | 2 | 20170102 | "Nope" | +--------+-------------+----------+---------+ | 3 | 2 | 20170104 | "Geez" | +--------+-------------+----------+---------+ | 4 | 1 | 20170110 | "Gone" | +--------+-------------+----------+---------+ I expect to retrieve latest records per FK(user_id) as followed: +--------+-------------+----------+---------+ | PK(id) | FK(user_id) | ctime | comment | +--------+-------------+----------+---------+ | 3 | 2 | 20170104 | "Geez" | +--------+-------------+----------+---------+ | 4 | 1 | 20170110 | "Gone" | +--------+-------------+----------+---------+ So I tried SELECT DISTINCT T.* FROM my_table AS T and SELECT DISTINCT T.user_id FROM my_table AS T; however, they won't work! I tried GROUP BY statement, as is followed, SELECT T.* FROM my_table AS T GROUP BY `user_id` DESC It does work perfectly as I expect. So I started to figure out how to translate SQL into Django! First, I tried to use RawSQL: from django.db.models.expressions import RawSQL def _select_latest_rows(model_class, target_column_name, query_set=None): query_set = query_set or model_class.objects table_name = model_class._meta.db_table raw_sql = ''' SELECT * FROM %s GROUP BY %s ''' return query_set.annotate(val=RawSQL(raw_sql, (table_name, target_column_name,))) Django pops the following error … -
Converting codes from FBV to CBV in Django Views
I'm currently converting my function-based views to class-based views. On my template, I get a value through the input tag. <input name="search_text" type="text"> After getting the value, I process with the value like the following in FBV. def search(request): search_text = request.GET.get('search_text') search_stores = Store.objects.filter(Q(businessName__icontains=search_text) | Q(mKey__icontains=search_text)) But now, I wanna convert the codes to CBV. How can I do that? -
Django queryset get Avg() of 2 fields
I have the following model: class Listing(models.Model): list_price = models.IntegerField() sold_price = models.IntegerField() I know that to get the average of say, the sold_price, I would do Listing.objects.aggregate(Avg('sold_price')). What I want to find is the average sale-to-list price. Basically the average of the sold_price / list_price. Something like: Listing.objects.aggregate(Avg('sold_price' / 'list_price')) Obviously the above statement doesn't work. Is there some way to do this with Django ORM? -
Update object with foreign key (id vs nested object)
I use Django 2.0 & DRF for Backend and API, and Angular 5 for Frontend. My backend model: class Task(models.Model): author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) completed = models.BooleanField(default=False) its serializers, one for retrieving so that I get the whole category object, and one for posting data using the ID: class TaskRetrieveSerializer(ModelSerializer): category = CategorySerializer(read_only=True) class Meta: model = Task fields = '__all__' class TaskPostSerializer(ModelSerializer): class Meta: model = Task fields = '__all__' In the frontend, this function is triggered when the update form is submited and works as desired: taskSubmit(event:any, taskDir:NgForm, taskForm:FormGroup) { event.preventDefault() if (taskDir.submitted) { this.taskItem.content = taskForm.value['content'] this.taskItem.category = taskForm.value['category'] this.taskItem.completed = taskForm.value['completed'] this.taskUpdateSubscription = this.tasksService.updateTask(this.taskItem) .subscribe( data => { console.log(data) }, errorResponse => { this.handleError(errorResponse)} ) } } In this function, taskForm.value['category'] is of type number, but why is this.taskItem.category also a number? I would expect an error here as I assign number to object Category. However, when I use console.log(typeof this.taskItem.category, typeof taskForm.value['category']) inside taskSubmit, gives number, number but outside it, this.taskItem.category is an object (!). -
Django: reset_password custom template_name not loading
so I'm trying to customize the templates for resetting passwords. I've made the html files but in my urls.py I do the following: url(r'^password_reset/$', auth_views.password_reset, {'template_name': 'password_reset.html'}, name='password-reset'), url(r'^password_reset/done/$', auth_views.password_reset_done, {'template_name': 'password_reset_verify.html'}), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.password_reset_confirm), url(r'^reset/done/$', auth_views.password_reset_complete), This code is in the root urls of the website and the templates I made are in the root templates directory as follows: website directory structure Please let me know what the issues may be with regards to locating each "template_name" properly. Thanks! -
Django: Uploading Multiple Files - What's going on in the documentation here?
I'd like one of my forms to handle multiple file uploads. I will override the save() method to save an object for each file. I'd like to do this using what comes with Django 1.11, and have turned to the documentation: If you want to upload multiple files using one form field, set the multiple HTML attribute of field’s widget: forms.py from django import forms class FileFieldForm(forms.Form): file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) Then override the post method of your FormView subclass to handle multiple file uploads: from django.views.generic.edit import FormView from .forms import FileFieldForm class FileFieldView(FormView): form_class = FileFieldForm template_name = 'upload.html' # Replace with your template. success_url = '...' # Replace with your URL or reverse(). def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('file_field') if form.is_valid(): for f in files: ... # Do something with each file. return self.form_valid(form) else: return self.form_invalid(form) As far as I know, when we use if form.is_valid(), the form must perform validation. For example, it will validate that every file uploaded was a .wav file. My question is: How can the form perform validation on multiple files like this if we need to call is_valid() in order to deal … -
NameError: name 'trix' is not defined
I have uninstalled django-trix from my django project with command pip uninstall django-trix and deleted from settings also. Now it Shows: I have found the file in migration: migrate makemigration runserver etc commands doesn't work Now what should I do? please help me guyz ask me if you need more details -
SMTPRecipientsRefused in Django send email
I'm trying to send email thru my Django app. I have this in my local_settings.py: EMAIL_HOST = 'smtp.privateemail.com' EMAIL_HOST_USER = 'support@mydomain.com' EMAIL_HOST_PASSWORD = 'myPassword' EMAIL_PORT = 587 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True I have this in my views.py: send_mail( subject="Subject here", message="Hello.", from_email=settings.EMAIL_HOST_USER, recipient_list=["someone@gmail.com], fail_silently=False, ) But when the send_mail() executes, I get this error: {u'someone@gmail.com': (504, '5.5.2 <webmaster@localhost>: Sender address rejected: need fully-qualified address')} Why? And how do I make my app send emails properly? -
Django (?P<pk>\d+) vs <int:pk>
I have this post_list.html file: (Ignore the second 'blog:post_detail' url) {% for post in post_list %} <h1><a href="{% url 'blog:post_detail' post.pk %}">{{ post.title }}</a></h1> <div class="date"> <p>Published on: {{post.published|date:"D M Y"}}</p> </div> <a href="{url 'blog:post_detail' post.pk}">Comments: {{post.approve_comments.count}}</a> {% endfor %} And in the urls.py I am trying to use re_path in the following way: re_path(r'^posts/<int:pk>/$', views.PostDetailView.as_view(), name='post_detail'), When I run the server I am getting NoReverseMatch at / error:Reverse for 'post_detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['posts/<int:pk>/$'] However if I replace re_path with url and <int:pk> with (?P<pk>\d+) it works perfectly: url(r'^posts/(?P<pk>\d+)/$', views.PostDetailView.as_view(), name='post_detail'), -
DateField Format in Bound Form
I'm collecting user input in a DateField in a Django form. I'm running into an issue when I display the datefield in an UpdateView for editing. Suppose a user originally inputs the date "04/13/2018". Then, in the edit form (where the form is bound), that date displays as "20/18/0413". So, it looks like I'm matching the same date formatting ("mm/dd/yyyy") but it's jumbling the numbers. The date renders correctly in the template, so it's not an issue with saving the date to the database. Docs on date formatting are here, but I wasn't sure how to fix this issue. I'm using default date formatting settings. -
How to add SQL function/view to Database in a django Project
If you have any project in Django that require load SQL functions or views, this code help you 1.- Create a command like Django create command 2.- Add this code into the file from django.conf import settings from django.db import connection from django.core.management.base import BaseCommand import os class Command(BaseCommand): help = 'Add SQL functions or view in db' def handle(self, *args, **options): """Add SQL functions or view in db""" path = os.path.join(settings.BASE_DIR, 'SQL') files = [x for x in os.listdir(path) if x.lower().endswith('.sql')] cursor = connection.cursor() for f in files: filepath = os.path.join(path, f) with open(filepath, 'r') as fh: sql_file = fh.read() try: cursor.execute(sql_file) except Exception: pass fh.close() self.stdout.write(self.style.SUCCESS('Done')) Run this code with: python manage.py command_name -
Django, add field from a join in my QuerySet
I have a model Exec with a FK User (the django's one) I have a model Profil with a FK User (the django's one) I have a QuerySet of Exec and I want to get a field from Profil in it by "joining" with Profil by the FK. How can i do that? -
Docker was working the first time but now throws no files or directory error
First time I ran the command docker-compose run web python /code/manage.py migrate --noinput on my django app it ran for a while but all successful Creating network "locallibrary_default" with the default driver Creating volume "locallibrary_postgres_data" with default driver Pulling db (postgres:10.1)... 10.1: Pulling from library/postgres Digest: sha256:3f4441460029e12905a5d447a3549ae2ac13323d045391b0cb0cf8b48ea17463 Status: Downloaded newer image for postgres:10.1 Creating locallibrary_db_1 ... done Building web Step 1/7 : FROM python:3.6 ---> d69bc9d9b016 Step 2/7 : ENV PYTHONUNBUFFERED 1 ---> Using cache ---> 040647619125 Step 3/7 : COPY . /code/ ---> 73108059d4d9 Step 4/7 : WORKDIR /code/ Removing intermediate container 2129cd008797 ---> 901087760135 Step 5/7 : RUN pip install pipenv ---> Running in 7b3a5a047847 Collecting pipenv Downloading https://files.pythonhosted.org/packages/2c/01/37a5867a47d52856b077d0faa561b791cb6e6e3e9410837b6d62f569c1e6/pipenv-11.10.1-py3-none-any.whl (6.3MB) Collecting virtualenv-clone>=0.2.5 (from pipenv) Downloading https://files.pythonhosted.org/packages/6d/c2/dccb5ccf599e0c5d1eea6acbd058af7a71384f9740179db67a9182a24798/virtualenv_clone-0.3.0-py2.py3-none-any.whl Collecting certifi (from pipenv) Downloading https://files.pythonhosted.org/packages/7c/e6/92ad559b7192d846975fc916b65f667c7b8c3a32bea7372340bfe9a15fa5/certifi-2018.4.16-py2.py3-none-any.whl (150kB) Collecting virtualenv (from pipenv) Downloading https://files.pythonhosted.org/packages/ed/ea/e20b5cbebf45d3096e8138ab74eda139595d827677f38e9dd543e6015bdf/virtualenv-15.2.0-py2.py3-none-any.whl (2.6MB) Requirement already satisfied: setuptools>=36.2.1 in /usr/local/lib/python3.6/site-packages (from pipenv) (39.1.0) Requirement already satisfied: pip>=9.0.1 in /usr/local/lib/python3.6/site-packages (from pipenv) (10.0.1) Installing collected packages: virtualenv-clone, certifi, virtualenv, pipenv Successfully installed certifi-2018.4.16 pipenv-11.10.1 virtualenv-15.2.0 virtualenv-clone-0.3.0 Removing intermediate container 7b3a5a047847 ---> 35735d34308d Step 6/7 : RUN pipenv install --system ---> Running in 93d2ae915ff4 Installing dependencies from Pipfile.lock (ca72e7)▒ Removing intermediate container 93d2ae915ff4 ---> 7a848e302b83 Step 7/7 : EXPOSE 8000 ---> Running in 3369c5a84e1f … -
How to auto-refresh the templates(or better views) whenever data is updated in models?
I am working on a project which sends data to django server using POST request (not through web browser) and updates data on models. My templates just runs through all the data in models and print it in a table. The problem here is that I've to manually refresh my page to get the updated data. I'm very new to django, so is there a way to achieve this? (I'll post the codes if needed) -
Can I manually create a registration token for my iPhone to use for Firebase Cloud Messaging?
I am trying to play around with django-push-notifications to hopefully integrate it with our system soon. Part of our team is working on the app itself within Firebase, but as a Python backend developer, I would like to test out sending notifications to my personal iPhone. I have the proper APNS dev certs, and I have my device ID, but I don't know of a way I can manually create a registration token to allow me to send messages. The way that I understand it from reading the Firebase docs, it is created once a user engages with the app, and the Swift code in the app handles creating/retrieving and storing the user's registration token. Is that the only way a token can be generated? Not sure what the best way of trying to integrate django-push-notifications if that is the case. -
Implementing wild card searches on a django model
I have a model called Host where I store all the information about all my servers. In the model I have a field hostname. I would like for the user to be able to specify wildcard searches like: *one where they'd get all the hosts with hostnames ending in one or one* where they'd get all the hosts with hostnames starting with one and one*two and *one*two and *one*two* and *one*two*three and one*two*three and so forth. I have tried iterating over the results of hostname.split('*') but I end up with confusing if/elif continue mess. Does anyone know a more elegant way to handle wildcards? -
Python Script Return Differernt value under Django
Current I'm working on a python project that analysis text and generate a summary of the text, The over all process is 1. Download url with lynx -dump, and the file store in temp directory with ID. e.g. temp1/text temp2/text 2. python Script to analysis and return paragraph However, when I use same URL, the paragraph return by Django is differnt from the result that I directly executed on console. and the result from djiango appears as one of the previous URL result. I've already turn Debug mode = false and disable all caches. Here is the ouput of question [what are new macbook advantages] Django (I've search a previous question "The best University") Django Console Test in Console