Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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); ?> -
Confusion on django on shared hosting and problems with post requests
I am using django on shared hosting at a2hosting. I seem to be having some problems and confusions. Firstly, I can't login using the django admin. It gives me a page not found error with the CPanel error telling me that it couldn't find anything in, /home/username/public_html/admin. Note: I have a virtualenv folder (created via CPanel's setup python app) and website folder (with django project and passesnger) on the root directory. I don't know why it gives me an error like this. Similar problems occur with my sites own login system(created from the django admin). So, I decided to move the files according to the CPanel error messages. Once I moved the files(admin and auth from virtualenv/.../site_packages/django/contrib/...) and the app, which contained the login files, to the public_html, the login in my site seems to work but not the django admin login system(note, I get the django login page but, before moving the files I used to get a page not found error and after moving the files, it simply changes the url from www.example.com/home to something like, www.example.com/admin/home). One more problem takes place at a comment-like section. Logged in users can put a comment. So, once the site's login … -
How to rollback transactions in a loop django
I'm trying to rollback a group of transactions if there are exceptions thrown in the loop. But I don't want to break out of the loop or throw an exception without catching it. I don't want the business logic to be saved if any of the children in the loop throw an exception. So that means I can't put the transaction inside the loop because if any of them fails it would only rollback the transaction for the specific child. parent = Parent.objects.get(pk='something') exceptions = [] with transaction.atomic(): for child in parent.children.all(): try: # business logic which also saves other models # I don't want this saved if there is an exception for any object in the loop except Exception as e: exceptions.append({ 'id': child.id, 'error': str(e), }) if len(exceptions) > 0: transaction.set_rollback(True) for exception in exceptions: Child.objects.filter(pk=exception['id']) \ .update(error=exception['error'] # more business logic and raise exception parent.is_blocked = True parent.save() # I don't want this exception to rollback all transactions raise Exception('Parent {} is blocked'.format(parent.id)) I'm getting an error with the above code. The message is pretty straight forward. I'm trying to rollback the transaction outside of the block. django.db.transaction.TransactionManagementError: The rollback flag doesn't work outside of an 'atomic' … -
Django: Change page when drop down menü value is selected
I am trying to change the variables used to display a page with a selection-box when another value of the selection box is chosen. I´ve got three different folders I want to apply settings to (with radio buttons). The folder can be chosen from the dropdown menü, and then the needed values can be chosen with the radio buttons. My problem is a follows: I want to display the previously selected settings by checking the options that where chosen before. So if I change the folder I want to apply settings to, I want the checked radio button to change accordingly. Therefore I would like to do something like this: {% if selection_box_id={{certain_value}} %} .........chose another set of variables.......{% endif %} is that possible ?