Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to customize the login error message?
I want to change "please enter a correct username and password. note that both fields may be case-sensitive" to something else. In login.html I have {{ form|crispy }} and in urls.py I have url(r'^login/$', auth_views.login, {'template_name': 'login.html'}, name='login'), in my URLs.py. -
how to fixe obj is not callable in pycham
TypeError: 'NoneType' object is not callable enter image description here -
Decoding Django POST request body
I'm building an mapping app using cordova and making a post request sending the following JSON (feature) { "type": "Feature", "geometry": { "type": "Point", "coordinates": [ -6.6865857, 53.2906136 ] }, "properties": { "amenity": "pub", "name": "The Parade Ring" } } This is the JQuery code sending the request function savePub(feature){ $.ajax({ type: "POST", headers: {"csrfmiddlewaretoken": csrftoken}, url: HOST + URLS["savePub"], data: { pub_feature: JSON.stringify(feature) }, contentType:"application/json; charset=utf-8" }).done(function (data, status, xhr) { console.log(data + " " + status); pubDialogAlert("Pub saved",feature); }).fail(function (xhr, status, error) { showOkAlert(error); console.log(status + " " + error); console.log(xhr); }).always(function () { $.mobile.navigate("#map-page"); }); } When the request is received in the Django backend I am not sure why when I print the request body it looks like this, b'pub_feature=%22%7B%5C%22type%5C%22%3A%5C%22Feature%5C%22%2C%5C%22geometry%5C%22%3A%7B%5C%22type%5C%22%3A%5C%22Point%5C%22%2C%5C%22coordinates%5C%22%3A%5B-6.6865857%2C53.2906136%5D%7D%2C%5C%22properties%5C%22%3A%7B%5C%22amenity%5C%22%3A%5C%22pub%5C%22%2C%5C%22name%5C%22%3A%5C%22The+Parade+Ring%5C%22%7D%7D%22' and when I try to decode it and then use json.loads() it throws this error @api_view(['POST']) def save_pub(request): if request.method == "POST": data = request.body.decode('utf-8') received_json_data = json.loads(data) return Response(str(received_json_data) + " written to db", status=status.HTTP_200_OK) JSONDecodeError at /savepub/ Expecting value: line 1 column 1 (char 0) I am assuming because once it decodes the binary string it can't be converted to valid JSON because of those characters %22 etc, but I don't know what the … -
Tablediff in Django for sync'ing two table
I'm dealing with two tables that are growing at consistent rate. I need to find a way to sync these two tables. Whatever's missing from one table should be added or modified, but I can't seem to come up with a good way to do it as I don't know which to update. For example: Table A has a row with value (1, 2, 3, 4, '2018-12-10') while Table B has (1, 2, 3, 5, '2018-12-11'). I want to take the last modified value (so 1, 2, 3, 5) In addition, any newly added rows from one table should be added to the other table. I searched around and found tablediff using CLI, but I'm doing it through Django and wonder if I can do it through Django models or raw sql commands. If so, how? -
How to fix NoReverseMatch on redirect
Why am I getting Reverse for 'explorer_js' not found. 'explorer_js' is not a valid view function or pattern name. when calling the select view below?: def explorer_js(request): activities = Activity.objects.all() fill_column = lambda attr : [getattr(activity, attr) for activity in activities] d = { 'ids' : fill_column('id'), 'dates_added' : fill_column('date_added'), 'numbers' : fill_column('number'), 'athletes' : fill_column('athlete'), 'start_dates' : fill_column('start_date'), 'names' : fill_column('name'), 'countries' : fill_column('country'), 'links' : fill_column('link'), 'segment_efforts' : fill_column('segment_efforts'), 'distances' : fill_column('distance'), 'average_speeds' : fill_column('average_speed') } context = {'d': d} return render(request, 'explorer_api/explorer_js.html', context) def select(request): """Filters explorer data and sends it to explorer again""" return redirect('explorer_js') The app's urls.py: app_name = 'explorer_api' urlpatterns = [ # Home page. path('', views.index, name='index'), path('explorer_js/', views.explorer_js, name='explorer_js'), path('select/', views.select, name='select'), ] -
post_save doesn't list tags
Idea is to use a post_save signal to do things if an object has certain tags, but the tags are not being listed @receiver(post_save, sender=List) def list_saved(sender, instance, created, **kwargs): if created: for tag in instance.tags.all(): print(tag.name) This never lists any tags, it's an empty query set. Yet if I then open the shell and do: >>> l = List.objects.filter(pk=1) >>> for tag in l.tags.all(): >>> print(tag.name) It works fine. Why are the tags not available in the post_save? Tags are added to list as such: class List(models.Model): tags = TaggableManager() -
Add a link to custom django admin view
I've created a custom admin view as documented here. class MyAdmin(admin.ModelAdmin): def get_urls(self): urls = super().get_urls() my_urls = [ path('stats/', self.admin_site.admin_view(self.stats)), ] return my_urls + urls def stats(self, request): request.current_app = self.admin_site.name context = dict( # Include common variables for rendering the admin template. self.admin_site.each_context(request), # Anything else you want in the context... key='blah', ) return TemplateResponse(request, "sometemplate.html", context) The URL is working and the template is loading. But how, can I get a link to my new custom view into the overview of the Django admin? -
Overriding save_formset to populate inlines in Django Admin
I have 1 ModelAdmin that functions as the main form and 2 admin.TabularInlines that go along with it. I'm trying to pre-populate the CleaningEntryInline with data when the CleaningLog is saved via Many-to-Many relationship via a separate model called RoomList. So I should be selecting all the records with a FK from my CleaningAction model and using that as a FK reference in the EntryInline but whenever I try to save it throws an error but gives no traceback. I got as far as to figure out that you need to override the save_formset() method but don't really know where to go from there. Any help would be a lifesaver! class CleaningActionAdmin(admin.ModelAdmin): list_display = ['room', 'action'] list_filter = ['room'] class CleaningEntryInline(admin.TabularInline): model = CleaningEntry extra = 0 autocomplete_fields = ['cleaning_item'] fieldsets = [ (None,{'fields':[('cleaning_item', 'checked', 'na', 'grade', 'notes')]}) ] class CleaningLogAdmin(admin.ModelAdmin): def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) pre_instance = form.save(commit=False) get_actions = EquipmentAction.objects.filter(machine_action_id=pre_instance.cleaned_machine_id) # This is where I'm lost... for action in get_actions: new_action, is_new_action = CleaningEntry.objects.update_or_create( log_entry_id=pre_instance.id, cleaning_item_id=action.id ) new_action.save() for obj in formset.deleted_objects: obj.delete() for instance in instances: instance.save() formset.save_m2m() def save_model(self, request, obj, form, change): obj.auditor = request.user.username obj.save() ordering = ('-start_time',) list_display = … -
HTTP Error 500.0 - Internal Server Error Unable to place a FastCGI process in a JobObject. Try disabling the Application Pool CPU Limit feature
I am trying to run my Django project on an IIS server using wfastcgi. I keep getting this error. I have tried adjusting the CPU limit settings for the Application pool but this error is still occurring. How can I completely disable the CPU Limit feature? My config file: <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\users\a0232200\python36\python.exe|c:\users\a0232200\python36\lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <!-- Required settings --> <add key="WSGI_HANDLER" value="project.wsgi.application" /> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\project" /> </appSettings> </configuration> I have given read and execute access to the application pool tied to my Python36 directory. I have read that wfastcgi and cpu limits are mutually exclusive but the error is suggesting that I need to disable the limiting feature. -
Django Rest Framework: Proper retrieve view doesn't handle request when I slightly change parameter
I have this weird problem where when I try to retrieve one object from my database I receive the message {"detail":"Not found."}. I know the object is there because I can see it in my django admin. And when I try to retrieve another object it locates it fine. urls.py router = routers.DefaultRouter() router.register(r'recalls', views.Recalls) admin.autodiscover() from rest_framework import generics, permissions, serializers from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope, TokenHasScope urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include(router.urls)), path('api/v1/recalls/rundate/<str:run_date>/', views.Recalls.as_view({'get': 'retrieve'}), name='retrieve_by_rundate'), path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),, ] views.py class Recalls(viewsets.ModelViewSet): ''' This view will be fore retrieving a recall for a car from the database ''' queryset = CarFax.objects.all() serializer_class = RecallsSerializer permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] def list(self, request, **kwargs): queryset = GetRecalls.objects.all() serializer = RecallsSerializer(queryset, many=True) print('LIST') return Response(serializer.data) def retrieve(self, request, pk=None, *args, **kwargs): queryset = CarFax.objects.all() #record = get_list_or_404(queryset, self.kwargs) record = get_list_or_404(queryset, vin__exact=pk) serializer = RecallsSerializer(record, many=True) print('RETRIEVE') return Response(serializer.data) def retrieve_by_rundate(self, request, run_date=None): queryset = CarFax.objects.all() #record = get_list_or_404(queryset, self.kwargs) record = get_list_or_404(queryset, run_date__exact=run_date) serializer = RecallsSerializer(record, many=True) print('RETRIEVE RUNDATE') return Response(serializer.data) I am using the URL 'http://127.0.0.1:8000/api/v1/recalls/(?P<pk>[\w-]+)/$/' (which is automatically created by DefaultRouter(). The issue is that when I look up with one parameter, let's say "test1so'http://127.0.0.1:8000/api/v1/recalls/test1'` it works, … -
Compare and Difference between datetime.now() and datetimefield from db
I can't find any answer to this that works for me. I'm trying to check difference between datetime for created post with datetime.now() example of what I would like to do in view.py if (datetime.now() - post.created_at).minutes > 10: Do_this else: Do_that I have tried with timedelta things. Also tried strptime with datetime formats. No luck When I print the datetime.now() i get: 2018-12-10 20:22:10.535052 And with the post.created_at: 2018-12-10 20:18:52:544396+00:00 How do I make them comparable? -
django two foreign key to same model's different columns
I just started learning Django A couple of weeks ago. I want to be able to refer two foreign keys from payments model to Tenant's Model's Tenant_ID and tenant_Name. Pardon me for the formatting didnt know how to post here Tenants Model: from django.db import models from applications.houses.models import HousesTable # Create your models here. class TenantsTable(models.Model): STATUS_CHOICES = (('M','Married'),('S','Single'),('D','Divorced')) GENDER_CHOICES = (('F','Female'),('M','Male')) House_ID = models.ForeignKey(HousesTable, to_field='House_ID', on_delete=models.DO_NOTHING) Tenant_ID = models.CharField(max_length = 10, primary_key=True, unique = True) Name = models.CharField(max_length = 30, unique = True) Telephone = models.CharField(max_length = 15) Date_Admitted = models.DateField() Status = models.CharField(max_length=1,choices=STATUS_CHOICES) Sex = models.CharField(max_length=1,choices=GENDER_CHOICES) Date_of_Birth = model`enter code here`s.DateField() def __str__(self): return self.Tenant_ID Payments model: from django.db import models from applications.tenants.models import TenantsTable from applications.administrators.models import AdministratorsTable # Create your models here. class PaymentsTable(models.Model): PID = models.AutoField(primary_key=True) Tenant_ID = models.ForeignKey(TenantsTable, to_field = 'Tenant_ID', related_name="Tenants_ID", db_column='Tenant_ID', on_delete=models.DO_NOTHING) Name = models.ForeignKey(TenantsTable, to_field = 'Name', related_name="Tenant_Name", db_column='Name', on_delete=models.DO_NOTHING) Date_Admitted = models.DateField(null=True) Date_Paid = models.DateField() Start_Date = models.DateField() Expiry_Date = models.DateField() Duration = models.IntegerField() Status = models.CharField(max_length=15) Received_By = models.ForeignKey(AdministratorsTable, to_field='Name', on_delete=models.DO_NOTHING) def __str__(self): return self.Name -
Date format in queryset lookups
I'm trying to retrieve information by weekday using querysets in Django, but if I use the week_day look up I get this error: Exception Type: NotImplementedError Exception Value: subclasses of BaseDatabaseOperations may require a date_extract_sql() method I tried different ways of getting the week day: sun_data = week.annotate(weekday=ExtractWeekDay('date_in'))\ .values('weekday')\ .annotate(c=Sum('data'))\ .values('weekday', 'c') and mon_data = week.filter(date_in__week_day=2) But I haven't had luck with any solution I have wrote. Hope you can help me! :) -
Logout from windows authentication in Django
Using JavaScript code i.e. ClearAuthenticationCache, i am able to logout user from IE but didn't find anything to deal with it in Chrome. Please suggest... Thanks in advance -
Create a custom Django field which is actually is a formset
I have to a little bit complicated thing, which could be described like this: I need to create a form with multiple forms (and formsets), but this form should behave like a usual form and I need to save all these forms with one "save" button. Something like this were already implemented in django-superform library here. Because of restrinctions I can't just take some library and use it but I have to implement it by myself. I tried this approach and it works, but it is really dirty from the semantics side: I have to pass to inlineformset_factory some objects as a parent objects but they are actually not a parent of that objects. I just have to give users the way to work with a different entities related to the some other entity. So I think about more general approach. My idea is simple: I create a form with fields, and that fields are actually forms, each of these forms has two fields: one is default Django ModelForm and another is default Django Formset. So I have 3 nested levels: MainForm(forms.Form): system_1 = SystemOneFormField(prefix='system1') system_2 = SystemTwoFormField(prefix='system2') system_3 = SystemThreeFormField(prefix='system3') SystemOneFormField(forms.Form): general_fields = GeneralFormField(prefix='general') multiple_fields = MultiFields(prefix='multi') # one-to-many … -
Django Database Locked After Modifying Migrations
I accidentally set a default value in OneToOneField as a string and this caused an error when doing python manage.py migrate. So I modified the file storing the bad migration and now its displaying: django.db.utils.OperationalError: database is locked This is the code that caused this: from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('blog', '0008_remove_post_cover_image'), ] operations = [ migrations.AddField( model_name='post', #default=exit name='author', field=models.OneToOneField (default='extra',on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), preserve_default=False, ), ] How do I unlock the database again? -
Django Reset PW emails not sending on AWS
Difficult to phrase this question and what I've done as I don't know where the error is occuring. I'm using Django hosted on AWS Elastic Beanstalk and SES to send emails. (Only for password reset) However the password reset emails don't seem to be sending. When I try to send an email as below however it works. send_mail('Test', 'Email content', 'email@email.com',['email@email.com',]) Also locally the password reset email sends (its put in spam but that's a different issue) My email settings are: EMAIL_HOST = 'smtp.gmail.com' # mail service smtp EMAIL_HOST_USER = 'email@email.com' # email id EMAIL_HOST_PASSWORD = '****' #password EMAIL_PORT = 587 # EMAIL_USE_TLS = True EMAIL_BACKEND = 'django_ses.SESBackend' AWS_ACCESS_KEY_ID = 'ACCESSKEY' AWS_SECRET_ACCESS_KEY = 'SECRETKEY' AWS_SES_REGION_NAME = 'eu-west-1' AWS_SES_REGION_ENDPOINT = 'email.eu-west-1.amazonaws.com' DEFAULT_FROM_EMAIL= 'email@email.com' If it's relevant, anywhere I've written email@email.com is actually the same email. Any help would be much appreciated. Thanks -
Custom-formatted Django form errors appearing twice
I am building a very simple form in Django, and want to display form errors in a Bootstrap alert tag. I know how to do this (e.g. Django docs or Django Forms: if not valid, show form with error message or How to render Django form errors not in a UL? ). However, when I do, I am seeing the errors appear twice. It seems like Django's {{ form }} element in the template is displaying the errors in a ul tag by default, in addition to my custom-formatted errors. What is the best way to avoid this duplication? In template.html: <!--Load the file search form from the view--> <form action="" method="post" id="homepage_filesearch"> <!--Show any errors from a previous form submission--> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% endif %} {{ csrf_input }} {{ form }} <button class="btn btn-primary" type="submit">Search</span></button> </form> In views.py: from .forms import FileSearchForm def view(request): # Create a form instance and populate it with data from the request form = FileSearchForm(request.POST or None) # If this is a POST request, we need to … -
Django: command management call from model, from view or from where?
I am new on Python3 and DJango. I am writing an app where the user can register a Company using Company Name and AWS Access Key and Secret Key. I will use the Access and Secret key to make a inventory "Discovery" of the AWS Account. Well, I want what every time an user register a company (click to create) django executes a management command called infra_discovery.py inside my app_folder/management/commands (that is working fine when I call via python manage.py infra_discovery). I have the following model: from django.db import models from django.urls import reverse from django.contrib.auth.models import User from empresa.models import Empresa class InfraDiscovery(models.Model): # user will fill this three fiels: infra_empresa = models.ForeignKey('empresa.Empresa', on_delete=models.CASCADE, blank=True, null=True ) infra_aws_key = models.CharField(max_length=100, null=True, blank=True) infra_aws_secret = models.CharField(max_length=255, null=True, blank=True) # my script called infra_discovery have to fill this fields: infra_vpc = models.TextField(blank=True, null=True ) infra_ec2 = models.TextField(blank=True, null=True ) infra_ebs = models.TextField(blank=True, null=True ) infra_rds = models.TextField(blank=True, null=True ) infra_vpn = models.TextField(blank=True, null=True ) infra_bill = models.TextField(blank=True, null=True ) def __str__(self): return self.id def get_absolute_url(self): return reverse('infrastructure_discovery_edit', kwargs={'pk': self.pk}) I really don't know how to make django fulfill this fields using my script at every time user clicks in "create" button; … -
Django SubForm not getting kwargs in Django subview
I am trying to make subform work in subview but can't make it work. It mainly is problem with inheritance and I tried the standard Python way but still I got stuck at this problem. Error is at bottom. Link for BasketLineForm I am trying to inherit from. My Form I am inheriting in: from oscar.apps.basket.forms import BasketLineForm as CoreBasketLineForm class AddBattery(CoreBasketLineForm): class Meta(CoreBasketForm.Meta): model=Battery fields = ('battery_manufacturer', 'battery_capacity', 'battery_warranty') Link for BasketView I am inheriting from: My View I am inheriting in: from oscar.apps.basket.views import BasketView as CoreBasketView class BasketView(CoreBasketView): def get_formset_kwargs(self): kwargs = super(BasketView, self).get_formset_kwargs() kwargs['strategy'] = self.request.strategy kwargs['battery']=self.request.modify return kwargs def get_queryset(self): return self.request.basket.all_lines() def get_battery_form(self): return AddBattery() def get_battery_objects(self): return Battery.objects.all() def get_context_data(self, **kwargs): context = super(BasketView, self).get_context_data(**kwargs) context['battery_form'] = AddBattery(self.request.POST) context['battery_data'] = self.get_battery_objects() return context def get_success_url(self): return safe_referrer(self.request, 'basket:summary') ERROR: Request Method: | GET -- | -- http://localhost:8000/en/shop/basket/ 1.11.15 TypeError __init__() missing 1 required positional argument: 'strategy' /home/shazia/oscar/getyoursolar/apps/oscar/basket/views.py in get_context_data, line 69 /home/shazia/oscar/bin/python 3.6.7 ['/home/shazia/oscar/getyoursolar', '/home/shazia/oscar/lib/python36.zip', '/home/shazia/oscar/lib/python3.6', '/home/shazia/oscar/lib/python3.6/lib-dynload', '/usr/lib/python3.6', '/home/shazia/oscar/lib/python3.6/site-packages'] On my line 69: def get_context_data(self, **kwargs): context = super(BasketView, self).get_context_data(**kwargs) context['battery_form'] = AddBattery() #this is line 69 context['battery_data'] = self.get_battery_objects() print(context) return context -
how to dispaly multiple inline form an django admin
I have multiple models and i want to display them all on one page in django admin. Some of these have no relationship(fk,onetoone,mm). how i can achieve that? class Category(models.Model): name = models.CharField(max_length=100) class Industry(models.Model): name = models.CharField(max_length=100) class SampleImages(models.Model): image = models.ImageField(upload_to='images/tile_images') category = models.ManyToManyField(Category) industry = models.ManyToManyField(Industry) class SampleColor(models.Model): image = models.ImageField(upload_to='images/tile_color') name = models.CharField(max_length=25) class OrderDetail(models.Model): name_in_logo = models.CharField( max_length=150) slogan = models.CharField(max_length=20) describe_website_and_audience = models.TextField() -
How to reduce verbosity of gunicorn access logging
I upgraded to Gunicorn 19.9 from 19.4 and it about doubled the amount of logging output into Heroku. I believe this is all due to access logs, which are for some reason now on. I want to turn this off. This is what these detailed messages look like: Dec 10 10:34:46 ballprice app/web.5: (IP address) - - [10/Dec/2018:16:34:46 +0000] "GET /us/c/reptiles/pythons/ball-pythons/home HTTP/1.1" 200 11271 "-" "Mozilla/5.0 (Linux; Android 8.0.0; SM-N950U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.83 Mobile Safari/537.36" Heroku claims to be getting the logging via stdout/stderr, but it seems like the default option is for accesslog to be None: http://docs.gunicorn.org/en/latest/settings.html#logging I also tried http://docs.gunicorn.org/en/latest/settings.html#disable-redirect-access-to-syslog thinking maybe the logging was getting sent to syslog but this did not remove it either. I am starting gunicorn in this manner: web: bin/start-pgbouncer-stunnel newrelic-admin run-program gunicorn mysite.wsgi --pythonpath mysite --timeout 30 --max-requests 10000 --disable-redirect-access-to-syslog Thanks! -
getting error while loading static file(*.css) file in django
Problem:- Getting Error GET /static/enquiry/homepage.css HTTP/1.1" 404 1765 Question:- I have made entries and created static directory {% load static %} but unable to resolve the problem. -
Integrate drag and drop with django forms.Form
I am currently using a django.forms.Form to upload user files to my project. I now need to add drag and drop functionality on files. I can't find a way to directly attach a drag and dropped file to a form. My code this far is: **javascript** var dropzone = document.getElementById('file-upload-wrapper'); dropzone.ondrop = function(e) { var form = document.getElementById('file-upload-form') var length = e.dataTransfer.files.length; if(length > 1){ alert('one at a time please') return; }; for (var i = 0; i < length; i++) { var file = e.dataTransfer.files[i]; console.log('Do something here...') console.log(form) } }; **template** <form method="post" enctype= multipart/form-data display="none" id="file-upload-form"> {% csrf_token %} {{ form }} <button type="submit" id="submit-file">submit</button> </form> **form** class UploadFileForm(forms.Form): data_import = forms.FileField() class Meta: model = Recipe fields = ('data_import',) Is this possible to add a file to a form without the use of dropzonejs or another similar package? -
Which database for python mysql or postgresql ?
postgresql or mysql I want to create a good web application with python and Django framework but I'm not sure which database i should use? I search on Google and i find postgresql is better but that Posts is for 2 years ago but now in 2018 which database is good ? I need a database that will not need to be changed later with another database Thanks