Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending Push Notifications using Firebase and Django
I have a Django application configured to send push notifications using Firebase. I am able to send notifications from the development server (http) but when I deploy my application and access it using 'https' I am not able to receive notifications sent from within my app. I am implementing the FCM library for Django. Here is code used to send the notification: def send(self, data, registration_ids=None, **kwargs): if not isinstance(data, dict): data = {'msg': data} registration_ids = registration_ids or [] if len(registration_ids) > self.max_recipients: ret = [] for chunk in self._chunks( registration_ids, settings.FCM_MAX_RECIPIENTS): ret.append(self.send(data, registration_ids=chunk, **kwargs)) return ret values = { 'data': data, 'collapse_key': 'message'} if registration_ids: values.update({'registration_ids': registration_ids}) values.update(kwargs) values = json.dumps(values) headers = { 'UserAgent': "FCM-Server", 'Content-Type': 'application/json', 'Authorization': 'key=' + self.api_key} response = requests.post( url="https://fcm.googleapis.com/fcm/send", data=values, headers=headers) response.raise_for_status() return registration_ids, json.loads(force_text(response.content)) Messages are received by Javascript on the frontend: <script type="text/javascript"> $(document).ready(function () { requestPermission(); }); const messaging = firebase.messaging(); const tokenDivId = 'token_div'; var sendTokenInProcess = false; messaging.onTokenRefresh(function () { messaging.getToken() .then(function (refreshedToken) { console.log('Token refreshed.'); setTokenSentToServer(false); sendTokenToServer(refreshedToken); resetUI(); }) .catch(function (err) { console.log('Unable to retrieve refreshed token ', err); showToken('Unable to retrieve refreshed token ', err); }); }); messaging.onMessage(function (payload) { console.log("Message received. ", payload); … -
How do you "skip" the Django Middleware when using the requests library or urllib3?
I have a Django REST Framework and I am trying to pull json data from it to be used for the different projects I have in my Django application. I have middleware that hijacks urls with HttpRequest.urlconf = 'app.urls' so I don't have to use my base urls.py. Whenever I try to use requests.get("url"), my middleware picks it up and tries to redirect my original path to the api page instead of pulling the json data. Is there a way I can tell my custom Middleware to not run or is there a completely better way to do this? -
Why can't I use, user input in jinja if statement ? (I am new to django)
I want to display database item by using for loop if they match the user input through form. I want to stay on the same page after submitting the input. Basically what I am doing here is matching if the city name entered matches my database city. inc.html <form method = "get" action = ""> City: <input type= "text" name = "q" value = "{{ query}}" /> <input type = "submit" value = "search" /> </form> <h2>Inc</h2> {%for inc in incubators%} {%if query == {{inc.city_location}}%} #inc.city_location is in my database <ul> <li><p>{{inc.inc_name}} <br> {{inc.city_location}}<p></li> </ul> <hr> {%endif%} {%endfor%} views.py def search(request): query = request.GET.get('q') return render(request, 'ekyam/incubators.html', {"query": query}) Help would be greatly appreciated. Also let me know If I should add urls file too. -
Editing a field belonging to a through table in a formset
I have two models that have a many to many relationship via a custom through table. Foo(models.Model): ... models.ManyToManyField('Bar', through='Foo_Bar', related_name='foo_bar') Bar(models.Model): ... Foo_Bar(models.Model) foo = models.ForeignKey(Foo, related_name='foobar') bar = models.ForeignKey(Bar, related_name='foobar') foobar_relationship = models.CharField() I have created a modelformset for the model Foo allowing users to edit all records of Foo belonging to a specific instance of Bar via, FooBarFormSet = modelformset_factory(Foo, form=FooForm) foobar_formset = FooBarFormSet(queryset=Foo.objects.filter(foobar__BAR_ID=id)) What I would like is to have the users be able to edit the field foobar_relationship at the same time. I am not really sure how to achieve this. I can add foobar_relationship as an input no problem, I simply add a charfield to the form used to create my formset, and then I save the values when I set the relationships. The problem is that once a value is stored I don't know how to populatethe forms in my formset during a GET request. -
A wrong id is assigned to each new object being created in Django
I deleted some objects belonging to one of my models in Django. Now when I create a new object, a wrong id is assigned to this object. This id is not successive. How can I address this problem? The example: >>> Programmer.objects.all().values() <QuerySet [{'id': 1, 'name': 'Linus Torvalds','occupation': 'Software enginner'}, {'id': 2, 'name': 'Tim Cook', 'occupation': 'CEO'}, {'id': 3, 'name': 'Elon Musk', 'occupation': 'Entrepreneur, engineer'}]> >>> p4=Programmer(name='Mark Zuckerberg') >>> p4.save() >>> Programmer.objects.all().values() <QuerySet [{'id': 1, 'name': 'Linus Torvalds', 'occupation': 'Software enginner'}, {'id': 2, 'name': 'Tim Cook', 'occupation': 'CEO'}, {'id': 3, 'name': 'Elon Musk', 'occupation': 'Entrepreneur, engineer'}, {'id': 15, 'name': 'Mark Zuckerberg', 'occupation': None}]> -
How to convert Python Django API queries to direct SQL Queries
I have this code below which works for Python Django using mysql. Everything works fine. now all i want is to convert Django API queries to Direct SQL. Can someone help me with that. 1.) My first problem is CRUD Application with Django. I need to convert the View Queries to Direct SQL Queries Below is Models.py from django.db import models # Create your models here. class Member(models.Model): firstname = models.CharField(max_length=40) lastname = models.CharField(max_length=40) class Meta: db_table = "crud_member" def __str__(self): return self.firstname + " " + self.lastname View.py from django.shortcuts import render, redirect from .models import Member # Create your views here. def index(request): members = Member.objects.all() context = {'members': members} return render(request, 'crud/index.html', context) def create(request): member = Member(firstname=request.POST['firstname'], lastname=request.POST['lastname']) member.save() return redirect('/') def edit(request, id): members = Member.objects.get(id=id) context = {'members': members} return render(request, 'crud/edit.html', context) def update(request, id): member = Member.objects.get(id=id) member.firstname = request.POST['firstname'] member.lastname = request.POST['lastname'] member.save() return redirect('/crud/') def delete(request, id): member = Member.objects.get(id=id) member.delete() return redirect('/crud/') 2.) My second Problem is Registration and Login with Django I also need to convert its View Queries to Direct SQL Queries Below is view.py from django.shortcuts import render, redirect, HttpResponseRedirect from .models import Member # Create … -
Use Django OAuth2 provider with JupyterHub
I'm attempting to run a Django web application that pairs with a JupyterHub server, where users enter via the web app and are then granted access to a notebook server once they've signed in. To facilitate this, I'm attempting to use OAuth2, where Django provides the authentication and JupyterHub verifies users against that. I'm using django-oauth-toolkit to provide the authentication service and linking against it using the Generic OAuthenticator. A docker-compose reference implementation is available here. Currently, the authorize redirect works, but some part of the token retrieval process throws the following error: jupyterhub_1 | [I 2018-01-07 18:53:41.763 JupyterHub log:124] 302 GET /hub/oauth_login?next= → http://localhost:8000/o/authorize?client_id=5hICA5iNiBhBuROGzxGJqGQ7Ur7yH8dHi53aPLB5&response_type=code&state=eyJuZXh0X3VybCI6ICIiLCAic3RhdGVfaWQiOiAiYWQ0NDc3MGVmZmY5NDMyOGEzODBlNThjMGI5YWQ0ZTcifQ%3D%3D&redirect_uri=http%3A%2F%2Flocalhost%3A8001%2Fhub%2Foauth_callback (@172.22.0.1) 3.98ms django_1 | [07/Jan/2018 18:53:41] "GET /o/authorize?client_id=5hICA5iNiBhBuROGzxGJqGQ7Ur7yH8dHi53aPLB5&response_type=code&state=eyJuZXh0X3VybCI6ICIiLCAic3RhdGVfaWQiOiAiYWQ0NDc3MGVmZmY5NDMyOGEzODBlNThjMGI5YWQ0ZTcifQ%3D%3D&redirect_uri=http%3A%2F%2Flocalhost%3A8001%2Fhub%2Foauth_callback HTTP/1.1" 301 0 django_1 | [07/Jan/2018 18:53:41] "GET /o/authorize/?client_id=5hICA5iNiBhBuROGzxGJqGQ7Ur7yH8dHi53aPLB5&response_type=code&state=eyJuZXh0X3VybCI6ICIiLCAic3RhdGVfaWQiOiAiYWQ0NDc3MGVmZmY5NDMyOGEzODBlNThjMGI5YWQ0ZTcifQ%3D%3D&redirect_uri=http%3A%2F%2Flocalhost%3A8001%2Fhub%2Foauth_callback HTTP/1.1" 200 3159 django_1 | [07/Jan/2018 18:53:42] "POST /o/authorize/?client_id=5hICA5iNiBhBuROGzxGJqGQ7Ur7yH8dHi53aPLB5&response_type=code&state=eyJuZXh0X3VybCI6ICIiLCAic3RhdGVfaWQiOiAiYWQ0NDc3MGVmZmY5NDMyOGEzODBlNThjMGI5YWQ0ZTcifQ%3D%3D&redirect_uri=http%3A%2F%2Flocalhost%3A8001%2Fhub%2Foauth_callback HTTP/1.1" 302 0 jupyterhub_1 | [W 2018-01-07 18:53:42.959 JupyterHub log:124] 405 POST /o/token (@127.0.0.1) 9.08ms jupyterhub_1 | [E 2018-01-07 18:53:42.961 JupyterHub web:1590] Uncaught exception GET /hub/oauth_callback?code=Rz9OLMKqO0QBne5evvJJjusEFjEhto&state=eyJuZXh0X3VybCI6ICIiLCAic3RhdGVfaWQiOiAiYWQ0NDc3MGVmZmY5NDMyOGEzODBlNThjMGI5YWQ0ZTcifQ%3D%3D (172.22.0.1) jupyterhub_1 | HTTPServerRequest(protocol='http', host='localhost:8001', method='GET', uri='/hub/oauth_callback?code=Rz9OLMKqO0QBne5evvJJjusEFjEhto&state=eyJuZXh0X3VybCI6ICIiLCAic3RhdGVfaWQiOiAiYWQ0NDc3MGVmZmY5NDMyOGEzODBlNThjMGI5YWQ0ZTcifQ%3D%3D', version='HTTP/1.1', remote_ip='172.22.0.1', headers={'X-Forwarded-Host': 'localhost:8001', 'Accept-Encoding': 'gzip, deflate, br', 'X-Forwarded-Port': '8001', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36', 'Upgrade-Insecure-Requests': '1', 'Cache-Control': 'max-age=0', 'Referer': 'http://localhost:8000/o/authorize/?client_id=5hICA5iNiBhBuROGzxGJqGQ7Ur7yH8dHi53aPLB5&response_type=code&state=eyJuZXh0X3VybCI6ICIiLCAic3RhdGVfaWQiOiAiYWQ0NDc3MGVmZmY5NDMyOGEzODBlNThjMGI5YWQ0ZTcifQ%3D%3D&redirect_uri=http%3A%2F%2Flocalhost%3A8001%2Fhub%2Foauth_callback', 'X-Forwarded-For': '172.22.0.1', 'X-Forwarded-Proto': 'http', 'Host': 'localhost:8001', 'Connection': … -
custom fields aren't shown on django admin panel
I wanted to make a django registration with email confirmation and few custom fields. So I've used this class in forms.py: class SignupForm(UserCreationForm): email = forms.EmailField(max_length=200, help_text='Required') team = forms.CharField() role = forms.CharField() class Meta: model = User fields = ('username', 'email', 'password1', 'password2', 'team', 'role') and in my views.py function, i called the class using this: if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() After that I've checked the admin panel, and only the default fields were there (username, password, email, firstname, lastname) and my custom fields were missing (team, role). What is the problem and how to fix it? Thanks :) -
How to runserver and see website for github project files
New to Django, I am trying to view the website with its associated functionality generated by the project files here: https://github.com/tomwalker/django_quiz When I use the usual: manage.py runserver on the command prompt, it says that there is no manage.py file, and there isn't. Worryingly, I followed the instructions for installation which suggested: Run pip install -r requirements.txt ...and my computer proceeded to de-install Django 2.0? What is that about, and can anyone explain how to restore settings if I messed them up completely. The second part of the instructions for installation asks to change something in the INSTALLED_APPS and urls.py section, but where? There is nothing in the root directory and it doesn't specify which folder/app to do this in? I don't quite understand how to "run" (see/view) these files and see this quiz app in process on my local host. What do I need to add? Why is the manage.py file not included? Any explanation or something to point me in the right direction would be appreciated -
Messaging in Django with attachments
I'm currently working on a platform like workana, freelancer, upwork, etc. It is being developed in Django and I'm in charge of a messaging application similar with the ones of the platforms mentioned previously. In detail, it should be in real time, storing the information securely and with a attachment functionality. I tried using several django packages like Django-Postman but still can't do the trick. Any suggestions on how to build it in a fast and cost-efficient way? -
whats wrong with my django url in this basic search function?
I tried implementing a search bar in my nav bar that sends a GET request with parameters to /search. When I type something into the search bar and hit enter it just takes me to /search/ with a 404 error. Same if I manually type /search/?searchstring=32423 I also get a page not found. views.py def basic_search(request): query = self.request.GET.get('searchstring') if query: if float(query): results = JobExecution.objects.filter(id=query) if len(query) == 1: job_title = results.job return redirect('/search/searchstring=%s/%s' % job_title, query) context={"results": results} return render(request, 'root_index.html', context) urls.py url(r'^search$', views.basic_search,), url(r'^search$/?P<searchstring>\w+', views.basic_search, name='search') in my base.html <form class="navbar-form navbar-right" role="search" name="searchstring" action="/search" method="get"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search" id="Search"> </div> <button type="submit" class="btn btn-default"> <span class="glyphicon glyphicon-search"></span> </button> </form> -
Django CORS Headers not putting Access-Control-Allow-Origin even configured so
I'm following this tutorial for learning how to use GraphQL with Vue.JS, and for backend, using a Django app based on [this example][2]. This paste shows how I'm setting Django project. Although following all orientations, "CORS header ‘Access-Control-Allow-Origin’ missing" warning still appears. How can I solve this problem? -
How to write a simple test case for Django Rest Framework?
How would I write a simple unit test for this: http://server_ip:port_number/api/v1/package/ This is my setup: models.py class Package(models.Model): name = models.CharField(max_length=255, unique=True) def __str__(self): return self.name serializers.py class PackageSerializer(serializers.ModelSerializer): class Meta: model = Package fields = ('name',) views.py class PackageViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = PackageSerializer queryset = Package.objects.all() lookup_field = 'name' urls.py router = routers.DefaultRouter() router.register(r'package', views.PackageViewSet) urlpatterns = [ url(r'^api/v1/', include(router.urls)), ] -
os.path operation in Django, change/join path issue
I'm getting the name of a file in Django after an Image save : path-> 'companies/92_dsa/log/Hydrangeas.jpg' as it is in database I do a clone of the file, an resize (is an image) and want to save the new file with a different name. I get the directory of the original file: folder = os.path.dirname(path) the filename and extension: filename, extension = os.path.splitext(os.path.basename(media_path)) then create a new_filename = filename + '_sz' + extension and the I want to recreate the path: new_path = os.path.join(folder, new_filename) and the problem(slash-backslash before the filename): 'companies/94_sda/logos\Hydrangeas_sz.jpg' I'm working in Windows, bur the final deploy probably will be on Linux, so I want a fix indifferent of the OS. -
Auto-Expanding TextAreas on PDF Generated from Django Template
I'm using pdfkit to generate a PDF of a Django template (doing this by getting an HTML string of the page from Django's get_template and render functions and passing that string to pdfkit... see post). On this page, I have some TextArea's that can contain many lines of text, and by default, they just get cut off when generating the PDF. I've tried to fix this by using some javascript libraries (I've tried several) to automatically expand the TextAreas on page load. I can get these to work perfectly on normal pages, but when I try to include it on the PDF template, I get various errors ranging from not working at all to expanding the TextArea way too much. My first assumption was that there was some styling differences that were causing the issues, but I'm fairly certain I've ruled that out. I tried to load the PDF template directly as a view, and the TextArea's resized correctly, leading me to believe that there's something with pdfkits generation that isn't playing nicely with the resizing. Given this, I tried to look if pdfkit has any suggestions for issues like this and couldn't find any, and I also tried to … -
Django: Different views for POST and GET - Form validation errors
I have a DemandDetailView(DetailView) and BidCreationView(CreateView). On DemandDetailView page, there is a form (for creating Bids) which posts data to BidCreationView. I can't figure out what to do in case form is invalid. I would like to render DemandDetailView again with form errors and preserve corresponding URL. class DemandDetailView(DetailView): model = Demand template_name = 'demands/detail.html' def dispatch(self, request, *args, **kwargs): self.bid_creation_form = BidCreationForm(request.POST or None, request.FILES or None,request=request) return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['bid_creation_form']=self.bid_creation_form return context class BidCreationView(CreateView): http_method_names = ['post'] model = Bid form_class = BidCreationForm def get_success_url(self): return reverse_lazy("demands:demands") def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs.update({'request': self.request}) return kwargs def form_valid(self, form): form.instance.demand_id = self.kwargs.pop('demand_id') return super().form_valid(form) Do you have any ideas? My only idea is to use Cookies which isn't probably the best way. -
Logs suddendendly very verbose on heroku
I have a django app deployed on heroku and I am fetching my logs with papertrails. Since my last push on heroku I have started getting logs from every connection to my app of the form: "Jan 09 01:42:22 my_app_name app/web.1: some_ip - - [09/Jan/2018:03:42:21 -0600] GET /main_site/static/main_site/images/favicon.ico HTTP/1.1" 200 - "https://my_url" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36" for every GET or POST request that I get. As far as I can tell I did not touch anything related to logging so I am wondering whether anything can have changed somewhere and more importantly, how can I filter those out. My logging configuration is as follow, in particular anything going through django should have a different formatting so this seems to be possibly coming straight from Heroku. My logging configuration, if useful: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(module)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'standard', "stream": sys.stdout } }, 'loggers': { 'django': { 'handlers': ['console'], 'level': 'WARNING', 'propagate': True, }, 'my_app': { 'handlers': ['console'], 'level': 'INFO', 'propagate': True, }, }, } -
Rename nested annotated field via Django ORM
Is it possible to renaming nested fields using for group by clause? This query: paymentitem.objects.filter(payment=p).values('item__vat_tax').annotate(base=models.Sum('price')).order_by('item__vat_tax') returns expected data: <QuerySet [{'base': Decimal('41.322'), 'item__vat_tax': 15}, {'base': Dec imal('483.470'), 'item__vat_tax': 21}]> I want to rename field 'item__vat_tax' as 'vat'. This query: paymentitem.objects.filter(payment=p).extra(select={'vat': 'item__vat_tax'}).values('item__vat_tax').annotate(base=models.Sum('price')).order_by('vat') return the same result but surprisingly ordered by vat too. If I change the field name inside the value statement, it raise an error. -
Queryset that returns the data of a foreignkey relationship
I am trying to make a query that returns the data of a foreignkey relationship, but I do not succeed. I want to bring the data of the web field of the Radio model to the query that I make of the model ProgramasRadiales. I only manage to bring the data from the Model ProgramasRadiales. Models class Radio(models.Model): usuario = models.ManyToManyField(settings.AUTH_USER_MODEL) radio = models.CharField('Nombre de la Emisora', max_length=50) web = models.URLField() class Meta: ordering = ['radio'] verbose_name_plural = 'radios' def __str__(self): return self.radio class ProgramasRadiales(models.Model): rango = ( ('lun', 'Lunes'), ('mar', 'Martes'), ('mie', 'Miercoles'), ('jue', 'Jueves'), ('vie', 'Viernes'), ('sab', 'Sábado'), ('dom', 'Domingo') ) nombre = models.CharField('Nombre del programa de radio', max_length=60) dias = MultiSelectField('Selecciona los días', choices = rango, max_length=40) inicio = models.TimeField(blank = False, null = True) duracion = models.PositiveSmallIntegerField('Duración del programa(minutos)', default=False) radios = models.ForeignKey(Radio) class Meta: ordering = ['nombre'] verbose_name_plural = 'programas radiales' def __str__(self): return self.nombre Querys datos = ProgramasRadiales.objects.all().values() result <QuerySet [{'nombre': 'Matinal', 'inicio': datetime.time(10, 0), 'radios_id': 2, 'dias': ['mie'], 'duracion': 20, 'id': 3}, {'nombre': 'Nocturnos', 'inicio': datetime.time(18, 0), 'radios_id': 1, 'dias': ['jue', 'vie'], 'duracion': 20, 'id': 4}, {'nombre': 'Siempre Informados', 'inicio': datetime.time(6, 0), 'radios_id': 1, 'dias': ['lun', 'mie', 'vie'], 'duracion': 15, 'id': 2}, {'nombre': … -
Do Django Model Managers require using=self._db
In working with the Django user model I've noticed model managers include a using=self._db parameter when acting on a database. If I'm only using a single database, is this necessary? What does using=self._db do other than specify the database. Is this specified as a fail-safe in the event another database is added? -
How to pass a javascript request / variable to python in Django?
I'm trying to implement a game. When a user creates an alert using form, Javascript sends a variable or request to python/ views.py and python/views.py catch that and proceed to the next level. I am new to both django and python so any help would be appreciated. I think one way of doing this would be sending XMLHttpRequest. #html <script> (function() { var YourAlert = window.alert; window.alert = function() { // run some code when the alert pops up document.body.innerHTML += "<br>Congratulations"; YourAlert.apply(window,arguments); // run some code after the alert document.body.innerHTML += "<br>Go next level<br>"; //var req = new XMLHttpRequest(); //req.send(aVariable) }; })(); </script> <form action="" method="POST"> {% csrf_token %} Enter a comment: <br> <textarea rows="3" cols="60" name='comments'>{{comments}}</textarea> <br> <input type="submit" value="comments"> </form> #views.py def(request) if request.method =='GET': context['comments'] = '' response = render(request,'template.html',context) else: context['comments'] = request.POST['comments'] response = render(request,'template.html',context) #disabling xss protection response['X-XSS-Protection'] = 0 #if 'aVariable' in request.POST: #print("success") return response -
Is it possible to upload a file to django before submitting a form?
I'm working on a webapp that lets users upload rather large video files and (based on data in a form they fill out) process them. At the moment it's setup to start uploading the file as soon as the form is submitted (as that's how django does it) but I'd like to take advantage of the time in which the user is busy filling out that form (assuming they start uploading the file first). Is this possible? how would I go about achieving this? Is this a django feature? The way I've got it now is that I have this model for my video: class Video(models.Model): def user_directory_path_thumbnail(instance, filename): # file will be uploaded to MEDIA_ROOT/thumbnails/<identifier>.png return 'thumbnails/{0}.png'.format(instance.identifier) def user_directory_path_video(instance, filename): # file will be uploaded to MEDIA_ROOT/videos/<identifier>.png return 'videos/{0}.mp4'.format(instance.identifier) uploader = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=256) identifier = models.SlugField(blank=True, null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) description_short = models.CharField(max_length=300, default="none") description = models.TextField(default="none") uploaded = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) time = models.IntegerField() thumbnail = ResizedImageField(size=[320, 180],upload_to=user_directory_path_thumbnail, force_format='PNG') type = models.IntegerField(default=0) media = models.FileField(upload_to=user_directory_path_video, default=settings.MEDIA_ROOT + '/videos/test.mp4') # Used to show video title in django admin page instead of 'video object(n)' def __str__(self): return self.title def get_absolute_url(self): return "/view/" + self.identifier and … -
How to pass multiple query-set in another class function
Let suppose I have some model class Testmodel1(): amount = models.IntegerField(null=True) contact = models.CharField() class Testmodel2(): price = models.ForeignKey(Testmodel1, null=True) Now I am using django ORM and apply a query like: objs = Testmodel2.objects.filter(price__amount=123) and it is returning n number of obj in any case like (obj1, obj2,..) , also I have written a another function in another class which is handling these obj and performing some other task, like- Class SentMail(): def sending_mail(self, price_obj): """performing some task """ SO, currently I am doing like for obj in objs: sentmail().sending_mail(obj) Is there any other better way to do this to make it better, I tried to find a good way, but don't get. any help would be appreciated. -
Can Django contribute_to_class method be used with abstract models?
Is there a way to use contribute_to_class method with abstract models, such that it would be executed separately for each child? I have the following models: class BaseHistoryModel(Model): change = JSONField(blank=True, verbose_name=_('Change')) comment = models.TextField(blank=True) class Meta: abstract = True class HistoryHelper: def contribute_to_class(self, cls, *_args): self.create_history_model(cls) def create_history_model(self, cls): attrs = {'__module__': cls.__module__} history_model = type( '{}{}'.format(sender.__name__, 'History'), (BaseHistoryModel, ), attrs ) history_model.target = models.ForeignKey(cls) return history_model class BaseModel(models.Model): name = models.CharField() history = HistoryHelper() class Meta: abstract = True I need it to create a separate history model for every child of BaseModel, but when I run makemigrations all I get is one change which creates history model for the abstract BaseModel. Is there a way to somehow get it to create one for every child? -
Sending pre-saved messages over Channels in bulk, acting funky
Based on the multichat Channels example, I'm implementing a private chat with message persistence. I got them to save and send over, but the messages that I'm trying to "pre-load" in the chat box as soon as a user connects, will load for user-A only after user-B connects to the chat room. Then, the pre-saved messages will load in the chatbox for user-B after I disconnect and reconnect with user-A. I am trying to have all saved messages be loaded in the chat immediately after a user connects to the chat. Why doesn't it work on the first go? Here's a model method for the chat-Room which sends the message on behalf of the user: def send_message(self, message, user, recipient, msg_type=MSG_TYPE_MESSAGE): """ Called to send a message to the room on behalf of a user. """ final_msg = {'room': str(self.id), 'message': message, 'username': user.username, 'msg_type': msg_type} print(recipient, user) if msg_type == MSG_TYPE_ENTER: recipient = profile.objects.get(username=recipient) qs_1 = Message.objects.filter(recipient=recipient, sender=user) qs_2 = Message.objects.filter(recipient=user, sender=recipient) all_messages = sorted(chain(qs_1, qs_2), key=lambda instance: instance.timestamp) for message in all_messages: final_msg = {'room': str(self.id), 'message': message.message, 'username': user.username, 'msg_type': msg_type} self.websocket_group.send( {"text": json.dumps(final_msg)} ) if msg_type == MSG_TYPE_MESSAGE: recipient = profile.objects.get(username=recipient) m = Message(sender=user, message=message, recipient=recipient) …