Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Displaying Data from Multiple Models
My models come from a postgres database. I have gotten data from both of my models to display in the browser (CurrentAlLeagueStandings and CurrentNlLeagueStandings). However, I can only get data from one model to display at a time. How do I get it to display data from each model, at the same time, on the same webpage. I'll include my code from gist. I am a beginner and I gave it a go, so if my code with both models doesn't make sense, bare with me. As I said before the code does work when I try to pull from only one model. Something to also note is that both of these models have the same field names. If anybody can help it would be greatly appreciated. An example relative to my code would be a huge help! https://gist.github.com/anonymous/052b91ea56a951ac3fbc5ab7f66cc9f8 -
Function save models django
There is an application model. The meaning of it is quite simple, the Author submits the application, the site administrator appoints the Contractor for its execution, which after completing the received application completes it. Everything seems to be fine, the application model was created, made sure that after the administrator chooses the Contractor the application immediately received the status of closed. But here is one problem that I can not cope with when the Administrator closes the application (Status "Completed"), then the application does not acquire the status Completed, because the Artist is assigned to it because of the save function in the model. How to make the status of the application complete, even if a contractor is appointed to this application? In advance I ask you to excuse me for such a presentation of the question, I'm still a beginner. Many thanks to all those who can help) models.py class Application(models.Model): STATUS_CHOICES = ( ('In_the_work', 'В работе'), ('New', 'Новая'), ('Complited', 'Завершена') ) author = models.ForeignKey('auth.User', related_name = '+', verbose_name = 'Автор') title = models.CharField(max_length=50, verbose_name = 'Заголовок') text = models.TextField(verbose_name = 'Описание проблемы') room = models.CharField(max_length = 4, verbose_name = 'Кабинет') published_date = models.DateField(blank=True, null=True, default = datetime.datetime.now, verbose_name … -
Full text search show frequency of a word
I have this model in django: class Text(models.Model): description = models.CharField(max_length=100, null=True, blank=True) title = models.CharField(max_length=100, null=True, blank=True) text = models.CharField(max_length=10000, null=True, blank=True) I am using this code in my django view to search for a word: from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector def someview(request): word = "someword" vector = SearchVector('title', weight='A') + SearchVector('text', weight='B') + SearchVector('description', weight='C') query = SearchQuery(word) result = Text.objects.annotate(rank=SearchRank(vector,query)). filter(rank__gte=0).order_by('-rank') And it returns a queryset of objects including the search word. But I would like to show the frequency of the word in each object instance. How would this be achieved? -
Which files should I have in my public_html for django?
I am using passenger to host django on a shared hosting plan at a2hosting. I have created a virtualenv in the /home/username/ directory with the cpanel setup app and then, in the same directory, I put a folder called website with my django project and apps in it along with passenger_wsgi.py. I have a .htaccess file in the public_html. I also have my static root and media root in the public_html folder. I, however, couldn't use the admin site(only the login page appeared but couldn't log in) or my own login system inherited from django authentication. I, then, copied the app files and admin and auth files into the public_html and the login in works. I still face other problems with the admin site and forms with post request. So, my question is, should I create my project in the public_html file? Or is my configuration somehow wrong? Any help is appreciated and I am sorry for any mistakes on my part. Thank you -
Making links in Django ,HTML and Jquery
I am using Django 1.8 and Python 3.5 This is my urls.py file from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.conf import settings urlpatterns = [ # Examples: url(r'^$', 'mainpage.views.home2', name='home2'), url(r'^currency/(?P<currencywa>[\w]+)', 'currency.views.curr1', name='curr1'), url(r'^userpage/', 'login.views.userpage', name='userpage'), ] I am trying to make links using Jquery for Django what I want to do is this <a href="somelink">test</a> // this resides in a table using jquery var typein="<a href=\"{% url 'curr1'%}\">test</a>"; $('#cryptotable > tbody:last-child').append('<tr id=\"5\"><td>data1</td> </tr>'); I want to do this equivalent in django <a href="{% url 'home2'%}">test</a> But when I click on this ,I get redirected to http://localhost:8000/{% url 'curr1'%} instead of http://localhost:8000/curr1} What do I do to use Django way of url links made using Jquery ? -
Adding an additional template to an existing project errors out
I posted something last week and I haven't been able to get an answer. I'm using the following github project for using filters. I'm having trouble getting any additional templates to work. https://github.com/sibtc/simple-django-filter When I attempt to add a new template to the project or view I get the following error when trying to navigate to search because the template has a reference to a new page called results,which the results of the filter will have a POST occur: django.urls.exceptions.NoReverseMatch: Reverse for 'results' not found. 'results' is not a valid view function or patter n name. When trying to add the url for the view for results using the following, I still get the error above: url(r'^results/$', views.results, name='results'), I also include from . import views in the urls.py I'm adding an empty view for results: def results(request): return render(request, 'results.html', args) I'm thinking it has to do something with how the directory structure of the simple filter app is setup and how i'm doing things. -
Making urls using Jquery
I am using Django 1.8 and Python 3.5 I am trying to make links using Jquery for Django what I want to do is this enter code heretest // this resides in a table using jquery var typein="<a href=\"{% url 'home2'%}\">test</a>"; $('#cryptotable > tbody:last-child').append('<tr id=\"5\"><td>data1</td> </tr>'); I want to do this equivalent in django <a href="{% url 'home2'%}">test</a> But when I click on this ,I get redirected to http://localhost:8000/{% url 'home2'%} instead of http://localhost:8000/home2} What do I do to use Django way of url links made using Jquery ? -
Python-Django. Providing multiple ldap server in python Django settings file
Followed the same syntax mentioned in : http://django-auth-ldap.readthedocs.io/en/latest/multiconfig.html Still can't figure out how to feed two ldap servers in django settings file. If anyone has got this setting work. Kindly share their valuable inputs. Thanks! -
How to use group-only permission in the application?
How to use group-only permission in the application? I have a user who is in a group1. I intend to get the permission to get the permission. How to do this? class home(LoginRequiredMixin, View): login_url = '/login/' def get(self, request): if request.user.has_perm('group1'): return render(request, 'index.html') -
Django ModelFormSet not submitting correctly
I am having trouble submitting a modelformset in my view. For some reason, the formset is not meeting is_valid criteria, whatever I set the actual data to. Here is the relevant part of the view: def admin_tools(request): ElectionFormSet = modelformset_factory(Election, exclude=('Complete',), formset=BaseElectionFormSet, extra=0) if request.method == 'POST': if 'edit_elections' in request.POST: election_formset = ElectionFormSet(request.POST) # print(formset) if election_formset.is_valid(): election_formset.save() messages.add_message(request, messages.SUCCESS, 'Election settings saved') return redirect(reverse('elections:home')) else: messages.add_message(request, messages.ERROR, 'Problem') return redirect(reverse('elections:home')) else: election_formset = ElectionFormSet() return render(request, 'admin/admin_tools.html',{ 'formset': election_formset, }) Every time I submit the formset I get the problem message indicating the formset is not valid and I don't know why. Here is form tag in the template: <form method="post" action=""> {{ formset.management_form }} {% for form in formset %} {% csrf_token %} <div class='card'> <div class='card-body w-75 mx-auto'> <div class='row'> <div class='col-6 text-center'> <p>Name<br>{{form.Name}}</p> </div> <div class='col-6 text-center'> <p>Videos<br>{{form.FlipGrid}}</p> </div> </div> <div class='row'> <div class='col-12 text-center'> <p>Description<br>{{form.Description}}</p> </div> </div> <div class='row'> <div class='col-6 text-center'> <p>Allow registration: {{form.CandidateReg}}</p> </div> <div class='col-6 text-center'> <p>Allow voting: {{form.VotingOpen}}</p> </div> </div><p>{{form.id}}</p> </div> </div> {% endfor %} <div class='text-center'> <br><button type="submit" class='btn btn-outline-dark' name='edit_elections'>Save</button> </div> </form> I'm not sure what the error would be here. My thought is that maybe each form … -
jquery: post not sending dynamic input
Firstly, I am aware that this question has been asked in many different flavours, however I am having trouble understanding why my current code does not send the data in a form. Some Context: I am building a django application and using the form in a bootstrap modal. I am sending multiple data inputs with one post form in the html template. Currently the UI is working as expected and when I check the post contents I only receive data in env_name[] and env_contents[]. HTML Here is the part of the html that should be defining the form i am sending. Note I omit some of it as it is already too big however I do not think it is on this side the issue lies. <form action="/user/session/action/" method="post" id="ModForm" > SOME TABLE SET UP CODE HAS BEEN OMITTED <input type='hidden' name="sha_id" value="{{ commit.id }}" /> <input type="hidden" name="web_url" value = "{{ project.web_url }}"/> <input type="hidden" name="project_id" value = "{{ project.id }}"/> <input type="hidden" name="project_name" value = "{{ project.name }}"/> {% if commit.active_session %} CODE NOT USED {% else %} <td><button type="button" class="btn btn-primary" name="launch" data-toggle="modal" data-target="#exampleModalCenter">Launch</button></td> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div … -
Iterating over a ManytoMany field and comparing values with another iteration not working as expected
I have two models. The Course model has a many-to-many field related to the Student model. Problem is, when I iterate through the Course.student and iterate trough the students to compare if values are same, there are too many iterations. Basically a list of students is normally displayed in my template, and when I submit the form, the Course.student field is updated by one. So when interation starts again, there will be 2 students to compare, which will display more students per page each time. Need to find a way to display the checked students just one time, otherwise display the form. {% for crs_stud in course.student.all %} {% for student in students %} {% if crs_stud == student %} <p>{{ student.name.upper }} is already enrolled.</p> {% else %} <form action="." method="POST"> {% csrf_token %} <label for="id_{{ student.id }}">{{ student.name }}</label> <input type="checkbox" id="id_{{ student_id }}" value="{{ student.id }}" name="student_ids"> <input type="submit"> </form> {% endif %} {% endfor %} {% endfor %} -
django - values() for foreign key relations
Django values() is very handy, is it possible to serialize nested object too? class Book(model.Models): name = models.CharField(max_length=50) user = models.ForeignKey(settings.AUTH_USER_MODEL) I would hope to do something like d = Book.objects.all().values('name', 'user', deep={ 'user': ['username', 'first_name', 'last_name'] # related user fields }) And to get a result [ { 'name': 'book1', 'user': {'username': 'user1', 'first_name': '...', 'last_name': '..'} } ] So I'll get a nested dict for the foreign key object (user), instead of just the user id. I don't need more than a depth of 1, so only one level of related objects. -
how to override user value and save into another table in django
I have a one model Product which have field location and 1 another model name is Inventory movement in which product is foreign key. inventory model product_id=models.ForeignKey(Product) from_location = models.CharField("from location",max_length=30) to_location=models.CharField("Locatiion",max_length=30) user=models.CharField("Supervised By",max_length=50) remarks=models.CharField("Remarks",max_length=50) now when user enter a to_location field is also override the product.location field -
Post.objects.filter(published_date__lte=timezone.now())
I am creating a blog using Django.I want to fetch my post from the database using Queryset by using command-Post.objects.filter(published_date__lte=timezone.now()) But I am getting blank output. I have already imported timezone using- from django.utils import timezone Here's a screenshot link to the screenshot -
Django start-app command
I am working on API with Django REST framework and Elasticsearch. I need to run a command which will setup Elastisearch index. I have defined a properly working command (BaseCommand). Is it possible to run this command on every django-rest start-app (simultaneously with runserver)? -
Djangocms on microsoft sql 2017
Django Version: 1.11.10 Python Version: 3.6.4 I would install DjangoCms on mssql 2017 and I followed this steps I installed djangocms with this setting DATABASES = { 'default': { 'CONN_MAX_AGE': 0, 'ENGINE': 'django.db.backends.sqlite3', 'HOST': 'localhost', 'NAME': 'project.db', 'PASSWORD': '', 'PORT': '', 'USER': '' } } After verified the good connection with python manage.py runserver I modified the database settings: DATABASES = { 'default': { 'CONN_MAX_AGE': 0, 'ENGINE': 'sql_server.pyodbc', #sql server 'NAME': 'myDB', 'USER': 'userdb', 'PASSWORD': 'passworddb', 'HOST': '127.0.0.1', 'PORT': '', 'OPTIONS': { 'driver': 'SQL Server', }, }, } And then I type: >python manage.py migrate >python manage.py runserver >python manage.py createsuperuser I can login as superuser but when I start with the cms_wizard I receive the following message: ProgrammingError at /it/cms_wizard/create/ Exception Value: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]'substr' is not a recognized built-in function name. (195) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'AND'. (156); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. (8180)") I have no idea how to solve the problem -
Conditional model fields on admin view
I'm quite new with Django. I'm trying to develop an admin interface for a robot I designed. This admin interface is used to create domotic scenario into a database. I created a Scenario model like this: class Scenario(models.Model): name = models.CharField(max_length=200) description = models.TextField() actionsId = models.ManyToManyField('AssistantAction') lastExecDateTime = models.DateTimeField() nextExecTime = models.DateTimeField() isRecurent = models.BooleanField() REPEAT_EVERY = [(i,i) for i in range(61)] repeatEvery = models.IntegerField(max_length=2, choices=REPEAT_EVERY, default=1) REPEAT_UNIT = [("Minutes","Minutes"), ("Hours","Hours"), ("Days","Days"), ("Weeks","Weeks"), ("Month", "Month") ] repeatUnit = models.CharField(max_length=20, choices=REPEAT_UNIT, default="Minutes") DAY_OF_WEEK = [(None, " "),("Monday", "Monday"),("Tuesday", "Tuesday"),("Wednesday","Wednesday"),("Thursay","Thursday"),("Friday","Friday"),("Saturday", "Saturday"),("Sunday","Sunday")] dayOfWeek = models.CharField(max_length=20, choices=DAY_OF_WEEK, default=None) MONTHS_WEEK = [(None, " "),(1,"First week"),(2,"Second week"),(3,"Third Week"), (4,"Fourth week")] monthWeek = models.IntegerField(max_length=1, choices=MONTHS_WEEK, default=None) DAY_OF_MONTH = [(i,i) for i in range(32)] dayOfMonth = models.IntegerField(max_length=2, choices=DAY_OF_MONTH, default=None) isActive = models.BooleanField() def __str__(self): return self.name The idea of these scenarios is that they are scheduled every X minutes/hours/days/weeks/months I would like the scheduled fields to be conditionals, for instance if the scenario is every 5 minutes, I don't want to see the fields for days, months etc. I hope this is understandable and hope someone could help me. Thanks in advance -
Tracking anonymous user when connected to Django via Django-Channels 2.02
I will try my best to explain this since this is my first post. Using Django 2.02, Django-channels 2.02. I wish to store what gets send, from the frontend to the backend into Django session store. My problem is that the Django-channels session scope only seems to store information as long as the WebSocket is open, but I need it store it like a Django http_session. First javascript from frontend index.html. <script> const conn = new WebSocket('ws://localhost:8000/'); var msg = { type: "message", message: "Trying to find a solution", date: Date.now(), }; msg = JSON.stringify(msg); conn.onopen = () => conn.send(msg); </script> Consumers.py from channels.generic.websocket import JsonWebsocketConsumer from importlib import import_module from django.conf import settings SessionStore = import_module(settings.SESSION_ENGINE).SessionStore #Have tried SessionStore to store but will also not work class ConnectConsumer(JsonWebsocketConsumer): def connect(self): self.accept() def receive(self, text_data=None): text = self.decode_json(text_data) #decode incoming JSON text_message = text.get('message') print(self.scope["session"]["message"]) #prints "None" self.scope["session"]["message"] = text_message self.scope['session'].save() print(self.scope["session"]["message"]) #prints "Trying to find a solution" def disconnect(self, message): pass Routing.py from django.urls import path from channels.http import AsgiHandler from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from consumers import ConnectConsumer application = ProtocolTypeRouter({ "websocket": AuthMiddlewareStack( URLRouter([ path("/", ConnectConsumer), ]), ) }) Views.py from django.shortcuts import render … -
Python/Django - Querying Database
So I have a Django API server running on local host 127.0.0.1:8000. This is the layout of my models.py: models.py class Book(models.Model): title = models.CharField(max_length=100) publisher = models.ForeignKey(Publisher) publication_date = models.DateField() def __str__(self): return u'%s' % (self.title) class Publisher(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=50) city = models.CharField(max_length=50) website= models.URLField() def __str__(self): return u'%s' % (self.name) I run a query like the following in my views.py file: book_list = Book.objects.all().values('title','publisher','publication_date') When this query is run and handled, the value seems to return the Index of the Publisher in it's original table, as opposed to the name linked to it (for example, if it is the 3rd publisher in the Publisher table, then the value 3 will be returned for publisher). Is there any way to get the actual name of the publisher that each value is linked to? Many thanks! -
Django: unhashable type 'list'
I'm trying to communicate a list of model objects into my template and just display them in a template. However, it doesn't like it when I put a list in my context. Is there a better way to do this? View: def team(request, team_number): cycle_times = CycleTime.objects.order_by('team') times_for_team = [] for cycle in cycle_times: if cycle.team == int(team_number): times_for_team.append(cycle) print type(cycle_times) print type(times_for_team[0].time) context = {'data', times_for_team} return render(request, "scoutapp2018/team.html", context) Template: <table> <tr> <th>Match Number</th> <th>Cycle Time</th> <th>Cycle Location</th> </tr> {% for cycle in data %} <tr> <td>{{cycle.match}}</td> <td>{{cycle.time}}</td> <td>{{cycle.location}}</td> </tr> {% endfor %}}} </table> -
Matplotlib in a Django Controller Error
So I have been building an app that takes recorded data from users and compares it to forecasted data from the REST API that the lab that I work in uses. I want it to create plots and store them in a directory , which I will then zip and return to them in a response. The problem is that for some reason when I plot the figures and save them in my view they take a long time to plot and they don't plot properly... Here is the code I am using. View: Note that a lot of the code has been omitted due to irrelevancy to my question, basically I just take the file date and loop through the list of uploaded files, then merge it with the data pulled from our REST API so that I can compare the forecasted and observed data. @login_required() def some_view(request): """Create the HttpResponse for the zip file with content""" # Setting response to none in case of errors response = HttpResponse() # Handle form submission if request.POST and 'submit-button' in request.POST: watershed = request.POST.get('watershed_select_input', None) if request.FILES: # Retrieving the gauge data csv gauge_data_list = request.FILES.getlist('gauge_data_upload') # Validate has_errors = False … -
Django object matching query does not exist
I have a problem with this code, it just doesn't want to pass to except: try: tariff = Cost.objects.get(language__name=order.language_destination.name, type__name=order.type.name) except Cost.DoesNotExist: tariff = Cost.objects.get(language__name=order.language_source.name, type__name=order.type.name) Every time it stops at try and it gives me: DoesNotExist at /shop/orders/doc/ Cost matching query does not exist. Any ideea why it's not getting the except code? -
Django: Set charfield default as variable composed of ForeignKeys
I need to set a default value for a CharField in a Django model as a composite of two ForeignKeys contained within the model itself. Here is the model in questions and the methods I attempted: class SensorParameter(models.Model): sensor = models.ForeignKey(Sensor) parameter = models.ForeignKey(Parameter) parameter_name_userdef = models.CharField(max_length=100, blank=False, default=default_name) live_value = models.FloatField() @staticmethod def default_name(): return str(self.sensor.name) + " - " + str(parameter.parameter_name) def __str__(self): return str(self.sensor.name) + ' - ' + str(self.parameter) def __key(self): return self.sensor.id, self.parameter.id def __eq__(self, y): return isinstance(y, self.__class__) and self.__key() == y.__key() def __hash__(self): return hash(self.__key()) class Meta: unique_together=(('sensor','parameter_name_userdef'),) Explanation: This will be a table of all Parameters that belong to a Sensor. The name of the Parameter instance is generated in another table by the Sensor instance, and the combination of both of those is presented in this table. The user can then opt to change the name of the Parameter for that Sensor only, through this table. The idea is, by default, the parameter_name_userdef(ined) will be a string of Sensor Name + " - " Parameter Name. But through a form and AJAX the user can change it to whatever string they want. I tried the following (assume "max_length=100, blank=False" are set): … -
Display contents of a file on website
Im trying to display the contents of the text file with no luck. I have tried php which looked like an easy way to do it with no luck base.html {% load i18n static %} <!DOCTYPE html> <html> {% load static %} <head> <head lang=en> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script> </head> <body> <div > <div class="jumbotron" style="background-color: white; padding: 1.5rem;margin-bottom:i 100.5rem"> <div class="row"> <div class="col-md-3"><a href="/"><img src="{% static 'css/images/hadoop.png' %}"</a></div> <div class="col-md-6"> <h2>Impala Query Metrics</h2> <hr class="my-2" href="{% url 'impala' %}"> </div> <?php $f = fopen("pathtofile/test.txt", "r"); // Read line from the text file and write the contents to the client echo fgets($f); fclose($f); ?>