Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i log exceptions from ListCreateAPIView generic view
this is my generic view,i want to log exceptions that occurs when invalid post request is made to this view. from rest_framework.generics import (ListCreateAPIView) class ProjectListCreateAPIView(ListCreateAPIView): queryset = Project.objects.all() serializer_class = ProjectSerializer -
Dropzone.js POST to upload an image return 403
I'm using this js code to upload an image to my /media path. var zdrop = new Dropzone(target, { url: "/media/", maxFilesize:20, previewTemplate: previewTemplate, autoQueue: true, previewsContainer: "#previews", clickable: "#upload-label" }); But i get Not Found: /media/ I know that i'm wrong because i'm doing a post request to a folder where i upload my file. But what should i place instead in the url? I need to write a funcion in my view.py? How can i upload images in my MEDIA directory? Thank you -
Apache - Django - ImportLib do not import module
I deploy django-project and i am block to a problem of loading module. My project work perfectly MYENVPYTHON/manage.py migrate or with runserver or just call the wsgi.py file. But when i will deploy with apache the script i had an error in the error_log file of apache : [THEDATE] [mpm_prefork:notice] [pid 49174] AH00170: caught SIGWINCH, shutting down gracefully [THEDATE] [core:notice] [pid 49611] SELinux policy enabled; httpd running as context system_u:system_r:httpd_t:s0 [THEDATE] [suexec:notice] [pid 49611] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [THEDATE] [auth_digest:notice] [pid 49611] AH01757: generating secret for digest authentication ... [THEDATE] [lbmethod_heartbeat:notice] [pid 49611] AH02282: No slotmem from mod_heartmonitor [THEDATE] [mpm_prefork:notice] [pid 49611] AH00163: Apache/2.4.6 (CentOS) mod_wsgi/4.6.4 Python/3.6 configured -- resuming normal operations [THEDATE] [core:notice] [pid 49611] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' [THEDATE] [wsgi:error] [pid 49612] [remote MYIP] mod_wsgi (pid=49612): Failed to exec Python script file '/PATHTOMYPARENTPROJECT/MYSITE/MYSITE/wsgi.py'. [THEDATE] [wsgi:error] [pid 49612] [remote MYIP] mod_wsgi (pid=49612): Exception occurred processing WSGI script '/PATHTOMYPARENTPROJECT/MYSITE/MYSITE/wsgi.py'. [THEDATE] [wsgi:error] [pid 49612] [remote MYIP] Traceback (most recent call last): [THEDATE] [wsgi:error] [pid 49612] [remote MYIP] File "/PATHTOMYPARENTPROJECT/MYSITE/MYSITE/wsgi.py", line 21, in <module> [THEDATE] [wsgi:error] [pid 49612] [remote MYIP] application = get_wsgi_application() [THEDATE] [wsgi:error] [pid 49612] [remote MYIP] File "/PATHTOMYENV/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [THEDATE] [wsgi:error] [pid … -
Django Error: ValueError: invalid literal for int() with base 10: '10,030'
Have this code to import a csv into my Django DB. This is my model DB and while saving i got the error. This is the line that created the error 23764,"HUA FU","vessel","DPRK4",-0- ,-0- ,-0- ,"10,030",-0- ,"Panama",-0- ,"Vessel Registration Identification IMO 9020003; Linked To: CHANG AN SHIPPING & TECHNOLOGY." In my DB the column is vessel_dwt = models.IntegerField(blank=True, null=True) How should i put the column in my DB? as float, or string? Thank you! -
Why my contained Query doesnot work in spatial coordinates in GeoDjango?
These are my models. I imported the Shapefiles into this models class Parcel(models.Model): objectid = models.BigIntegerField() apn = models.CharField(max_length=80) lot_size = models.BigIntegerField() neibrhc = models.CharField(max_length=80) street_nbr = models.CharField(max_length=80) street_nam = models.CharField(max_length=80) city = models.CharField(max_length=80) zip = models.BigIntegerField() tra = models.CharField(max_length=80) subdivisio = models.CharField(max_length=80) lot = models.CharField(max_length=80) landuse = models.CharField(max_length=80) lu_general = models.CharField(max_length=80) lu_specif = models.CharField(max_length=80) lu_detail = models.CharField(max_length=80) lu_use = models.CharField(max_length=80) lu_sec_use = models.CharField(max_length=80) area = models.FloatField() perimeter = models.FloatField() shape_are = models.FloatField() shape_len = models.FloatField() geom = models.MultiPolygonField(srid=3492) def __str__(self): return 'City: %s' % self.city class Primary(models.Model): id = models.CharField(max_length=12, primary_key=True) address = models.CharField(max_length=30) city = models.CharField(max_length=30) zip = models.CharField(max_length=10) state = models.CharField(max_length=2) unit = models.CharField(max_length=13) primpgon = models.BigIntegerField() numpgons = models.BigIntegerField() x = models.FloatField() y = models.FloatField() censusbloc = models.CharField(max_length=15) objectid = models.BigIntegerField() geom = models.MultiPolygonField(srid=4326) from django.contrib.gis.geos import Polygon parcel = Parcel.objects.filter(objectid="22520").values() geojson = parcel[0]['geom'].geojson format_l = ast.literl_eval(geojson) coordinates_data = format_l['coordinates'][0][0] poly = Polygon(coordinates_data, srid=3492) poly_parcel = poly_california.transform(4326, clone=True) pprint(poly_parcel.coords) I define the Polygon as below (((-121.49440799279022, 38.55725848782723), (-121.49438844924772, 38.557303481514126), (-121.4943760310021, 38.5573320694682), (-121.49436263531841, 38.557362909896675), (-121.49402385986245, 38.557269114460084), (-121.49406987333441, 38.55716268909225), (-121.49440799279022, 38.55725848782723)),) My Aim is I want to locate the Primary data within the Parcel Data. So I tried this. Primary.objects.filter(geom__contains=polygon).values() When I try this queryset it throws the … -
filtering a queryset, applying more than one filter
My models are: models.User: id = pk username = text models.Offer id = pk description = text publicationDate = Date user = Fk(User) my serializer is: class UserOfferSerializer(ModelSerializer): offers = OfferSerializerAll(many=True, read_only=True) class Meta: model = User fields = ('id', 'username', 'offers') I am trying to apply more than one filter on the queryset: users = users.filter(offers__publicationDate__range=[startdate, enddate]). prefetch_related(Prefetch('offers', queryset=Offer.objects.filter( publicationDate__range=[startdate, enddate]))).distinct() then users = users.filter(offers__description__icontains=sometext).prefetch_related(Prefetch('offers', queryset=Offer.objects.filter(description__icontains=sometext))).distinct() First one works fine and the other one throws the following exception: ValueError: 'offers' lookup was already seen with a different queryset. You may need to adjust the ordering of your lookups. Any help? Thank you all :))) -
Django with Postgres and advanced constraints
I have the following model: class AppHistory(models.Model): campaign = models.ForeignKey('campaigns.Campaign') context_tenant = models.ForeignKey('campaigns.FacebookContextTenant') start_date = models.DateField() end_date = models.DateField(blank=True, null=True) The backend is a Postgres database. For the above model I need the following constraints to be checked before a dataset is inserted: A row can only be inserted if it does not overlap in the date (start_date - end_date) with an existing one with the same campaign and context_tenant A row can only be inserted if there's none with the same campaign and context_tenant where end_date is NULL I know there's the option to do this in Django by performing a validation. But I'd like to make sure that even manual insertion into the database are verified. So currently I came up with two options, database constraints and triggers. I'm not too familiar with postgres, so I'm uncertain how extensive the constraints are. Is it possible to do the above restrictions with constraints only or should I use triggers (or even something else)? -
python3 manage.py dbshell not working
I am getting the following error while executing python3 manage.py dbshell on my mac. Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/MySQLdb/__init__.py", line 19, in <module> import _mysql ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/_mysql.cpython-36m-darwin.so, 2): Library not loaded: libssl.1.0.0.dylib Referenced from: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/_mysql.cpython-36m-darwin.so Reason: image not found The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/base.py", line 114, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/base.py", line 315, in add_to_class value.contribute_to_class(cls, name) File … -
Field "pk" can only be accessed when assigned on its own line of code
I have a django web app that does some filtering of a list based on its field. When converting the list back to a queryset (by generating a list of primary keys and querying for those keys) I get a strange error. Django reports "Global name pk is not defined" when done like so: Note that "entry" is an object of type "myObject", which obviously has a field "pk". pk_list=[] for entry in filtered_List: pk_list.append(entry.pk) query = myObjects.filter(pk__in=pk_list) I fixed it by simply assigning the pk-field to a variable, like so: pk_list=[] for entry in filtered_List: key=entry.pk pk_list.append(key) query = myObjects.filter(pk__in=pk_list) While it works as expected, I have no idea why my first approach didn't work. Any guesses or ideas? -
Django Permanent Model - how to keep deleted objects in admin change view?
I'm using this package to provide soft delete logic. https://github.com/MnogoByte/django-permanent class ExternalSystem(PermanentModel): full_name = models.CharField() class Fact(PermanentModel): external_system = models.ForeignKey(blank=True, null=True, on_delete=models.DO_NOTHING) So, if I "delete" ExternalSystem, in Fact admin change view I see "-" in ExternalSystem field. FK is kept, but ExternalSystem object isn't accessable by default manager. The only way I found to fix it - is to change FactEditForm: external_system = forms.ModelChoiceField(queryset=ExternalSystem.all_objects.all()) However, I have to make such changes in ten+ forms. And I also have to override logic to separate two forms - Edit and Create - because "deleted" objects not supposed to be in CreateForm. But they must remain in ChangeForm for history reasons. Is there any other way? -
Django Error: ModuleNotFoundError: No module named 'ofac'
I have an old project, i have to work on. While running the project i got this no module error. Am not running the project on a virtual environment. I am running it on my MAC. Please see below the image of the folder structure. Hope it helps. Running Django 2 or more. Traceback (most recent call last): File "/Users/Dropbox/ofac_project/ofac_sdn/import_save/import_all_sdn.py", line 9, in <module> django.setup() File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'ofac' This is the code i want to run: import csv, sys, os # project_dir = "/Users/cohen/my-python-project/venv/ofac/ofac_project/ofac_sdn/import_save/" project_dir = "/Users/Dropbox/ofac_project/ofac_sdn/import_save/" sys.path.append(project_dir) os.environ['DJANGO_SETTINGS_MODULE']='ofac.settings' import django django.setup() from ofac_sdn.models import Ofac_Sdn from ofac_sdn.models import Ofac_Add from ofac_sdn.models import Ofac_Alt from ofac_sdn.models … -
Django webpage not showing button
I'm a beginner with django python and I've read a lot of tutorials for couple days now. I'm making some progress but I'm definitely making noob mistakes. My problem is that I want the data to be returned to my webpage, only Hello appears. The submit button in my template is supposed to appear first then send that account_Id number to my code to properly call the rest api. Any help is very appreciated, I'm sure this is an easy fix, Thank you for your time. views.py class AccountView(FormView): form_class = AccountForm template_name = 'account.html' email="xxxxxxx@yahoo.com" Password="xxxxxxxxxxxxxxxxxx" IntegratorKey="xxxxxxxxxxxxxxxxxxxxx" Date="2018-05-30" def form_valid(self, form,email,Password,IntegratorKey,Date): # request to the external API account_id = form.cleaned_data['account_id'] url = "https://demo.docusign.net/restapi/v2/accounts/" + account_id + "/envelopes" headers = { 'X-DocuSign-Authentication': "{\"Username\":\""+ email +"\",\"Password\":\""+Password+"\",\"IntegratorKey\": \""+IntegratorKey+"\"}", 'Content-Type': "application/json", 'Cache-Control': "no-cache", 'Postman-Token': "e53ceaba-512d-467b-9f95-1b89f6f65211" } querystring = {"from_date": Date, "status": "completed"} resp = requests.request("GET", url, headers=headers, params=querystring) ctx = { 'result': resp.text, } return render(self.request, 'result.html', ctx) url.py urlpatterns = [ url(r'',views.AccountView.as_view(), name='Account'), ] forms.py class AccountForm(forms.Form): account_id = forms.IntegerField() result.html <html> <h1>hello</h1> <h1>{{ctx}</h1> <body> <div> <h1></h1> </div> </body> </html> account.html {% extends 'result.html' %} <form action="/web/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </form> -
filtering queryset in django
I have a queryset in Django which looks like: [ { username1, [ { id, text-which-match }, { id, text-which-doesnot-match } ] }, { username2, [ { id, text-which-match }, { id, text-which-match }, { id, text-which-doesnot-match } ] } ] I am trying to filter it by a snippet of text appearing in the text and it is straightforward (to filter the first level object) but then I want to filter the inner array so what I am trying to do is to filter twice and return the outer object including some of the objects in the inner array to get a result like this: [ { username, [ { id, text-which-match } ] }, { username2, [ { id, text-which-match }, { id, text-which-match } ] is there any solution for this? Thank you! -
Django Generic ListView for multiple inlineformsets
Is it possible to have a generic DetailView for displaying an inline formset with multiple models having a foreign key reference to that same one table. -
Django - Search for existence of 'slug' in multiple models
I want to search for the existence of slug in multiple models at once in django, right now i have to search through all of them one by one. Is there any method to search through all models at once? -
the model field's form disappears in django admin
I have two models, which are User and Record. Each has several fields. from django.db import models class User(models.Model): openid = models.CharField(max_length=20) nickname = models.CharField(max_length=20,null=True) def __str__(self): return self.nickname class Record(models.Model): expression = models.CharField(max_length=100) user = models.ForeignKey(User) time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.expression I register them in admin.py from django.contrib import admin from .models import User,Record class RecordAdmin(admin.ModelAdmin): list_display = ('expression','user','time') class UserAdmin(admin.ModelAdmin): empty_value_display = "空" list_display = ('openid','nickname') admin.site.register(User,UserAdmin) admin.site.register(Record,RecordAdmin) it works well in django admin initially. but one day, the fields of the Record model disppeared. It looks like . No field displays. It makes me unable to modify or add the values of the Record model. The other model User works well and all data exists in database. So why? -
How to pass flag to child serializer in DRF
I have a nested serializer and I want to pass Parent serializer data to the child. But I don't understand how can I do this. I want to do something like this: class BookingSerializer(serializers.ModelSerializer): use_additional_fields = serializers.BooleanField() persons = PersonSerializer(many=True) class PersonSerializer(serializers.ModelSerializer): def validate_date_of_birth(self, value): if parent.use_additional_fields and not value: raise serializers.ValidationError(_('Date of birth is required')) return value class Meta: model = Person exclude = ('phone', 'date_of_birth') So if user select use_additional_fields in parent serializer, then some of my fields in child serializers should be required -
"pip install django-haystack" throwing exception
ERROR Command "python setup.py egg_info" failed with error code 1 in C:\Users\cvcvcv\AppData\Local\Temp\pip-install-uy8qqve7\django-haystack\ I want to optimize search bar for my django project, has per Documentation haystack docs. unable install because of above error. plz comment to know more exceptions occured -
Django fitler/exclude against list of objects
I'm having a model Animal and list of Animal objects A1 = [a1, a2, a3] Now I am making a Django query A2 = Animal.objects.filter(some__filters) Now I want to exclude A1 from A2 A3 = A2.exclude(A1) // Wouldn't simply work. I know I have to do something like this A3 = A2.exclude(id__in=[a.id for a in A1]) Should there be a shorter version of that? -
reference refs/head/master error in django
Hello guys um having this kind of error when running tests from a cloned project, and um not sure what to do File "/Users/moffat/.venvs/ambition-screening/lib/python3.6/site-packages/git/refs/symbolic.py", line 167, in _get_ref_info_helper raise ValueError("Reference at %r does not exist" % ref_path) ValueError: Reference at 'refs/heads/master' does not exist -
Input Fields not showing up from a Model in Django forms
I'm new to python and Django. I'm trying to display a form which shows the fields from a model. the model and form are different apps. here is my Users Model from django.db import models # Create your models here. class Users(models.Model): first_name=models.CharField(max_length=128) last_name=models.CharField(max_length=128) email=models.EmailField(max_length=256,unique=True) here is my forms.py from registerapp from django import forms from apptwo.models import Users class NewUserForm(forms.ModelForm): class Meta(): model = Users fields= '__all__' here is my views.py from registerapp from django.shortcuts import render from registerapp.forms import NewUserForm from apptwo.views import index def register(request): form=NewUserForm() if request.method=="POST": form =NewUserForm(request.POST) if form.is_valid(): form.save(commit=True) return index(request) else: print("error form invalid") return render(request,'registerapp/register.html') my register.html file <div class="container"> <h1>Register here</h1> <form method="POST"> {{ form.as_p }} {%csrf_token%} <input type="submit" class="btn btn-primary" value="submit"> </form> </div> this is what i'm getting register.html please help me find my mistakes -
How come django one-to-one field still shows previous foreign inputs
Why does the django admin one-to-one field still show the previously saved foreign key inputs in the drop-down list. I thought that it would'nt make sense as since it is a one to one field should'nt it be unique but it has other previously saved values in the foreign key drop down list. -
URL masking in Python Django
I have built a website using Django framework(www.example.com). While navigating the site the URL changes to like (www.example.com/home or /profile etc). Is there some way that the current url is masked by a placeholder eg(www.example.com/home should be shown as www.example.com). This should work throughout the website. The url shown to the user would remain same (www.example.com) to where ever the user navigates on the site -
Dealing with django admin foreign key as number of foreign keys increase
How can I optimize the django admin foreign key as the number of foreign key inputs increase in the list to a point where it becomes hard for the user to select the foreign key. -
How to print all recieved post request include headers in python
I am a python newbie and i have a controler that get Post requests. I try to print to log file the request that it receive, i am able to print the body but how can i extract all the request include the headers? I am using request.POST.get() to get the body/data from the request. Thanks