Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Crontab with deployment environment
django cron job using this package django-crontab how setup or setting apache2 deployment environment? Help Please !! -
How to refer to set objects in a django view from a template?
I have data in a database in the form like this: collection_name|manufacturer|product_type|description|image_url ---------------------------------------------------------------- Testing |FakeCo |Bed |pretty nice|/img/1.jpg Testing |FakeCo |Desk |pretty bad |/img/2.jpg Testing |FakeCo |Nightstand |pretty ok |/img/1.jpg Testing |FakeCo |Draws |pretty nice|/img/3.jpg Initially, I was using a for loop to display fields from each result, which ends up with something like this:. For the example data set above, what I am trying to do is display only the first result from certain fields, knowing they are identical for all rows returned, and then for remaining fields only display them when they are distinct. I tried using sets in my django view, as another answer suggested this would eliminate duplicates and solve my issue. My django view: def collection_detail(request, name=None): template = loader.get_template('/webapps/my_webapp/furniture_site/main_page/templates/main_page/product-detail.html') products = product.objects.filter(collection_name=name) collection_name = [] manufacturer = [] description = [] image_url = [] for product in products: collection_name.append(product.collection_name) manufacturer.append(product.manufacturer) description.append(product.description) image_url.append(product.image_url) collection_name = set(collection_name) manufacturer = set(manufacturer) description = set(description) image_url = set(image_url) context={'products': products} return HttpResponse(template.render(context)) My issue is, that I am unable to refer to these set items in my template. For example, in my template using: {% for instance in products %} {{ instance.collection_name }} Collection <br /> {% endfor … -
I'm getting username from HTML form to my views but not password
I' getting username form HTML form but i'm not able to get password from input password field to my views in dajngo. views.py def logMeIn(request): username = request.POST.get("inputEmail", False) password = request.POST.get("inputPassword", False) return HttpResponse(password) my login.html file is .... <form method='POST' action = 'logMeIn/'> <div class="form-label-group"> <input type="email" id="inputEmail" name="inputEmail" class="form- control" placeholder="Email address" required autofocus> <label for="inputEmail">Email address</label> </div> <div class="form-label-group"> <input type="password" id="inputPassword" class="form-control" placeholder="Password" required> <label for="inputPassword">Password</label> </div> </form> please help me on this ,Thanks & Regards., -
Find out differences between dirlist on time A and time B on ftp
I want to build a script which finds out which files on a ftp server are new and which are already processed. for each file on the ftp we read out the information, parse it and write the information we need from it to our database. The files are xml-files, but have to be translated. At the moment I'm using mlsd() to get a list, but this takes up to 4 minutes because there are already 15.000 files in this dir - it will be more everyday. Instead of comparing this list with an older list which I saved in a textfile I would like to know if there are better possibilities. Because this task has to run "live" it would end in an cronjob every 1 or 2 minutes. If this method takes to long this won't work. The solution should be either in php or python. def handle(self, *args, **options): ftp = FTP_TLS(host=host) ftp.login(user,passwd) ftp.prot_p() list = ftp.mlsd("...") for item in list: print(item[0] + " => " + item[1]['modify']) this code examples already runs 4 minutes -
Take user input from multiple forms in the same page
I am working on a django web application. the application holds two forms in the same page. The first form is for uploading an image and the second form is a description for the image. After the user uploads an image and clicks on the upload image button, an image classifier should classify the image and autofill some parts of the second form. This is my code so far models.py class Item(models.Model): title = models.CharField(max_length=100) color = models.CharField(max_length=100) img = models.ImageField(upload_to='item/img/', null=False, blank=False) def __str__(self): return self.title def delete(self, *args, **kwargs): self.img.delete() super().delete(*args, **kwargs) forms.py from .models import Item class ItemImage(forms.ModelForm): class Meta: model = Item fields = ('img',) class ItemForm(forms.ModelForm): class Meta: model = Item fields = ('title', 'color') views.py from .forms import ItemForm, ItemImage from .models import Item def upload_item(request): if request.method == 'POST': form_img = ItemImage(request.POST, request.FILES) if form_img.is_valid(): form_img.save() form_des = ItemForm(request.POST, request.FILES) if form_des.is_valid(): form_des.save() return redirect('item_list') else: form_img = ItemImage() form_des = ItemForm() return render(request, 'upload_item.html', {'form_img': form_img, 'form_des': form_des}) upload_item.html template {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %} upload_item {% endblock title %} {% block content %} <div class="row justify-content-center"> <div class="col-6"> <h2>Upload item</h2> <div class="card mb-5 mt-1"> … -
When I use model in django, and I use many to one, How do I get the top 5 by comparing the count of the many
this is my models: class question(models.Model): question_user_id = models.ForeignKey('log_in.user', on_delete=models.CASCADE) question_type = models.CharField(max_length=10) question_date = models.DateTimeField('date published') question_name = models.CharField(max_length=100) question_content = models.CharField(max_length=10000) class comment(models.Model): comment_question_id = models.ForeignKey(question, on_delete=models.CASCADE) comment_date = models.DateTimeField('date published') comment_content = models.CharField(max_length=5000) comment_user = models.ForeignKey('log_in.user',on_delete=models.CASCADE) we can know that comment and question is in a relationship of many to one, I wonder how can i get the top 5 questions which has the most comments, I know I can find all the questions and use some arithmetics to solve it, but it costs a lot, can I just use the django model's Built-in methods to solve the problem? maybe like use question.objects.order_by(*),(actually, I don't know what to write in the *) -
Do we have to use SPA with RESTful API backend?
I am curious about the question stated in the title. I understand the pros/cons of SPA + RESTful stack vs Dynamic Web Pages. But is it reasonable to use other front-end architectures to communicate with RESTful API backend? Using Django as an example, can we create TWO Django applications, one serves as our front-end, one serves as our RESTful API Backend (via Django Rest Framework). When a user requests a page, the front-end application will makes calls to the back-end API to fetch and display the data, then sends back the requested page. Appreciate your feedback/insights! -
ssl is invalid ClearDB Heroku Django
I can't connect my ClearDb to Django app on Heroku, show me this error. -
Get opposite of manage.py inspectdb / print sql created from models
To get the django models from my sql database I can do: $ python manage.py inspectdb How would I get the sql tables that should be created from my models in django 2.1? I'm not looking for anything beside it literally printing out the sql create table syntax. No creating tables or anything else. I've tried using sqlmigrate, but could figure out how to get that to print the sql. Any help would be great here. -
How do you run a python file in html
A while ago, I created some mini games with python. And now i'm working with html. I know how to link a css file to an html file. But I do not know how to link a python file to some words in an html file. I have tried to directly href it to my python file like this: <a href="Alien Invasion\Main\Alien Invasion.py">Play the Game</a> This is what I've got so far {% load static %} <html> <link rel="stylesheet" type="text/css" href="{% static 'webinfos/style.css' %}"> <ul> <li><a>Home</a></li> <li><a>Alien Invasion</a> <ul> <li><a>Explanation of Game</a></li> <li><a>How to play</a></li> <li><a>Origin</a></li> <li><a>Play the Game</a></li> </ul> </li> <li><a>Crossy Road</a> <ul> <li><a>Explanation of Game</a></li> <li><a>How to play</a></li> <li><a>Origin</a></li> <li><a>Play the Game</a></li> </ul> </li> <li><a>Classic Snake Game</a> <ul> <li><a>Tips&amp;Tricks</a></li> <li><a>Best Gameplays</a></li> <li><a>Funny Moments</a></li> <li><a>How to Play</a></li> </ul> </li> <li><a>Other stuff</a></li> </ul> </html> I expected it so that when I click on the words that are linked to the file, it runs the game. But instead, it shows: Page not found (404) Can someone help me with this? Thanks. -
django super post not saving
I have a pretty simple update view: class GroupLocationUpdateView(UpdateView): model = GroupLocation form_class = GroupLocationForm grouplocation_form_class = GroupLocationForm grouplocation_term_form_class = GroupLocationForm template_name = 'ipaswdb/grouplocations/group_location_form.html' success_url = '/ipaswdb/grouplocations/' def get_context_data(self, **kwargs): context = super(GroupLocationUpdateView, self).get_context_data(**kwargs) ..stufffff... return context def post(self, request, *args, **kwargs): if self.request.POST.has_key('terminate'): form = GroupLocationTermForm(request.POST) if form.is_valid(): do things here with a model grouplocation_term.save() else: super(GroupLocationUpdateView, self).post(request, *args, **kwargs) #why is this not saving/posting??? return HttpResponseRedirect(self.success_url) I have this exact same code for another update view and it works great, this code does not error out but saves no changes updated on the form. Just curious where I could look to see if it is failing somewhere. I did check chrome's method:POST response header and the change is getting sent across the wire it just seems like its failing somewhere on the backend but I see that "POST /ipaswdb/grouplocations/272/ HTTP/1.1" 302 0 "GET /ipaswdb/grouplocations/ HTTP/1.1" 200 24213 in the terminal window and so it looks like things are a-ok? -
Bootstrap 4 modal appears behind background (Django app)
I have thoroughly researched this issue already, but all of the solutions are from an older version of Bootstrap, and they didn't help. My problem is that when I press the button, the modal appears behind the background. All the solutions I've found say that the parent container/modal can't have fixed or relative position. However, my modal doesn't have a parent container and I don't have any custom CSS written for the modal. I think the problem could be with the fact that I am using Django with this HTML file. Here is the code - example.html {% extends 'main/base.html' %} {% load static %} {% block title %}Example Title{% endblock %} {% block fullscreen_content %} <div id="map-canvas" style="height: calc(100% - 50px); width: 100%;"></div> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Launch demo modal </button> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> {% endblock %} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> base.html {% load static %} <!doctype … -
Feeding celery queue with it's own result
I'm coding a crawler for my SPA application. Since it's a SPA I can't use wget/curl or any other non-browser based solution for crawling, because I need a browser in order to run the javascript in my SPA. I coded this using python and selenium. It will start at the homepage, scan for all href elements, save them in a set, discard the ones that I have already visited (visited as in opened with selenium and collected all the href elements), and take the next URL from the set and visit it. Then it will repeat the process over and over until it has visited all links. The code looks like this: def main(): ... # Here we will be saving all the links that we can find in the DOM of # each visited URL collected = set() collected.add(crawler.start_url) # Here we will be saving all the URLs that we have already visited visited = set() base_netloc = urlparse(crawler.start_url).netloc while len(collected): url = collected.pop() urls = self.collect_urls(url) urls = [x for x in urls if x not in visited and urlparse(x).netloc == base_netloc] collected = collected.union(urls) visited.add(url) crawler.links = list(visited) crawler.save() def collect_urls(self, url): browser = Browser() browser.fetch(url) urls … -
Django - Logged in User Not Populating in admin.py
I’m trying to create a form to when the current logged in user makes a submission the user column in admin.py gets populated with the logged in user. My problem: The user column gets populated when a new user gets created however when the newly created user makes a form submission with the form listed below, the user column doesn’t get populated. The Custom User Model is located in users.models which is imported so I’m not sure why this isn’t working. How do I get the current logged in user to populate in admin.py in the users column with the form listed below? Any help i gladly appreciated, thanks. Code Below: user_profile/models from django.db import models from django.urls import reverse from django.contrib.auth.models import AbstractUser, UserManager from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from users.forms import CustomUserCreationForm, CustomUserChangeForm from users.models import CustomUser class Listing (models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True) created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=100) address = models.CharField(max_length=100) zip_code = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100) cc_number = models.CharField(max_length=100) cc_expiration = models.CharField(max_length=100) cc_cvv = models.CharField(max_length=100) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = Listing.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=CustomUser) user_profile/admin.py from django.contrib import … -
How to fix 'Interner Server Error (500)' when start 'mod_wsgi-express starts-server myapp/wsgi.py'
I'm using python 3.5, django 2.*, apache2 in ubuntu. It's success when I 'runserver' my django project and using 'mod_wsgi-express start-server', malt wisky(?) page appear well on the screen. But using command 'mod_wsgi-express start-server myapp/wsgi.py', '500 Internal Server Error' appeared. There is no log on var/log/apache2/access.log and error.log. And the Ubuntu terminal also doesn't show any messages. What are the causes? Just let me know what you think. -
Multiple website within single droplet with seperate django admins
I host two django website within a single droplet on different ports with different domains. I would like to have seperate django admin interface for each of the websites. I could create superusers for both of the websites but only one of the website's superuser could login through same_ip/admin. When try to login with other website's superuser, I receive error 'Please enter the correct username and password for a staff account.'. When try to reach django admin by same_ip:port/admin, I receive error '404 Not Found'. Would it be possible to reach different django admin interfaces through same_ip:8001/admin and same_ip:8002/admin? Or is there any other way? Hope someone could help me about this, thanks in advance -
intermittent No module named context_processors when using nginx/uwsgi
I am having an odd interment django problem. I have an app which is deployed at 30 different sites, some with apache and wsgi and some with nginx and uwsgi. At only the nginx/uwsgi sites and only intermittently, users will get the error No module named context_processors. It may happen on a page that was previously accessed with no error and upon refreshing the same page it will come up fine. It will not occur for months, then happen a few times in one day. Here is a typical traceback: Internal Server Error: / Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 158, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 156, in _get_response response = response.render() File "/usr/local/lib/python3.5/dist-packages/django/template/response.py", line 106, in render self.content = self.rendered_content File "/usr/local/lib/python3.5/dist-packages/django/template/response.py", line 83, in rendered_content content = template.render(context, self._request) File "/usr/local/lib/python3.5/dist-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/usr/local/lib/python3.5/dist-packages/django/template/base.py", line 173, in render with context.bind_template(self): File "/usr/lib/python3.5/contextlib.py", line 59, in __enter__ return next(self.gen) File "/usr/local/lib/python3.5/dist-packages/django/template/context.py", line 246, in bind_template processors = (template.engine.template_context_processors + File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/dist-packages/django/template/engine.py", line 85, in template_context_processors return tuple(import_string(path) for … -
Configurable SAML SSO Authentication in Django REST Framework
I have recently joined a project that was written with Django REST framework (DRF for rest of this question). I am working on adding the ability to configure SSO on a per customer/company basis. This is an existing application that is using TokenAuthentication and has a good number of users. TokenAuthentication would remain the default method of authentication but we want to allow an admin for an enterprise customer to configure a SAML 2.0 compliant SSO. Now instead of one size fits all we'd want to support a customer-selected SAML 2.0 (and potentially other forms of SSO or MFA in the future). Below I reference an existing question and answer that was helpful to see how to enable SAML support through a plugin but it serves a simpler use case. What we need to do seems to be pushing the limits of the DRF's normal use. Is there is a standard pattern for allowing a customer admin to choose an SSO platform via SAML (such as Okta or OneLogin) if desired but still allow TokenAuthentication and perhaps other SSO or MFA methods (SAML, OAuth...)? In other words I don't want a "one size fits all" authentication method but rather one … -
changing cursor while waiting for requested page to be render using html and django
I want to change the cursor to waiting while waiting to finish request for a page. I am using Django I have a page that has bottom when clicking the page random Wikipedia page will load. I want to change the cursor during the waiting this is the file view.py def get_page(request): r = requests.get('https://en.wikipedia.org/w/api.php?format=json&action=query&generator=random&grnnamespace=0&prop=extracts|images&rvprop=content&grnlimit=1') #r = requests.get('https://en.wikipedia.org/w/api.php?format=json&action=query&grnnamespace=0&prop=extracts&rvprop=content&titles=Application%20programming%20interface') #r = requests.get('https://en.wikipedia.org/wiki/Application_programming_interface') data = r.json() pageid = next(iter(data['query']['pages'])) title = data['query']['pages'][pageid]['title'] content = data['query']['pages'][pageid]['extract'] context = '<h1>'+title+'</h1><br>'+content # import time # time.sleep(2) return render(request, 'wiki/wikipage.html', {'data':context}) and this is the wikipidea.html file <FORM> <INPUT class="button" TYPE="button" onClick="history.go(0)" VALUE="Refresh"> </FORM> {{data | safe}} Most of the answers that I found are using JS and I need to use Django with HTML. Any suggestion? Thanks. -
what does precompile standard library mean?
i faced a lot of problem in django so I delete python and install it again with a customize installation. I saw precompile standard library check box but i didn't get it can someone explain that to me? -
GraphQL Endpoint returns 400
I have a django app built with graphene and I have a problem running a simple POST query for the GraphQL endpoint, it keeps returning a 400 Bad request syntax. but it should work since I don't have any problems running the query from the endpoint http://localhost:8000/graphql-dev and I can't see any issues in the way I send the postman request. I looked online for suitable solutions but couldn't find any that would help. Any help/tips would be greatly appreciated. -
Django running under Apache and mod_wsgi uses "virtual" file system?
Ok, I know this is strange, but after a day of searching, I couldn't find any answer to this problem. I've got this system running since two years with Django under Apache with a classical mod_wsgi installation. An exact mirror of the web site is used for development and testing. In order to speed up a query, I used the inbuilt Django cache, using a file backend. In development (inbuilt Django server) everything works fine and a file is created under /var/tmp/django_cache. Everything works also in production, but no file is created. I was surprised, so I started experimenting and inserted a bunch of prints in the django.core.cache modules and followed the execution of the cache stuff. At a certain point I got to a os.makedirs, which doesn't create anything. I inserted a open(), created a file (absolute path) and nothing is created. Tried to read back from the nonexisting file and the content was there. I'm really puzzled. It seems that somehow there is a sort of "virtual" filesystem, which works correctly but in parallel with the real thing. I'm using Django 1.11.11. Who is doing the magic? Django, Apache, mod_wsgi? Something else? -
Field value is lost when form form.is_valid() = False and form reloads
I'm manually rendering a ModelChoiceField in my form so that I can insert a custom attribute on each option. When there is any sort of form field error that prevents submission, when the page is reloaded, the user entered/selected data is lost (i.e. field values revert to what they were on the very first page load). I'm wondering how I can prevent the loss of this information when a form error forces the page/form to reload). Note: this only impacts fields that are manually rendered in the way shown below. forms.py self.fields['formpricing'].choices = ZERO_BLANK_CHOICE + tuple([(t.id, t) for t in FormPricingMethod.objects.filter(industryname=industry)]) self.fields['formpricing'].queryset = FormPricingMethod.objects.filter(industryname=industry) views.py formpricing = userprofile.formpricing form = BasisOfPricingForm(request.POST or None, user=user, initial={'formpricing': formpricing}) template <select name="formpricing" required="" id="id_formpricing"> {% for value, object in form.formpricing.field.choices %} <option typenumber="{{object.typenumber}}" value="{{value}}" {% if form.formpricing.initial.id == value %} selected {% endif %} > {{object.title}} </option> {% endfor %} </select> Thanks! -
Azure not finding custom deploy.cmd
I have a Django project that I have hosted on Azure. I'm need to add deployment which execute upon each deployment. I've used kuduscript to generate custom deployment scripts, and my file structure now looks like such: - site/ - app/ - manage.py - requirements.txt - .deployment - deploy.cmd I haven't made any changes to either the .deployment or deploy.cmd file. Yet when I run git push azure master I get the following error messages: Running custom deployment command... Not setting execute permissions for deploy.cmd Running deployment command... /opt/Kudu/bin/Scripts/starter.sh: line2: exec: deploy.cmd: not found App container will begin restart within 10 seconds Error - Changes committed to remote repository but deployment to website failed Any idea on why the deploy.cmd can't be found? -
Django Reverse Relation Serializer
I am trying to create a project for self learning and right now, I am stuck at this point. Its an event planner and each event will have meat. Organizer of the event can select or create new meat types for his event. Once the event created, guests can select their preferred meat type from the selection pool which the organizer picked. For example, as an organizer I can say I will have "Chicken", "Turkey", and "Beef" from a MeatType table which has "Chicken", "Turkey" and "Pork" . (Organizer will create a new MeatType and select it for his event) So I have 3 Django model related for this specific problem. Event model: class Event(models.Model): name = models.CharField(_('Event name'), max_length=255) capacity = models.IntegerField(_('Capacity'), null=True) address = models.CharField(_('Address'), max_length=255) date = models.DateTimeField(_('Event Date'), db_index=True) organizer = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Organizer'), related_name='events', on_delete=models.CASCADE) Meat Type model: class MeatType(models.Model): """ A model just to hold meat type names on the database. This model will only have a "name" field which represents the Meat Type. For example, "Chicken" or "Beef" """ name = models.CharField(_('Name'), max_length=255) and Available Meat Type Model: class AvailableMeatType(models.Model): """ Available meat types for the event selected by Organizer """ event = models.ForeignKey(Event, …