Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) … -
Difference between Django JSONField and TextField
I have to save a JSON string to a Django model and am curious as to which field type I should use. I have seen a JSONField used before, but surely a TextField will do the exact same job since JSON is a string? What type of field should I be using? -
Django queryset out of queryset union
I'm working on Django with a database where one of the models relates to itself like a tree like this: class Perfil(models.Model) : ingresado_por = models.ForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True) and I'm trying to access all 'branches' from a root perfil object. To do so, I thought listing the branches and then uniting them would be enough. On one level, that would look somewhat like this, I think: hijos = Perfil.objects.filter(ingresado_por=ingresor) une1 = qset.union(hijos) if hijos.exists() : nietos = [] for hijo in hijos : nietos.append(Perfil.objects.filter(ingresado_por=hijo)) if len(nietos) > 0 : une2 = une1.union(*nietos) une1 = une2 return une1 however, this throws a bad SQL syntax error. I added a couple of 'if une is QuerySet' and found that apparently my queryset union results aren't even querysets to begin with, despite the documentation listing union() as a function that returns a queryset. What data type are these unions? Or, what can I do for my code to work, if I need the final object to be a QuerySet, or list of perfil objects or something of that nature? (by the way, I'm not sure I'm using the *statement correctly, or if union allows it in the first place, but I've … -
Python/Django model query
Suppose I have a table that matches Drivers with Tracks, TrackDriver. class TrackDriver(models.Model): driver = models.ForeignKey(Driver, on_delete=models.CASCADE) track = models.ForeignKey(Track, on_delete=models.CASCADE) The following statement races = TrackDriver.objects.values() gives {'id': 1, 'track_id': 8, 'driver_id': 5} {'id': 2, 'track_id': 8, 'driver_id': 6} {'id': 3, 'track_id': 9, 'driver_id': 3} while I want to display it like {'track_id': 8, 'driver_ids'=[5,6]} {'track_id': 9, 'driver_ids'=[3]} I then want to add this to the view context so that I can list the track with their corresponding drivers on the template. How would I go about this? I hope this example makes any sense, as it's pretty hard to explain. I'm using Django 2.0. -
How to keep the current tab active in Jquery after reload the page also for dynamic tabs
$(document).ready(function(){ $('.scroll_nav li a').click(function(){ $('li a').removeClass("active_scroll"); $(this).addClass('active_scroll'); $('ul li .btn-br_all_gun').click(function(){ $('li a').removeClass("active_scroll"); }); }); }); <li><a href="{% url 'gun:browse_gun' %}" class="btn btn-br_all_gun">Browse All Your Guns</a></li> {% for gunName in gunModelUserTieIn %} <li><a href="#">{{ gunName.gun_model.model_name }}</a></li> {% endfor %} Browse all gun button is the static button. and remaining tabs are came dynamically in user select cases. Here When i click the other tabs the page is reloading that's why it will again shows the first:li a tab is active. how to solve this problem