Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Model Inheritance - Query parent model for 'unkown' relationship
Take the following as an example: class Manufacturer(models.Model): name = models.CharField(max_length=200, blank=False) slug = models.SlugField(max_length=200, blank=False, unique=True) class Category(models.Model): name = models.CharField(max_length=200, blank=False) slug = models.SlugField(max_length=200, blank=False, unique=True) class Product(models.Model): category = models.ForeignKey(Category, related_name='products') manufacturer = models.ForeignKey(Manufacturer, related_name='products') name = models.CharField(max_length=50, blank=False) slug = models.SlugField(max_length=200, blank=False, unique=True) class Car(Product): pass class Food(Product): pass class CellPhone(Product): pass what I am trying to do is create a 'base' class called Product and apply a variety of 'sub-product-types' using Model Inheritance. The reason I am not using the Django's 'Abstract Model Inheritance' is because I actually want a table in my DB to hold all the products, so I can make a query like Product.objects.all() to get all the products, then type product.car to get all the field values for the related Car object. However, the problem I am running in to is that there is no way in knowing which 'relationship' a Product object has. Is it related to Car? Food? CellPhone? How should I approach this? Is there a better database schema I should be using? -
django-graphene alter column name deprecation
I would like to alter a column name in a table my database, deprecate the old field in django-graphene and add the new field. How or can I do this without creating the same column twice in my Django model? I can avoid errors during system checks while doing this, but still run into errors with my tests. Model class MyModel(BaseModel): my_column = models.CharField( max_length=255, blank=True, null=True) mycolumn = models.CharField( max_length=255, blank=True, null=True db_column='my_column') Schema class MyNode(DjangoObjectType): mycolumn = String(deprecation_reason='Deprecated') Settings SILENCED_SYSTEM_CHECKS = ['models.E007'] This works, however, now I try to run tests where I create a sample MyModel factory instance. class TestMyModel(TestModelBase): def setUp(self): self.my_model = MyModel(my_model_nm='Some model') Which, of course, throws an exception. django.db.utils.ProgrammingError: column "my_column" specified more than once I seem to be going about this wrong. How do I change a field name in django-graphene, deprecate the old name and have a new field reference the same column in my table? graphene==1.2 graphene-django==1.2.1 graphql-core==1.0.1 -
Django add hard-coded href links to an admin model's form view page
In Django's admin panel, how do I add hard-coded links to a Django model's form page (/add/ page). These are links to documentation that will never change. I want these links to appear every time on the form as a reference for the user to figure out what values to input into the fields. Do I need: Custom field? Built-in field already? Modify the admin templates somehow? Add a helper function somewhere? I'm not referring to the "change list" view; I am referring to the /change/ or /add/ page view when you go and add or edit an object within a model. models.py class DateRange(models.Model): date_name = models.CharField(max_length=100) adwords_name = models.CharField(max_length=100) bingads_name = models.CharField(max_length=100) def __str__(self): return self.date_name forms.py class DateRangeAdminForm(forms.ModelForm): class Meta: model = DateRange fields = '__all__' admin.py @admin.register(DateRange) class DateRangeAdmin(admin.ModelAdmin): form = DateRangeAdminForm list_display = ['date_name', 'adwords_name', 'bingads_name'] -
Iterable object and Django StreamingHttpResponse
I want to connect to internal http services with django and I need to buffer the output the http response of those services because some contents are very large. I am using python 3.6, django 2.0, http.client and the following code: class HTTPStreamIterAndClose(): def __init__(self, conn, res, buffsize): self.conn = conn self.res = res self.buffsize = buffsize self.length = 1 bytes_length = int(res.getheader('Content-Length')) if buffsize < bytes_length: self.length = math.ceil(bytes_length/buffsize) def __iter__(self): return self def __next__(self): buff = self.res.read(self.buffsize) if buff is b'': self.res.close() self.conn.close() raise StopIteration else: return buff def __len__(self): return self.length def passthru_http_service(request, server, timeout, path): serv = HTTPService(server, timeout) res = serv.request(path) response = StreamingHttpResponse( HTTPStreamIterAndClose(serv.connection, res, 200), content_type='application/json' ) response['Content-Length'] = res.getheader('Content-Length') return response And the reponse is empty, I test the iterator with: b''.join(HTTPStreamIterAndClose(serv.connection, res, 200) And everything works fine, I don't know why is not working. -
Unable to load model keras [Django]
I'm developing a web app where the user uploads an image and then I predict it using my model which is saved in my hard disk. I'm not sure what is causing the error. Is it image-related? I get the following error: ValueError: Fetch argument <tf.Operation 'init' type=NoOp> cannot be interpreted as a Tensor. (Operation name: "init" op: "NoOp" input: "^dense_1/kernel/Assign" input: "^dense_1/bias/Assign" input: "^dense_2/kernel/Assign" input: "^dense_2/bias/Assign" input: "^dense_3/kernel/Assign" input: "^dense_3/bias/Assign" is not an element of this graph.) My Keras config file is: { "epsilon": 1e-07, "floatx": "float32", "image_data_format": "channels_last", "backend": "tensorflow" } My python code to load model is: model = load_model('my_model.h5') model.load_weights('my_model_weights.h5') -
Return dict indexed by primary key
I have a realy simple API Endpoint which return a list of MyModel. views.py: @api_view(['GET']) def index(request): myModel = MyModel.objects.all() serializer = MyModelSerializer(myModel, many=True) return Response(serializer.data) serializers.py class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ['field1', 'field2'] Now I'd like to return a serialized dictionary of models indexed by the primary key (which is a CharField). { 'pk1':{ 'field1': 'fo', 'field2': 'bar', }, 'pk2':{ 'field1': 'fobar', 'field2': 'foo', } } -
Using Django models in different projects
Simplified project(s) structure: -DatabaseController (Project1) -App -Models -ModelActions -SomeOtherProject (Project2) -Extensions -<symlink to Project1> -App -Views -Urls Structure explanation: I have some projects, that should not directly execute Django ORM code and query the database. For that i have a separate project, called DatabaseController which does various actions like "get all subscribers" or "get subscribers count" where these actions actually execute Django ORM against a databse. So if you want to get all subscribers for SomeOtherProject (Project2) you would simply have a reference to the DatabaseController (Project1) project and call an according action. Example: In DatabaseController (Project1): class SubscriberActions: @staticmethod def get_all_subscribers(): return Subscriber.objects.all() In SomeOtherProject (Project2): from SomeOtherProject.extensions.the_symlink_to_controller.app.model_actions\ .subscriber_actions import SubscriberActions result = SubscriberActions.get_subscribers() What goes wrong: I get this error: RuntimeError: Model class SomeOtherProject.extensions.the_symlink_to_controller.app.models.partner.Partner doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. (Yes, i have to models - subscibers and partners) What am i doing wrong? How do i fix this error related to models? -
Nested Relationship Serializer Rest Framework Not Displaying Properly
I'm trying to display the attributes in the Disease Model and Evidence Model, but the attributes that is displayed on the end link are only those attributes that are present in the Rule Model. Models.py :- class Rule(models.Model): disease = models.ForeignKey(Disease, default=0,related_name="DRules") evidence = models.ForeignKey(Evidence, default=0,related_name="ERules") measure_of_belief = models.PositiveIntegerField( \ help_text="The measure of belief (percentage) that a disease is present given this evidence exists", \ default=0,validators=[MinValueValidator(0), MaxValueValidator(100)]) measure_of_disbelief = models.PositiveIntegerField( \ help_text="The measure of disbelief (percentage) that a disease is present given an evidence does not exists", \ default=0,validators=[MinValueValidator(0), MaxValueValidator(100)]) archived = models.BooleanField(default=False) def __str__(self): return "{}-{}".format(self.disease, self.evidence) class Meta: verbose_name = "Rule" verbose_name_plural = "Rules" unique_together = ('disease', 'evidence',) class Disease(models.Model): """ The model where the category will be stored """ name = models.CharField(max_length=255) advise = models.CharField(max_length=500,blank=True) archived = models.BooleanField(default=False) def __str__(self): return self.name class Meta: verbose_name = "Disease" verbose_name_plural = "Diseases" class Evidence(models.Model): evidence_choices = { ("Observable Evidence", ("Observable Evidence")), ("Cause", ("Cause")) } name = models.CharField(max_length=255) question = models.CharField(max_length=500) evidence_type = models.CharField(choices = evidence_choices,max_length=20,default="Observable Evidences") archived = models.BooleanField(default=False) image_name = models.ImageField(upload_to='media/', default='media/None/no-img.jpg') def __str__(self): return self.name class Meta: verbose_name = "Evidence" verbose_name_plural = "Evidences" Serializers.py class DiseaseSerializer(serializers.ModelSerializer): class Meta: model = Disease fields = '__all__' class EvidenceSerializer(serializers.ModelSerializer): class … -
Handling Date and DateTime timezones
I have an API which has to do with transactions. Where Parent Transaction ( PT ) can have multiple Child Transactions. Both, in Parent and Child Transaction ( CT ) i store the date-time field to UTC.( i use Django's DateTime(auto_now_add=True ) But i need to clear some things out so here are my questions: I need to import transactions from a CSV file to my current API, where most of the transactions in the CSV are in local time zone and have only date (YYYY-MM-DD) how should i handle this ? Client selects from Date picker a date ( 2017-12-28 ) how should i search that in my API? cause i don't have a time, and timezone is different. -
What's a more efficient way to create a field-less form without a dummy forms.Form?
I'm trying to implement a form that simply presents data, and offers the user the choice of "Accept" or "Deny". I'm sending the data that I want to display by overriding the get_context_data() method, and I have two <input type="submit">'s on the template. Here is the view: class FriendResponseView(LoginRequiredMixin, FormView): form_class = FriendResponseForm template_name = 'user_profile/friend_response.html' success_url = '/' def get_context_data(self, **kwargs): context = super(FriendResponseView, self).get_context_data(**kwargs) context['respond_to_user'] = self.kwargs.get('username') responding_profile = Profile.objects.get( user__username=self.request.user) requesting_profile = Profile.objects.get( user__username=self.kwargs['username']) friend_object = Friend.objects.get(requester=requesting_profile, accepter=responding_profile) context['accepter_asks'] = friend_object.requester_asks return context def form_valid(self, form): super(PairResponseView, self).form_valid(form) if 'accept' in self.request.POST: # do something else: return redirect('/') Because the form does not accept any input or choices, I have this dummy form: class FriendResponseForm(forms.Form): pass There must be a more efficient, Django way to achieve the same result. How would I go about it? -
app.yaml is not pointing to the WSGI file properly in Django with Google App Engine
I have the following files structure: And shown below, is the part of the code of my app.yaml that's pointing to the wsgi of my project: handlers: - url: /static static_dir: static/ - url: .* script: testproject.wsgi.application Of course there are other files which I think is not necessary to be shown, such as the other apps. When I ran it in local, everything is working fine. But when I upload it to the cloud, it's not working and is showing a server error. I have been researching a lot but still no luck. Please help me. Thanks! -
Mapping two MEDIA_URLs to the same MEDIA_ROOT
I’m migrating a website from WordPress to Django/Wagtail. I have all the old WP content in my media directory & it’s all being served appropriately. It would be convenient to map other URLs (specifically /wp-content/) to MEDIA_ROOT, for the sake of old media URLs that were hardcoded in the content. So for example a migrated asset now available at //example.com/media/uploads/2017/12/IMG_2120.jpg can also be served from //example.com/wp-content/uploads/2017/12/IMG_2120.jpg I’m sure there’s some obvious way to do this (in urls.py?) but totally drawing a blank. -
Don't work cleaned_data in Django
This is my code: class HighschoolForm(forms.ModelForm): class Meta: model = Highschool fields = ['id', 'dni', 'name', 'address', 'city', 'country', 'phone', 'mobile', 'mail', 'website', 'contact', 'entrydate'] def clean_mail(self): mail = self.cleaned_data.get('mail') #self.cleaned_data['mail'] mail_base, proveedor = mail.split('@') dominio, extension = proveedor.split('.') if extension == 'ptn': raise forms.ValidationError('Does not allow Pluton mails....') return self.cleaned_data['mail'] However when I introduced data in ModelForm in the admin view a mail with a "ptn" extension, Django doesn't refused the data and record in the database. Which is the problem? I read de Django 2.0 documentation and I don't find the failure. Thanks -
Django tags/keywords based search
I'm learning Django to build a website with a search engine. I only found documentation for full text search. However, I'm trying to implement a keywords/tags based search that I add to each item. For example, if a user searches meat, all meat products like chicken, beef, ham, will pop up. Items can also have multiple keywords. So how do I implement something like that; is there a tool or app I can use? I would love a link to the documentation as well. -
Django check if Form is_valid()
I am trying to replicate if form.is_valid(): With the django form wizard. (this question shouldn't have anything to do with the wizard) I have this code: class ContactWizard(SessionWizardView): def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self, form_list, **kwargs): if self.request.method == 'POST': print(form_list) process_form_data(form_list) return HttpResponseRedirect('../home') def process_form_data(form_list): if form.is_valid(): form_data = [form.cleaned_data for form in form_list] first_name = form_data[0]['first_name'] last_name = form_data[0]['last_name'] email = form_data[0]['email'] fav_food = form_data[0]['fav_food'] fav_drink = form_data[0]['fav_drink'] user = User.objects.create_user(email) user.first_name = first_name user.last_name = last_name user.email = email user.save() user_addon = UserAddon.objects.create(user=user,fav_food=fav_food,fav_drink=fav_drink) user_addon.save() return form_data If i print out form_list i get this odict_values([<UserAddonForm bound=True, valid=True, fields=(fav_food;fav_drink;first_name,last_name;email)>,ContactForm3 bound=True, valid=True, fields=(info1;info2;message)>]) and if i try running it with just form.is_valid() i get Exception Value: name 'form' is not defined how can i get an equivalent of the form.is_valid() working? Thanks -
Django - Transforming Form data to REST API, POST request
Given an arbitrary html form, what is the fastest and smoothest way of transforming the entered data to a REST API JSON POST request to an arbitrary address? Are there any good libraries for this in Django? Thanks -
How do I write a file to temporary storage that I receive through django rest framework?
I have a view that accepts a file (.doc, docx, or pdf): from rest_framework.decorators import api_view from rest_framework.parsers import FileUploadParser @api_view(['POST']) @parser_classes((FileUploadParser,) ) def parse_document(request, format=None): file_obj = request.data['file'] I need to parse these documents and return json. I'm using Textract to convert the documents to text but in order for that to happen I need to pass a filepath to Textract, hence the reason I need to write the file temporarily to the file system. -
DJango Is this possible?
I'm new to Django and I'd just like to know if this is possible or if I should go about it another way. Maybe there is a library out there that I don't know about. I have a field in my User model that is pulled from AD which identifies a primary location. A User at creation can only have one, but after a submit is requested in a view they can have multiple by request. I'd like for them to be able to add this manually with a button. I.E. the view: UserID: ### Coid: ###### [+] Data is wrote to the database as: Coid, Coid added by Button pulled from a list of locations in a pre-existing database table/model called SecurityList. If a users request is approved the Coid will display as: UserID: ### Coid: ######, ######, etc.. If i'm going about it the wrong way please give me suggestions. -
Django channels with redis-server and nginx
I've been following this http://channels.readthedocs.io/en/latest/getting-started.html My current setup (before adding channels) was nginx, uwsgi, django. On my local, I'm running all this on a vagrant box which forwards port 5000 Django server currently runs on 0.0.0.0:5000 My nginx config listens on 8000 and serves static files It also has: location / { include uwsgi_params; uwsgi_pass unix:{{backend_uwsgi_socket}}; } While following the tutorial, everything works until I get to the point of changing my settings.py from CHANNEL_LAYERS = { "default": { "BACKEND": "asgiref.inmemory.ChannelLayer", "ROUTING": "myapp.routing.channel_routing", }, } to CHANNEL_LAYERS = { "default": { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { #"hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], #"hosts": [("redis-server-name", 6379)], "hosts": [("localhost", 6379)], }, "ROUTING": "myapp.routing.channel_routing", }, } So the tutorial says to install redis-server, then just run the command again:manage.py runserver 0.0.0.0:80000 If I turn off nginx, and run this it complains: ConnectionError: Error 111 connecting to localhost:6379. Connection refused. I tried adding a listener for this port in my nginx server block, then I get the below error: ^Cvagrant@vagrant-ubuntu-trusty-64:/srv/myproj/backend$ sudo python manage.py runserver 0.0.0.0:8000 Performing system checks... System check identified no issues (0 silenced). December 28, 2017 - 17:10:25 Django version 1.10, using settings 'backend.settings' Starting Channels development server at http://0.0.0.0:8000/ Channel layer default (asgi_redis.core.RedisChannelLayer) Quit the … -
TWO MODEL COUNT AGGREGATE IN LISTVIEW DJANGO
TWO MODELS TO JOIN TO COUNT A FIELD WITH GROUP BY CLAUSE i am not getting a correct result. count is coming but field2 key is coming but i need value not foreign key id views.py class QoutationListView(ListView): template_name = "ePROC/Acquisition/qoutation_list.html" model = QoutationModel context_object_name = 'qoutationlist' queryset = QoutationModel.objects.values('Field2','Field1').annotate(Count('Field3')) paginate_by = 10 def get_context_data(self, **kwargs): context = super(QoutationListView, self).get_context_data(**kwargs) context['range'] = range(context["paginator"].num_pages) return context SQL STATEMENT SELECT FIELD1,FIELD2,COUNT(FIELD3)AS COUNT FROM ABCTABLE A,ACCTABLE B WHERE A.FIELD2=B.FIELD1 GROUP BY FIELD1,FIELD2 EXPECTATION FIELD1 | FIELD2 | COUNT ----------------------- 1 | TABLE | 5 2 | CHAIR | 4 3 | LAPTOP | 3 4 | SOFA | 2 FIELD 2 IS FOREIGN KEY IN ABCTABLE -
Google AppEngine Django memcache "CACHES" setting
I haven't been able to find the correct settings for Django "CACHES" setting in order to use Google AppEngine's memcache. After looking at djangoappengine (https://github.com/django-nonrel/djangoappengine/blob/master/djangoappengine/settings_base.py), I have tried: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', } I have vendored python-memcached==1.59 into lib. There are no errors in the logs and app renders views correctly. But the views are not being cached, as evidenced by debug logs. And gcloud console appengine memcache stats show that caching is not in effect: Items in cache: 0 Total cache size: 0 I have set the middleware correctly and confirmed correct operation in a non-AppEngine environment with a local memcache server. What is the correct BACKEND setting to use AppEngine standard environment memcache for Django applications? -
Python - How to add two model fields in models.py in Django
I have a class in my models.py class Inventory(models.Model): date = models.DateField(("Date"), default=datetime.now) product = models.ForeignKey(Product) stock_in = models.IntegerField() stock_out = models.IntegerField() balance = models.IntegerField() particulars = models.CharField(max_length=250) Now I want to add some stocks in the balance. Using the stock_in values to add certain numbers to the balance of a specific product in the Inventory class. Using an UpdateView to it, so that I can just Update the stock_in field then adding that value to the balance. I'm currently using this, I've tried couple of solution in the internet but to no avail. @property def total(self): return self.stock_in + self.balance -
django TypeError: coercing to Unicode: need string or buffer, list found
I am getting this error "TypeError: coercing to Unicode: need string or buffer, list found" when I run the command python manage.py collectstatic. Please solve this issue settings.py `STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static-pro"), '/var/www/static/', ] STATIC_ROOT =[ os.path.join((BASE_DIR), "static_cdn","static_root"), ] MEDIA_URL = '/media/' MEDIA_ROOT =[ os.path.join(os.path.dirname(BASE_DIR), "static_cdn","media_root"), ] -
Django oracle db settings
I just want to connect my local oracle db with my django project but my database credential is not working. Actually, I'm able to connect my oracle database via sql developer with that credential: I just used that credential in django settings_py like that DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'INTERNAL', 'USER': 'system', 'PASSWORD': 'oracle', 'HOST':'localhost/xe', 'PORT':'1521' } } and error is: Traceback (most recent call last): web_1 | File "manage.py", line 22, in <module> web_1 | execute_from_command_line(sys.argv) web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line web_1 | utility.execute() web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute web_1 | self.fetch_command(subcommand).run_from_argv(self.argv) web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv web_1 | self.execute(*args, **cmd_options) web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute web_1 | output = self.handle(*args, **options) web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 110, in handle web_1 | loader.check_consistent_history(connection) web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 282, in check_consistent_history web_1 | applied = recorder.applied_migrations() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations web_1 | self.ensure_schema() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema web_1 | if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 254, in cursor web_1 | return self._cursor() web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 229, in _cursor web_1 | self.ensure_connection() … -
Should I learn Django or Java for SPA BE
I have finally decided to learn some backend technology. I found that Django framework should be quite a good fit since you should be able to deliver fully functional app quickly, so I watched some tutorials and gave it a shot. But honestly, I was quite sad to find that it probably isn't SPA ready, the whole FE and BE is kind of mixed together and in order to use REST you have to use another stuff (Django REST framework is recommended), but I don't want to be using a 3rd party framework for such a crucial part of the app, which might be discontinued or something like that. So for me, given the fact, that I use Angular to develop FE (and I want to keep it that way), I got an impression, that Django is not the way to go. I was also considering Java for BE but didn't go that way, because I thought that it would take ages to actually create something. But now, I am 90% sure that using the robust Java is the technology to choose. But I don't want to give up on Python for several reasons (current market use is one of …