Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django objects get deletes after a while automatically on heroku server
Does anyone know why my django saved objects getting deleted automatically after a while ' this happened like most of the times that i check my website and see's one of my files get's delete automatically from the server also the deleted file's is not the last saved file but 3rd last file sometime's maybe 2nd last file... and i don't think it's a problem with my written code because this doesn't happens on local development server where usually i keep running development server for more than 4-5 hours sometime's whole day.. -
How to clean 'forloop.counter' variable (reset variable to 1)
in my database there are customers and each customer have sensors. For example customers 1 have 2 sensors. am gettin sensors infos and put them separately in tables. but items's ID (NO) is wrong. please take a look to pic1 as coding, i use standard django template filters. {% for info in infos %} ...... ...... <span> {{ forloop.counter }} </span> {% endfor %} -
How to get selected data from different table in Django database and return json to web client
I have Company, product, customer table in view.py, and product.id, customer.id are forighen key in Company class, how to get the selected data. like sql (select * from Company, customer, product where Company.customer_id = customer.id and company.product_id =product.id) and make it return json, so that in the client side can get the json data? and how to use the json data in the web client? Im new in Django, can you help me with this issue? class Company(models.Model): id = models.IntegerField(blank=True, primary_key=True) customer_id = models.IntegerField(blank=True, null=True) product_id = models.IntegerField(blank=True, null=True) class product(models.Model): id = models.IntegerField(blank=True, primary_key=True) name = models.TextField(blank=True, null=True) class customer(models.Model): id = models.IntegerField(blank=True, primary_key=True) name = models.TextField(blank=True, null=True) -
How to Pass a value from mysql to a form field in create view
I have a PatientConsultationView with a createview class that creates, and an AllConsultationView that List all consultation. I will like to pass the consultation ID to the PatientObservationView and use it to populate the PatientObservationForm OR, just saved it in the PatientObservation Model without end users havent to enter the ID manually since it can be gotten from the AllConsultationView views.py class PatientConsultationView(CreateView): model = PatientConsultation template_name = 'patient/patient_consultation_add.html' form_class = PatientConsultationForm context_object_name = 'Patient_Consultation' success_url = reverse_lazy('patient_list') class AllConsultationView(ListView): model = PatientConsultation template_name = 'patient/all_consultation.html' context_object_name = 'All_Patient_Consultation' def get_consult_id(self): return PatientConsultation.objects.filter(consultation_id=self) class PatientObservationView(CreateView): model = PatientObservation template_name = 'patient/patient_observation_add.html' form_class = PatientObservationForm context_object_name = 'Patient_Observation' success_url = reverse_lazy('patient_list') forms.py class PatientConsultationForm(forms.ModelForm): class Meta: model = PatientConsultation fields = ('patient_id', 'weight', 'temperature', 'blood_pressure', 'pulse', 'oxygen_saturation', 'body_mass_index', 'status',) widgets = { 'patient_id': forms.Select(attrs={'class': 'form-control input-height', 'placeholder': 'Patient ID'}), 'weight': forms.TextInput(attrs={'class': 'form-control input-height', 'placeholder': 'Patient Weight'}), 'temperature': forms.TextInput(attrs={'class': 'form-control input-height', 'placeholder': 'Patient Temperature'}), 'blood_pressure': forms.TextInput(attrs={'class': 'form-control input-height', 'placeholder': 'Patient Blood Pressure'}), 'pulse': forms.TextInput(attrs={'class': 'form-control input-height', 'placeholder': 'Patient Pulse'}), 'oxygen_saturation': forms.TextInput(attrs={'class': 'form-control input-height ', 'placeholder': 'Patient Oxygen Saturation'}), 'body_mass_index': forms.TextInput(attrs={'class': 'form-control input-height', 'placeholder': 'Patient Body Mass Index'}), 'status': forms.Select(attrs={'class': 'form-control input-height', 'placeholder': 'Patient Status',}), } class PatientObservationForm(forms.ModelForm): class Meta: model = PatientObservation … -
Django development server static files 404
I know there's a lot of questions about the same topic out there, still there was not one which helped me. I can locate my static files using python manage.py findstatic --verbosity 2 FILENAME, yet when I run server it gives me 404 on those files. I have {% load staticfiles %} command at the beggining of my templates and every file is loaded with {% static FILENAME %} How can I fix this? -
Deploy Django Python 3 MySQL on AWS elastic beanstalk
Can anyone help to deploy django python 3 app on AWS Elastic Beanstalk. Need suggestions for- Configuration for settings.py Static & Media files to S3 RDS mysql setup and configuration Thanks in advance. -
The good bootcamp for python learner and django library
Im a learner of python for a year and i wanna become web app dev with django,is there any bootcamp in highly recommened to that purpose I apprecaite your helps -
Django templates. Comparing variable and constant not working/
I am using Django+python+Docker. I am trying to compare variable and constant in Django templates as: {% if some_variable < 1.25 %} <td class="success"></td> {% else %} <td class="danger"></td> {% endif %} When i'am runing this on localhost, it works fine. When i run this on server it doesn't work. Docker settings are same. All versions are same too. Variable got from django models as models.FloatField(). Db on server and localhost are migrated. -
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