Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Cannot import user in Django 1.9
I'm using Django 1.9 and following along on this tutorial: https://www.youtube.com/watch?v=6WkQOlYgkHM&index=15&list=PLEsfXFp6DpzQFqfCur9CJ4QnKQTVXUsRy When I put in the following code as recommended: def post_list(request): # return HttpResponse("<h1>Update</h1>") if request.user.is_authenticated(): context = { "title": "My User List" } else: context = { "title": "List" } return render(request, "index.html", context) I get the following error message: AttributeError: 'WSGIRequest' object has no attribute 'user' I looked up the documentation and tried doing this: from django.contrib.auth.models import user But user is underlined on my pycharm and now the error message I'm getting is ImportError: cannot import name 'user' -
Custom User model fields (AbstractUser) not showing in django admin
I have extended User model for django, using AbstractUser method. The problem is, my custom fields do not show in django admin panel. My models.py: from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_bot_flag = models.BooleanField(default=False) My admin.py: from django.contrib.auth.admin import UserAdmin from .models import User admin.site.register(User, UserAdmin) Thanks -
Django Rest Framework - Give Serializer of default User model validations that mimic the default validations
I am currently making a REST API that people can register themselves via. And I am just about to write the validations for how long/complex passwords should be etc. when it occurred to me there maybe is a way to mimic the default constraints that the model have set already? Is there? My code for serializer.py looks like the following: from rest_framework import serializers from django.contrib.auth import get_user_model from rest_framework.reverse import reverse User = get_user_model() class UserSerializer(serializers.ModelSerializer): links = serializers.SerializerMethodField() class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name', 'email', 'password', 'groups', 'user_permissions', 'is_staff', 'is_active', 'is_superuser', 'last_login', 'date_joined', 'links') def get_links(self, obj): request = self.context['request'] username = obj.get_username() return{ 'self': reverse('user-detail', kwargs={User.USERNAME_FIELD: username}, request=request) } def validate(self, attrs): #... Thanks -
Showing auth. errors in Django in HTML
I'm new in Django. I have custom HTML form for login and sign up, so when i input wrong username or password my page just reloads. How can I put messages into HTML printing "wrong password" or "wrong username"? Thanks! -
Two mutually exclusive many-to-many relations
Imagine an online shop. You have goods. Some goods have size, some don't. I've got an orders table id int not null, ... orders_products table order_id int not null, product_id int null, product_size_id int null, ... products table id int not null, ... product_sizes table id int not null, product_id int not null, ... Right now either product_id or product_size_id is not null. In other words, primary key is order_id + (product_id || product_size_id). Not both. In Django's terms that would be: class OrderProduct(models.Model): product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE) product_size = models.ForeignKey(ProductSize, null=True, on_delete=models.CASCADE) order = models.ForeignKey('Order', on_delete=models.CASCADE) amount = models.PositiveSmallIntegerField() class Order(models.Model): products = models.ManyToManyField(Product, through=OrderProduct, related_name='orders') product_sizes = models.ManyToManyField(ProductSize, through=OrderProduct, related_name='orders') ... At least that's what I have right now. But I don't like having two mutually exclusive foreign keys in orders_products table. Or two attributes in Order model. One of which (product_sizes) is probably redundant. So, I probably have to remove product_sizes attribute from the Order model. Is that it? Or should I make product_id not null in orders_products table? And have product_size_id only when the product comes in different sizes? Any other suggestions? I've marked the question with django, python, postgresql tags. But I'm not stuck …