Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django suddenly serving blank pages for anonymous users
Incredibly strange behavior and it happened out the blue, very suddenly. I'm not even sure it happened during code change. For anonymous users only, Django will serve only the index page, as normal. But any attempt to jump to another page in the site will be met with a completely blank screen. On these blank screens, Devtools will show the expected output, but I cannot select or see any element on the actual webpage besides the <html> tag. Sources show that all the correct files are being served, even a script that I have running on every page will run as normal(evident by the script's console.log() statement). No errors. As I said, I really don't think I changed any important code to cause such a break. The page simply isn't showing anything. I'm stumped. Only the index is showing. Further adding to the complexity--if I log in through admin, and am no longer an anonymous user, the site will work as usual for that user. I've checked git diff--nothing has changed except some code relating to an image feature I was working on. I've restarted the server many times. Restarted my browser, tried it in incognito both in Chrome and … -
When i run heroku ps:scale web=1 command i am getting this error. Can anyone help me with this
When i run heroku ps:scale web=1 command i am getting this error. ▸ Missing required flag: ▸ -a, --app APP app to run command against ▸ See more help with --help Can anyone help me with this. -
Amazon Seller Central integration in Django App
I am working in django web application. I have requirement to integrate Amazon Seller Central into my existing app. The tasks I need to implement by connecting Amazon Seller Central are. User can : Login List/Update Inventory positions. Update product info When I searched in the web, I found python-amazon-mws, but its documentation is incomplete and out-of-date. http://python-amazon-mws.readthedocs.io/en/latest/tutorial_1.html Thanks in advance. -
Hoe to store python results in Django model
I wrote one .py file which will do some network functions and save the one value I should save this value in Django model that is in database I wrote a .py file in the main project when I run python some.py I will get one result that should be in a database I am using the Django framework -
Pass object to Django model classmethod to save it
Is it a good practice to pass entire object to class method of a model to save it in a database or I should use create method each time directly? class PageEvent(models.Model): occured_at = models.DateTimeField() status_code = models.SmallIntegerField(default=200) load_time = models.IntegerField() load_time_valid = models.BooleanField() @classmethod def save_event(cls, event): return cls.objects.create( occured_at=datetime.fromtimestamp(event.ts), status_code=event.status_code, load_time=event.time, load_time_valid=event.time_valid ) -
Why does test case using Django's assertInHTML() method fail?
Given the following Django test case, why does it fail? And just as important, what can I do to test for the presence of the HTML element <form class="bc-form" id="update_template" action="" method="get" novalidate>? from django.test import TestCase class Test_assertInHTML(TestCase): def test_something(self): needle = '<form class="bc-form" id="update_template" action="" method="get" novalidate>' haystack = '''<html> <form class="bc-form" id="update_template" action="" method="get" novalidate> <table> <tbody> <tr><th>Template Name </th><td><select name="name" id="id_name"></select></td></tr> <tr><th>Format </th><td><select name="format" id="id_format"> <option value="E">Email</option> <option value="S">SMS</option> </select> </td></tr> <tr><th>The message </th><td><textarea name="message" cols="40" rows="10" required id="id_message"></textarea></td></tr> </tbody> </table> <input type="submit" value="Submit"> </form> </html>''' self.assertInHTML(needle, haystack, count=1) -
How to run such specific query using django models
I am using the following SQL code to check previous sunday: DATE_ADD(tbl.date, INTERVAL (- 1) * DAYOFWEEK(tbl.date) + 1 DAY) AS week Could you tell me whether I can use the same thanks to django models ? I have completely no idea how to do this. In another words I want to group by sunday in my query Thanks in advance, -
django.core.exceptions.FieldError: Unknown field(s) (email) specified for Profile
I am trying to customize djoser's createuser end point. For that I have installed django custom user following this link https://github.com/jcugat/django-custom-user. Here is my models.py from django.db import models from custom_user.models import AbstractBaseUser class Profile(AbstractBaseUser): account_address = models.CharField(max_length=30, blank=True) and serializers.py from djoser.serializers import UserCreateSerializer as BaseUserRegistrationSerializer class UserRegistrationSerializer(BaseUserRegistrationSerializer): class Meta(BaseUserRegistrationSerializer.Meta): fields = ('url', 'id', 'email', 'first_name', 'account_address', 'password') and in app.admin.py i have registered it in following way. from django.contrib import admin from custom_user.admin import UserAdmin from .models import Profile class MyCustomEmailUserAdmin(UserAdmin): """ You can customize the interface of your model here. """ pass # Register your models here. admin.site.register(Profile, UserAdmin) but when I am trying to makemigrations i am running into following error. any clue what's wrong here? -
Adding or removing a form as a different user type
So considering that I have these two user types: a teacher and a student, I wanted that a teacher could add or remove an upload form, from the course page. But a student could upload a file only once, and after form is submitted it won't show again. I managed to implement that after a student submits the file form it won't show anymore, but now I am a bit stuck. How do I allow a teacher user to add or remove the form from the course page for each particular course that he has ? For example show the form for course number 1 only and not other courses, and when he wants he can just remove it from that course as well. Here is what I did so far: def courses(request, slug): query = Course.objects.get(slug=slug) data = request.POST.copy() data['course'] = query.id form = StudentFileForm(data, request.FILES) if request.method == 'POST': if form.is_valid(): upload = form.save(commit=False) upload.user = request.user student = upload.user.student student.file_status = True student.save() upload.save() return HttpResponseRedirect(reverse('courses:confirmation')) else: form = StudentFileForm(initial={'course': query.id}) context = {'courses': Course.objects.filter(slug=slug), 'students': Student.objects.all(), 'students_data': StudentData.objects.all(), 'lectures': query.lectures.order_by('lecture_category'), 'form': form, 'uploads': StudentFileUpload.objects.all(), } return render(request, 'courses/courses.html', context) {% if user.is_student %} {% if user.student.file_status … -
Custom oauth in django website
I have a django website. I installed and configure django-oauth-tolkit. I have another website where my users resides. I want to give access of my django website to those users of another website using django-oauth-toolkit. I searched on the internet and I get authentication with gmail,facebook,github,twitter etc, I want similar kind of thing but instead of gmail and facebook I want to use my site for authentication. If anyone has any idea about it would be very helpful to proceed me further. -
Django NoreverseMatch error not found url
I've looked for pass paramater(id) with a link to view but i got this error: I want to click on the link and got redirect to modifyPlanteur.html with the form filled by the id query. but i got this error: Reverse for 'modifyPlanteur' with arguments '('',)' not found. 1 pattern(s) tried: ['blog/modifyPlanteur/(?P[0-9]+)$'] ps: sorry my bad english i'm french thanks. url project: urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^about/$', views.about, name='about'), url(r'^contact/$', views.contact, name='contact'), url(r'^blog/', include('blog.urls'), name='blog'), url(r'^admin/', admin.site.urls), ] if settings.DEBUG: import debug_toolbar urlpatterns = [ url(r'^__debug__/', include(debug_toolbar.urls)), ] + urlpatterns url app: from django.conf.urls import url from . import views app_name ='blog' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^posts/(?P<id>[0-9]+)$', views.show, name='show'), url(r'^planteur/$', views.planteur, name='planteur'), url(r'^mouvement/$', views.mouvement, name='mouvement'), url(r'^ajax/planteur/$', views.searchPlanteur, name='searchPlanteur'), url(r'^ajax_query/$', views.ajax_query, name='ajax_query'), url(r'^ajax_query/blog/ajax_query.html/$', views.ajax_query, name='ajax_query'), url(r'^autocomplete/$', views.autocomplete, name='autocomplete'), url(r'^get_planteurs/$', views.get_planteurs, name='get_planteurs'), url(r'^modifyPlanteur/(?P<id>[0-9]+)$', views.modifyPlanteur, name='modifyPlanteur'), ] views: def planteur(request): planteurs = Planteur.objects.all() #instance = get_object_or_404(Planteur, id=17) form = PlanteurForm(request.POST or None) if form.is_valid(): planteur = form.save(commit=False) planteur.save() #envoie = True # form = PlanteurForm() #else: # form = PlanteurForm() def modifyPlanteur(request, id): planteurs = Planteur.objects.all() instance = get_object_or_404(Planteur, pk=id) form = PlanteurForm(request.POST or None, instance=instance) if form.is_valid(): planteur = form.save(commit=False) planteur.save() envoie = True form = PlanteurForm() templates: … -
django_filter ModelChoiceFilter auth.models.User ForeignKey to_field_name
I am using django_filter to apply filtering to django_tables2 rendered in my template (Django 1.11). One of the fields I would like to filter on is a ForeignKey from in-built User model: class User(auth.models.User,auth.models.PermissionsMixin): class Task(models.Model): assigned = models.ForeignKey(User,on_delete=models.DO_NOTHING) My filter is setup as follows: class TaskFilter(django_filters.FilterSet): assigned = django_filters.ModelChoiceFilter(queryset=User.objects.filter(is_staff=False),label=('Assigned')) The filtering works fine but rather than the default "username" being displayed in the filter dropdown I would like to use the full name of the user: get_full_name Does anyone have advice on how to acheive this? Any guidance will be much appreciated! -
Django admin (grapelli) with custom create view
I am doing custom create view, I override change_form.html and change form url to custom one. In my app I have admin_urls.py which defines my custom url to create view. Then I have a admin_view.py where I have my custom create view defined: class SendPushNotificationsView(LoginRequiredMixin, PermissionRequiredMixin, CreateView): permission_required = 'push_notifications.add_pushnotification' model = PushNotification template_name = 'admin/push_notifications/change_form.html' form_class = PushNotificationForm def form_valid(self, form): push_notification = form.save() // some extra logic // send to some custom detail view return HttpResponseRedirect( reverse_lazy( 'admin-push-notifications:push-notification-detail', kwargs={'pk': push_notification.id}) ) def form_invalid(self, form): // here I want to render the same form withh error messages return render_to_response( self.template_name, { 'form': form, 'opts': self.model._meta } ) So I can not find a way to render the same form with error messages as it would be in default behaviour in django. The reason why I have custom creation is that i need some extra work to be done. I tried overriding model save or save_related (this solution had some other issues with convenience), then tried adding view in ModelAdmin by overriding get_urls and adding extra method, but it has the same issue since I dont know how to render same form on error. -
Django 2 / Python 3.6.3 STATIC_ROOT and javascript on Windows
Python: 3.6.3 // Django: 2.0.2 I am writting a Django app. I am developing it using PyCharm on Windows. I am debugging it on Windows. I am deploying it to a linux box. the linux side of things just works. The Windows side seems to forget about STATIC resources. Sometimes the app will load my project css file, sometimes not. It almost never loads the project js file. The Static portion of my settings file looks like: STATIC_URL = "/static/" STATIC_ROOT = os.path.join(SITE_BASE_DIR, "public/static/") STATICFILES_DIRS = [ # os.path.join(SITE_BASE_DIR, "public/static"), ] This setup works ok on linux but windows gets confused. On windows, if I uncomment the STATICFILES_DIRS entry (leaving STATIC_ROOT uncommented) then the css and js resources seems to work. On linux it complains about duplicate items in STATIC_ROOT and STATICFILES_DIRS. The static structure looks like |-- public | |-- favicon.gif | |-- favicon.ico | `-- static | |-- MyApp | | |-- css | | | `-- index.css | | `-- js | | `-- index.js | |-- admin | | |. . . | `-- django_extensions | |. . . This must be my fault but I'm not seeing where I am goofing up. -
Django URLField doesn't accept hostname-only URLs
I'm currently using Django with Docker. I have main dispatcher Django project, and several other microservices that are running on different Docker containers. When I start up a new microservice, I want to add new Django model which has URLField pointing that microservice. But URLField doesn't accept such URLs, e.g. http://foo-service/ and it's because of these code. Of course I could define custom validator or custom field that inherits URLField, but shouldn't URLField accept those URLs? -
Django jQuery File Upload stopped working on update
I have lost my file upload app. I followed the site below and had it working great. https://simpleisbetterthancomplex.com/tutorial/2016/11/22/django-multiple-file-upload-using-ajax.html I am not sure if it was updating to Django 2.0.2 or the latest update for jQuery File Upload, but it is not working now. This is the error I get in the view when I check if form is valid. <ul class="errorlist"><li>file<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Here is the html: <input id="fileupload" type="file" name="file" multiple style="display: none" data-url="{% url 'upload:index' %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'> Yes I updated the URL and the Form. Thanks. -
Django is only applying the first style from my css file
For some reason django is applying only the first style from my stylesheet to my template when I runserver. For instance, i wrote three styles: #header { text-align: center; }; .header-element { color: yellow; }; #foo { background-color: yellow; } in this case the style assigned to #header is being applied, but the other two are not. I assume i have referenced my /static/ folder correctly, since the first style is being applied and "base.css" is also showing in the "network" tab on chrome. My HTML is as follows: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}"> <title>DataClub</title> </head> <body> <div id="header"> <h1 class="header-element">DataClub</h1> <h3 id="foo" class="header-element">data driven aplications</h3> <hr> </div> {% block body %} {% endblock body %} </body> </html> any help would be much appreciated -
Live Streaming for numerous devices
Currently the idea is too have a raspberry pi that has two USB cameras attached streaming video preferably at 1080p 60fps or as close to that as I can. Both cameras don't always have to stream at the same time but sometimes they both need streamed. From the PI I want to send that video off to a Django Rest Server that saves the video and then restreams it off to a mobile application that requested it. So a device is associated with an account thus only that account should be able to view their devices stream. How do I go about accomplishing this? Was looking into pygst but their weren't enough resources for me to understand it. Figured sockets would be the best way to associate different devices to different client requests. Trying to get this done for my Senior Design project and this is the biggest issue. -
console not showing print message on server, django and uwsgi with nginx
I am currently using django's back end to post another api which works correctly when I am developing locally. But when I push it to a staging cloud server which uses uwsgi with nginx that it is not working properly anymore. I am trying to use print from django to either save the messages into a file or somehow show it in terminal so I can know the post response to start debugging but I have no luck trying to find a way to log any print I have already did something like this in the settings LOGGING = { 'version': 1, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/path/to/your/file.log', 'formatter': 'simple' }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, } } it does work perfectly and show messages normally but how can I also print messages into the file too? Can someone give me an idea or advice? Thanks in advance -
How could I add or remove a form as a different type of user?
I have two user types: a teacher and a student. I wanted that a teacher could add or remove an upload form, from the course page. But a student could upload a file only once, and after form is submitted it won't show again. I managed to implement that after a student submits the file form it won't show anymore, but now I am a bit stuck. How do I allow a teacher user to add or remove the form from the course page for each particular course that he has ? For example show the form for course number 1 only and not other courses, and when he wants he can just remove it from that course as well. Here is what I did so far: def courses(request, slug): query = Course.objects.get(slug=slug) data = request.POST.copy() data['course'] = query.id form = StudentFileForm(data, request.FILES) if request.method == 'POST': if form.is_valid(): upload = form.save(commit=False) upload.user = request.user student = upload.user.student student.file_status = True student.save() upload.save() return HttpResponseRedirect(reverse('courses:confirmation')) else: form = StudentFileForm(initial={'course': query.id}) context = {'courses': Course.objects.filter(slug=slug), 'students': Student.objects.all(), 'students_data': StudentData.objects.all(), 'lectures': query.lectures.order_by('lecture_category'), 'form': form, 'uploads': StudentFileUpload.objects.all(), } return render(request, 'courses/courses.html', context) {% if user.is_student %} {% if user.student.file_status == False %} <form … -
Shorten a Python Django DB query
We have m2m relationship between E and U models: class E(models.Model): us = models.ManyToManyField('U', related_name='events', symmetrical=False) class U(models.Model): pass Now we want to remove all links for U with pk=2. I wrote this code: U.events.through.objects.filter(u=2).delete(). Can this code be shortened/simplified? -
How do i make djangoCMS urls to work with my django app urls?
I'm developing a django site and i have built all my templates and then decided to install djangoCMS to manage my content, so the problem is that my django url patterns don't seem to work with djangoCMS page generated paths and this is causing a serious problem with the placeholders in my template pages since they only show up on structure view when i navigate to a djangoCMS page generated path but when i access the same page with my own defined urls the placeholders are not visible in structure view of the page? what might be causing this problem? -
Migrating to django-guardian permissions with custom User class
I am trying to migrate my models to use Guardian permissions. At this point I have: class Data(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Meta: permissions = ( ('view', 'View'), ('edit', 'Edit'), ('owner', 'Owner'), ) I created one migration that added the new permissions, and in a custom migration I am trying to assign the permissions like this: def assignDataPermissions(apps, schema_editor): Data = apps.get_model('api', 'Data') for data in Data.objects.all(): assign_perm('api.owner', data.user, data) class Migration(migrations.Migration): dependencies = [ ('api', '0169_auto_20180304_1619'), ] operations = [ migrations.RunPython(assignDataPermissions) ] This fails with guardian.exceptions.NotUserNorGroup: User/AnonymousUser or Group instance is required (got EmailUser object). Is there a better/proper way of migrating to Guardian? If not, how do I make it see my custom User class? -
How can I pass a variable from one page(view) to another on GET?
I need to pass on GET a variable from one page to another. On the next page, in the view/template I check the variable, and if exist I make some adjustments how the page is rendered. -
How to save to a remote server with Django
I'm fairly new to Python and Django. I've recently got a Django app working on localhost in Linux Mint 18.3 with a Postgresql database. I've uploaded the app to PythonAnywhere, but unfortunately it requires Java for some of the NLP features (Stanford POS). Is there a way to parse and process the data on a local system and save it to the remote Postgres DB and serving the data from the remote server? I've looked at some answers on here regarding SSH tunnelling, but I'm not sure this applies here?