Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to compare fields of same instance of related model in queryset
I have a model of Product. A product can be rented and each rental is an object made of a date_start and date_end class Product(model.Model): field1= model.Charfield(...) field2= model.Charfield(...) class Rental(model.Mode): product = model.ForeignKey(Product, related_query_name='rental') date_start = model.DateField() date_end = model.DateField() I am doing a form that returns all the Products available based on a period given by the user (user_date_start and user_date_end).. There is an equation that works for that, it tells you if there is an overlap in your dates: source (StartA <= EndB) and (EndA >= StartB) I start my queryset as follow: qs= Product.objects.exclude(rental__date_start__lt = user_date_end, rental__date_end__gt = user_date_start) I works well when I have only one reservation of the product. BUT when I have multiple reservations already done, it fails due to the fact that it combines all "date_start" together and all "date_end" together. Let's say for my product I have the dates 14-16/04/2020 and 20-25/04 in the database, the queryset will exclude the dates in-between, (eg. 17-19/04). Because (17 < 25) and (19 > 14). I would like to tell my queryset to compare date_start and date_end of the same Rental object, and not all 'date_start' and all 'date_end' without their respective bindings but … -
Download Video in Users Device Python Django
I'm making a Django app where users can paste link and download videos but there's a problem. I've tried to run it on my local server and then on WAN but both times results are same. Video is downloaded in my directory rather than users. I'm using youtube-dl for this. I'll be really thankful if someone help me out with this. I'll add the views.py file so you get a better understanding. Thanks! from django.shortcuts import render from django.http import HttpResponse,HttpResponseRedirect from download.models import urlinput from download.forms import Input import youtube_dl import subprocess import os # Create your views here. def index(request): form=Input() if request.method=='POST': form=Input(request.POST) if form.is_valid(): link=form['url'].value() #downloadaudio(link) #video1080(link) #homedir = os.path.expanduser("~") #dirs=homedir +'/Downloads' video720(link) #download4k(link) form.save(commit=True) return render(request,'index.html',{'form':form}) else: print("Invalid Input") return render(request,'index.html',{'form':form}) def downloadaudio(link): options={'format':'bestaudio/best','extractaudio':True,'audioformat':'mp3'} with youtube_dl.YoutubeDL(options) as ydl: ydl.download([link]) def video1080(link): options={'format':'bestvideo+bestaudio/best'} with youtube_dl.YoutubeDL(options) as ydl: ydl.download([link]) def video720(link): options={'format':'best'} with youtube_dl.YoutubeDL(options) as ydl: ydl.download([link]) def download4k(link): subprocess.call("youtube-dl -f 299+140 {}".format(link)) -
Decoding User Data to String in Django
I have a model in Django titled Account class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) I am trying to print out the email as a string in views.py. def fill_view(request): # ... authentication ... email = Account.objects.filter(email=user.email).first() # ... setting up forms .... can.drawString(10, 100, email) I get the following error: Exception Type: AttributeError at /fill/ Exception Value: 'Account' object has no attribute 'decode' How can I decode the email into a string in Django when transferring the data from models.py to views.py? -
Managing multiple PostgreSQL instances on Heroku (Django project)
I’m taking John Elder’s Udemy course titled: “How To Push Django Python Apps To Heroku for Web Hosting”. The title explains what I am trying to do. When I initially set everything up 2 weeks ago, it appears I created three PostgreSQL database instances. See here for a screenshot on imgur. My question: In that screenshot of my Heroku dashboard, what are the second and third configuration entries for? I’ve already got some non-critical data in production on my live demo site. I’d like to delete the two of the three duplicate PostreSQL instances that I am not using but I’m curious and would first like to establish which one is the active one and which two are not. What is a potential use case for even having multiple duplicate databases? Rolling back a database to a given state (like by using PostreSQL’s Continuous Archiving and Point-in-Time Recovery (PITR) feature) and importing/exporting instances are ways of backing up and restoring data which have been corrupted. But how are those features different or similar from configuring more than one db URL in the Heroku dashboard, as depicted in my imgur screenshot above? I’ve Googled around using search terms such as ‘config … -
Invalid syntax error in Django form translate
I try translate my forms.py (placeholder, choices, etc) but i take syntax error. my code is here; from django import forms from django.utils.translation import ugettext_lazy as _ class CreatePollForm(forms.Form): title = forms.CharField(max_length = 300, label="", widget=forms.Textarea(attrs={'rows':'1','cols':'20', 'placeholder': (_'Type your question here'),'class': 'createpoll_s'})) polls = forms.CharField(max_length = 160, required=False, label="", widget=forms.TextInput(attrs={ 'placeholder': (_'Enter poll option'), 'class': 'votes firstopt','id':'id_polls1','data-id':'1'})) ... if i use like this, i take syntax error. how can i translate "Type your question here" and "Enter poll option" ? -
django.setup() not finding my Django Project
I am trying to write a faker script to populate my Django 3.0.4 project with some dummy data, but am getting stuck at the very beginning of the script. If I run this: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyProject.settings') import django django.setup() I get this error: return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'MyProject' The script is in the same folder as my settings.py, urls.py, etc... and it's being executed within the venv for the django project. Why can't if find my project when django.setup() is executed? -
Problems with Google Api - Django
In my project I used GoogleOAuth2 to log in through Google account. It works fine for the first time. I mean, I chose two accounts and it works perfectly, but when I try to log in once again to these account I have an error: 'TypeError at /social-auth/complete/google-oauth2/ from_db_value() missing 1 required positional argument: 'context'' Django cannot process users who have already connected to the server in the past. Maybe someone know why it happens? In addition, when I want to delete these type os users in my django admin page I cannot do it, because I get the same error. -
Multiple file upload Django using multiple attribute in input field
I am trying to create a media post with multiple files upload. This is my code for views.py. @login_required() def CreateMediaPost(request): if request.method == 'POST': postForm = MediaPostForm(request.POST) files = request.FILES.getlist('media') print(files) if postForm.is_valid(): post_form = postForm.save(commit=False) post_form.postedBy = request.user post_form.save() for file in files: upload = FileUpload() upload.mediaPost = post_form upload.media = file upload.save() print(upload) messages.success(request, "Post submitted") return redirect("create-media-post") else: print(postForm.errors) else: postForm = MediaPostForm() upload = FileUploadForm() return render(request, 'forms/mediapost.html',{'postForm': postForm,'fileUpload':upload}) Models.py class MediaPost(models.Model): title = models.CharField(max_length=50) content = models.CharField(max_length=150) postedBy = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(CategoryPost, on_delete=models.CASCADE) type = models.ForeignKey(TypeMediaPost, on_delete=models.CASCADE) tags = TaggableManager() def get_filename(object, filename): postId = object.MediaPost.id return "postMedia/%s" % postId class FileUpload(models.Model): mediaPost = models.ForeignKey(MediaPost, on_delete=models.CASCADE) media = models.FileField(upload_to=get_filename, verbose_name='Media') getting attribute error for file upload model while submitting form Please help me to resolve this error or suggest a better way to implement multiple files upload. Other than modelformset_factory method. -
I need help importing fonts from Fontastic.Me
`I am trying to get my font from "Fontastic.me" working. I made a custom font but it isn't appearing. I really want to get this to work! I've been working for hours! @charset "UTF-8"; tbody{ color: red; font-weight: normal; font-style: normal; } @font-face { font-family: "cylexion"; src:url("../fonts/cylexion.eot"); src:url("../fonts/cylexion.eot?#iefix") format("embedded-opentype"), url("../fonts/cylexion.woff") format("woff"), url("../fonts/cylexion.ttf") format("truetype"), url("../fonts/cylexion.svg#cylexion") format("svg"); font-weight: normal; font-style: normal; } [data-icon]:before { font-family: "cylexion" !important; content: attr(data-icon); font-style: normal !important; font-weight: normal !important; font-variant: normal !important; text-transform: none !important; speak: none; line-height: 1; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } [class^="icon-"]:before, [class*=" icon-"]:before { font-family: "cylexion" !important; font-style: normal !important; font-weight: normal !important; font-variant: normal !important; text-transform: none !important; speak: none; line-height: 1; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .icon-cylexion-a:before { content: "\61"; } .icon-cylexion-ah:before { content: "\42"; } .icon-cylexion-ai:before { content: "\44"; } .icon-cylexion-aw:before { content: "\45"; } .icon-cylexion-ay:before { content: "\41"; } .icon-cylexion-b:before { content: "\62"; } .icon-cylexion-c:before { content: "\63"; } .icon-cylexion-d:before { content: "\64"; } .icon-cylexion-e:before { content: "\65"; } .icon-cylexion-ear:before { content: "\49"; } .icon-cylexion-f:before { content: "\66"; } .icon-cylexion-g:before { content: "\67"; } .icon-cylexion-h:before { content: "\68"; } .icon-cylexion-i:before { content: "\69"; } .icon-cylexion-j:before { content: "\6a"; } .icon-cylexion-k:before { content: "\6b"; } .icon-cylexion-l:before { content: "\6c"; … -
Django: write view based on multi-tenant static and media file structure
I am pretty confused about working with 'Django-tenants' in the regard of passing files to a function within a view. Here is my process: A tenant uploads a csv files that gets stored in his own media file (from django-tenant MULTITENANT_RELATIVE_MEDIA_ROOT). Then this file must pass through a python script that modifies the data and uploads it to this tenant's schema. the structure looks like that: media folder: tenant1: csv_file tenant2: csv_file view.py def etl(request): pd.read_csv(either tenant1 or tenant2 csv_file) # this is the part that is depending on the tenant [....] return render(request) although this process is not difficult, i am having trouble wrapping my mind about writing a view that would be applying to any tenant and not one particular tenant, especially because pd. read_csv needs the specific path. I was wondering if anyone had any help on this because I am really stuck and I cannot move forward. -
How to pass request.user correctly to query in Django Template
So I am attempting to query and display messages between two users in an inbox. I am running into a problem where no messages are appearing for request.user. It's showing as empty when there are messages. However, when I go into an inbox for another user that my request.user has messaged while still logged in to request.user, I can see the messages from both parties there and displayed correctly. So basically my current user cannot access their own messages. I know I need to pass request.user somehow into the template to query the messages correctly, but I'm not sure how. messages.html {% for msg in messages %} {% if msg.receiver_id == user.id %} <li class="text-right list-group-item">{{ msg.message }}<br/>{{ msg.date }}<br/>{{ request.user.username }}</li> {% elif msg.sender_id == user.id %} <li class="text-left list-group-item">{{ msg.message }}<br/>{{ msg.date }}</li> {% endif %} {% empty %} {%endfor %} views.py/messages def messages(request, profile_id): messages = InstantMessage.objects.filter(Q(sender_id=request.user, receiver_id=profile_id,) | Q(sender_id=profile_id, receiver_id=request.user,) ).\ values('sender_id','receiver_id', 'message', 'date', ).\ order_by('date',) return render(request, 'dating_app/messages.html', {'messages': messages,}) urls.py/messages path('messages/<int:profile_id>/', views.messages, name='messages') base.html/messages url href <a class="nav-link" href="{% url 'dating_app:messages' user.id %}">Check Messages</a models.py/InstantMessage class InstantMessage(models.Model): sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'senderr',on_delete=models.CASCADE ) receiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) message = models.TextField() date = models.DateTimeField(auto_now_add=True) def … -
Download youtube video to user machine on Django website
Pretty much what the question says. Right now I have this function using pytube: `def download(request, video_url): url='http://www.youtube.com/watch?v='+str(video_url) homedir = os.path.expanduser("~") dirs = homedir + '/Downloads' download = YouTube(url).streams.first().download(dirs) return redirect('../../')` But this downloads the video to a directory '/Downloads/' in pythonanywhere - the site that I have uploaded my project to. How do I download the video to the user's machine? The solution doesn't have to be using the pytube package, as I just want an answer. It will be great if you tell me how to download the file as an .mp3 file too. Thanks in advance. -
How to check is model fiel empty or not before save it to database
I have a model which is template for creating objects League(models.Model): league = models.IntegerField(primary_key=True) league_name =models.CharField(max_length=200) country_code = models.ForeignKey("Country",null=True, on_delete=models.SET_NULL) season = models.ForeignKey("Season", null=True,on_delete = models.SET_NULL, to_field = "season") season_start = models.DateField(null = True) season_end = models.DateField(null = True) league_logo = models.URLField(null = True) league_flag = models.URLField(null = True) standings = models.IntegerField(null=True) is_current = models.IntegerField(null=True) cover_standings = models.BooleanField(null=True) cover_fixtures_events = models.BooleanField(null=True) cover_fixtures_lineups = models.BooleanField(null=True) cover_fixtures_statistics = models.BooleanField(null=True) cover_fixtures_players_statistics = models.BooleanField(null=True) cover_players = models.BooleanField(null=True) cover_topScorers = models.BooleanField(null=True) cover_predictions = models.BooleanField(null=True) cover_odds = models.BooleanField(null=True) lastModified = models.DateTimeField(auto_now=True) Data for creating objects from League model coming from external API #get data response = requests.get(leagues_url, headers = header) #cutting it and paste into variables to create objects from them leagues_json = response.json() data_json = leagues_json["api"]["leagues"] for item in data_json: league_id = item["league_id"] league_name = item["name"] country_q =Country.objects.get(country =item["country"]) season = Season.objects.get(season = item["season"]) season_start = item["season_start"] season_end = item["season_end"] league_logo = item["logo"] league_flag = item["flag"] standings = item["standings"] is_current = item["is_current"] coverage_standings = item["coverage"]["standings"] coverage_fixtures_events = item["coverage"]["fixtures"]["events"] coverage_fixtures_lineups = item["coverage"]["fixtures"]["lineups"] coverage_fixtures_statistics = item["coverage"]["fixtures"]["statistics"] coverage_fixtures_players_statistics = item["coverage"]["fixtures"]["players_statistics"] coverage_players = item["coverage"]["players"] coverage_topScorers = item["coverage"]["topScorers"] coverage_predictions = item["coverage"]["predictions"] coverage_odds = item["coverage"]["odds"] #creating objects from variables b =League.objects.update_or_create(league = league_id,league_name = league_name,country_code = country_q,season = season,season_start = season_start, … -
function in form_valid not being called (django)
class ARecordCreateView(CreateView): model = Record form_class = ARecordModelFormSpecial template_name = 'engine/dns/dns_settings_a_create.html' def get_success_url(self): return reverse('dns_settings', kwargs={ 'domain_name': self.kwargs['domain_name'] }) def get_context_data(self, *args, **kwargs): context = super(ARecordCreateView, self).get_context_data(**kwargs) context['my_domains_dns_settings_user'] = Domain.objects.get(name=self.kwargs['domain_name']).created_by context['domain_name'] = self.kwargs['domain_name'] return context def form_valid(self, form): f = form.save(commit=False) f.domain = Domain.objects.get(name=self.kwargs['domain_name']) f.save() rectify_zone(self.kwargs['domain_name']) return super(ARecordCreateView, self).form_valid(form) def get_form_kwargs(self): kwargs = super(ARecordCreateView, self).get_form_kwargs() # update the kwargs for the form init method with yours kwargs.update(self.kwargs) # self.kwargs contains all url conf params return kwargs I import rectify_zone from this package: https://github.com/gnotaras/django-powerdns-manager/blob/master/src/powerdns_manager/utils.py django-powerdns-manager When I run rectify_zone in shell it runs fine, but for some reason is not being executed in form_valid. Can anyone help? Thanks in advance. -
I deployed one Django project on two Elastic Beanstalk servers. Why does one have no images/access to the static file?
I deployed the same application (I know it's the same because the directory structures are exactly the same and I checked every file with the diff command) on two Elastic Beanstalk environments. I checked the settings and they appear identical except for Security Groups and one is not synced with my key (so I currently can't get into it's EC2 instance). Do you have any advice as to why they are behaving differently. Both are Python 3.6 running on 64bit Amazon Linux/2.7.7 servers and I am running Django 1.1.1. Here is my config file: option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTING_MODULE: "ecs_site.settings" PYTHONPATH: "/opt/python/current/app/ecs_site:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: "ecs_site/ecs_site/wsgi.py" It's located in the .ebextensions directory. I think it's a problem with my static directory. Here's the pertinent information from the settings.py file. STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'ecs_site/static')] I'm sure you'll have environmental questions. I'm here. -
Cannot import function from mysite.views in Django
mysite is the app name i created in my django project. below is the hierarchy of my app. mysite --- views.py --- tasks.py --- urls.py --- __init__.py I have a normal function(there is no request parameter, hence no entry in urls.py as well) in views.py as shown below. def function1(param1,param2): return something I am trying to import this function1 in tasks.py by using from .views import function1 but its throwing an error saying ImportError: cannot import name 'function1' from 'mysite.views' Is there any way to get rid of this error. -
Django qsessions - __init__() got an unexpected keyword argument 'ip'
When I try to install django qsessions, I get this error: Traceback (most recent call last): File "/.../lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/.../lib/python3.8/site-packages/sentry_sdk/integrations/django/middleware.py", line 131, in __call__ return f(*args, **kwargs) File "/.../lib/python3.8/site-packages/sentry_sdk/integrations/django/middleware.py", line 92, in sentry_wrapped_method return old_method(*args, **kwargs) File "/.../lib/python3.8/site-packages/django/utils/deprecation.py", line 93, in __call__ response = self.process_request(request) File "/.../lib/python3.8/site-packages/qsessions/middleware.py", line 10, in process_request request.session = self.SessionStore( Exception Type: TypeError at /home/ Exception Value: __init__() got an unexpected keyword argument 'ip' Thank you for any suggestions -
Problem With Django POST Request in Google Cloud Endpoint
My iOS app sends POST requests to my Cloud Run service. I've implemented ESP for security. So here is the setup: Cloud Endpoints (ESPv2) (deployed on public Cloud Run instance) as a gateway for my private Cloud Run instance. I'm using firebase security definition. While sending POST requests to Cloud Endpoint I was getting 401. I thought the problem was with authentication. But I was wrong. Further testing in Postman: I disabled all security definitions in open api file. GET requests to Public ESP which calls Private Cloud Run Container work fine POST requests to Public ESP which calls Private Cloud Run Container result in 404 then I enabled all my previous security definitions: GET request with JWT to Public ESP which calls Private Cloud Run Container works fine POST request with JWT to Public ESP which calls Private Cloud Run Container result in 404 then I made my Private Cloud Run Container public (all_users) both POST and GET requests directly to Public Cloud Run work fine My Private Cloud Run Container runs on Django Rest Framework. Clearly the problem is in that EPS is not able to route POST requests to Private Cloud Run Container or Django is somehow … -
How to fetch data after selecting the item from dropdown, without reloading the page ,
I am trying to build the an invoice system,I have put all the models and views The problem that i am facing is when select the option from dropdown, I want it to fetch all field of that product from the database without reloading, and also I want this same step in next line with different product. [Views.py][1] [1]: https://i.stack.imgur.com/bVQhF.png Invoice.html <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <meta charset="UTF-8"> <title>Entry</title> </head> <body> <div class=""> <select name="" id="select_path" ONCHANGE="location = this.options[this.selectedIndex].value;"> {% for product in Products %} <option value="{% url 'book' product.id %}">{{ product.Name }} </option> {% endfor %} </select> {{productInfo.Name}} </div> </body> </html> Views.py from django.http import HttpResponse,Http404,HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .models import Product # Create your views here. def index(request): context={ 'Products':Product.objects.all(), } return render(request,'invoices/index.html', context) def query(request): context={ 'Products':Product.objects.all(), } return render(request,'invoices/invoice.html',context) def book(request,product_id): context={ 'Products':Product.objects.all(), 'productInfo':Product.objects.get(pk=product_id) } return render(request,'invoices/invoice.html',context) URL from django.urls import path from . import views urlpatterns =[ path('',views.index,name="invoice"), path('invoice/',views.query,name='detail'), path('<int:product_id>/book',views.book,name='book') ] Models from django.db import models # Create your models here. class Product(models.Model): id = models.AutoField(primary_key=True) Name=models.CharField(max_length=50) HSN_code= models.CharField(max_length=15,unique=True) Rate=models.DecimalField(max_digits=11,decimal_places=2) def __str__(self): return f" {self.id} {self.Name} {self.HSN_code} {self.Rate}" -
Django Storing Payment Method
I'm tasked with providing users the ability to store multiple payment methods (Credit Cards) within their profile. What's the best way to validate credit card entry and have it encrypted when saved to the database? This is a personal project and will only be used locally. -
How to play song from its object [closed]
Okay, so, I have two objects in django, two songs, and I want if I click on Frank Sinatra example, I want to play his song, if I click some other song, to play exactly that song, here is my code: Django models: class Song(models.Model): art_name = models.CharField(max_length=30) song_name = models.CharField(max_length=70) cover_image = models.ImageField(upload_to='images/') file = models.FileField(upload_to='musics/') Django views: def index(request): all_objects = Song.objects.all() json_data = serializers.serialize("json", Song.objects.all()) context = { 'json': json_data, 'all_objects': all_objects } return render(request, 'index.html', context) Javascript: var data = {{json|safe}} function playSong(){ console.log(data) } HTML: <div class="box"> <div class="arrowLeft">prev</div> <div class="arrowRight">next</div> <div class="img"><img src="{{ song.cover_image.url }}" alt="" onclick="playSong()"></div> <p class="title">{{ song.art_name }}</p> <p class="desc">{{ song.song_name }}</p> </div> -
How can i display my RadioSelect Widget in django
I have a model, form, view and i cannot seem to actually display the RadioSelect widget. it doesnt show anything, i think everything is fine except the views, however, i am unsure. I basically want someone to choose and option from the two radio buttons, submit to then be able to register as one of the two options but like i said i cant even get the buttons to show. views.py def registration(request): reg = Registration.objects.all() return render(request, 'HTML/Registration.html', {"reg":reg}) models.py class Registration(models.Model): OPTIONS = ( ('COUNS','Counsellor'), ('CLIENT','Client'), ) SELECT = models.CharField(max_length=15, choices=OPTIONS) forms.py class Registration(forms.ModelForm): class Meta: model = Registration fields = '__all__' widgets = {'SELECT': forms.RadioSelect} HTML <form method="POST"> {% csrf_token %} <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom"> <h1 class="h2">Registration</h1> </div> {% render_field reg.SELECT %} <div class="form-row"> <div class="col pt-md-2"> <input type="submit" value="Next" class="btn btn-primary" style="float: right;"> </div> </div> </form> -
Update several fields in model instance using select_for_update in Django
I have model class named DataObj and some copmlex method that fetches DataObj isntance in the beginning, performs some calculations and updates it's fields. For integrity in concurrent environment it utilizes optimistic locking using integer version field. In order not to wrap all calculations in @atomic, I have short and fast save_changes function: @transaction.atomic def save_changes(DataObj dataObj): db_instance = DataObj.objects.select_for_update().get(id=dataObj.id, version=dataObj.version) # copy all changes from dataObj to db_instance db_instance.save() and I call it from my complex method def long_update_func(dataobj_id): obj = DataObj.objects.get(id=dataobj_id) # perform several calculations, update fields obj.field1 = result_of_calc1() ... try: save_changes(obj) except: # whoops, version changed notify_data_changed_during_calculations() Question: copying fields is really annoying. Can I avoid copying fields in save_changes function? I have nice modified dataObj with exactly same id, that I use to lock database rows in select_for_update call. Can I simply rewrite like this (or similar): @transaction.atomic def save_changes(DataObj dataObj): db_instance = DataObj.objects.select_for_update().get(id=dataObj.id, version=dataObj.version) # save our instance, because it has same id as db_instance and therefore its row in db table is locked db_instance.save() ? -
Django dev server using old version of views.py
For some reason, the changes I make on the views.py file are not being reflected. I initially made a function inside view.py to return HttpResponse(request.POST.items()). Even after making changes to the function, it's still performing the same thing. I tried clearing the cache of the browser, restarted the server, and also tried deleting the pyc files. Nothing worked. Any guess on why this is happening? -
How to add a value for a ModelMultipleChoiceFilter to queryset?
I need to add a field 'All' to choices of ModelMultipleChoiceFilter. In MultipleChoiceFilter I just use: shops = Shop.objects.filter(is_active=True) SHOP_CHOICES = [('All', 'All')] for x in shops: SHOP_CHOICES.append((x.address, x)) SHOP_CHOICES = tuple(SHOP_CHOICES) but in ModelMultipleChoiceFilter I have queryset instead of tuple. My filter: def departments(request): if request is None: return Shop.objects.none() curr_user = request.user if curr_user.role == 'SV': return Shop.objects.filter(is_active=True) else: return Shop.objects.filter(is_active=True, custom_user=curr_user) class ShopFilter(django_filters.FilterSet): address = django_filters.ModelMultipleChoiceFilter(queryset=departments)