Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter ModelChoiceField by model field in Django Admin Form
I have two models: class Room(models.Model): number = models.PositiveIntegerField(primary_key=True) places = models.PositiveIntegerField() price_per_night = models.PositiveIntegerField() class Order(models.Model): places = models.PositiveIntegerField() moving_in = models.DateField('moving in date') moving_out = models.DateField('moving out date') room = models.ForeignKey(Room, on_delete=models.CASCADE, blank=True, null=True) and custom form to view Order in admin page: class OrderAdmin(admin.ModelAdmin): readonly_fields = ('places', 'moving_in', 'moving_out') form = OrderAdminForm class CustomModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return "Room number: %s | Class: %s | Price per night: %s" % (obj.number, obj.places,obj.price_per_night) class OrderAdminForm(forms.ModelForm): room = CustomModelChoiceField(queryset=Room.objects.filter(places=????)) class Meta: model = Order fields = '__all__' The problem is in string: room = CustomModelChoiceField(queryset=Room.objects.filter(places=???)) The question is how to filter rooms by number of places in field 'places' of Order model. -
Applying class method to queryset in Django
I am new to advanced concepts of Django, and I find myself a bit confused about the application of concepts such as custom methods. Basically, my goal is best descriped by this short example. I have two classes, namely vendor and order. Each order has a vendor. The models look like this: class Order(models.Model): vendor_agreement = models.ForeignKey(VendorAgreement, on_delete = models.CASCADE) @property def get_vendor_agreement(self): .... return result As you see, I have all the business logic between an order and vendor_agreement encapsulated in the get_vendor_agreement method. The question Is there any elegant way to get the list of distinct vendor_agreements that correspond to order queryset ? I mean, something like Order.objects.filter(...).vendor_agreement(), which would return a list of distinct vendor agreements. Thank you in advance. -
How to reflect the result from a function into a HTML table Django
I have this view function that filters the objects of a model by date (range 5 days ignoring Saturday/Sunday) and counts a certain item from a column. I need to know how to reflect the results instead of print in them in console I want them on a html as a table, any ideas? This is what I got: Views.py def dashboard(request): week = {0, 1, 2, 3, 4} deltaday = timedelta(days=1) today_date = datetime.now().date() day = today_date for i in range(7): if day.weekday() in week: orders = Shipment.objects.filter(current_fcd_date=day) #this is the date will be filter from range hold = orders.filter(ctb_comments__contains="HOLD").count() # this is the element that will count to get the number every day ignoring weekends print(day.strftime(("%d/%m/%y --- %A --- Holds: "))) + str(hold) # with this I will get in console the result day += deltaday return HttpResponse(request) This is the result I get from console that i want to be reflected in a html view in the webapp: models.py: class Shipment(models.Model): sales_order = models.CharField(max_length=40) po_num = models.CharField(max_length=35) df_status = models.CharField(max_length=45) ctb_comments = models.CharField(max_length=400) current_fcd_date = models.DateField(null=True, blank=True) and this is the prototype from the table with fake data(I do have the html code if is needed): Thanks … -
django ORM - order by status value
I have a model with three statuses: draft, launching, launched. What I want is to display models in a particular order: first drafts, then launching ones, and then launched ones. I don't want to name my attributes as 0_draft, 1_launching, 2_launched as this will be a problem down the road; i need clear values in my DB. Is there a way to annotate these values with some integers? The ideal syntax for this would look like this: def detect_status_number(campaign): if campaign.status == 'draft': return 1 ... etc ... cs = Campaign.objects.annotate(new_arg=lambda campaign: detect_status_number(campaign)) cs = cs.order_by('new_arg').all() this obviously doesn't work; but is there a way to make this work? -
is_valid() returns false on nested serializers
The code Serializers.py: class ActivitySerializer(serializers.ModelSerializer): class Meta: model = Activity class RouteOrderingSerializer(serializers.ModelSerializer): activity = ActivitySerializer() class Meta: model = RouteOrdering fields = ('id','activity','day','order','route','activity') def create(self, validated_data): routeordering = RouteOrdering.objects.create(**validated_data) return routeordering a create func: def make(data): serializer = RouteOrderingSerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() The problem For some reason, because of the writable nested serializer, the serializer.is_valid() function finds the passed data as not valid and does not let me save the instance. I have tried also to skip the is_valid() function but of course it is not allowed by the rest framework. The data is on the currect format, and the ORM should accept it. Any help will be appriciated :) -
DJANGO-PYODBC problems at runserver
i'm testing django project to connect a Sql Server database via ODBC. i have some problems when I try doing runserver of my project the installed components are: python 2.7 django 1.10.2 django-pyodbc 0.4.4 the first error was File "C:\Python27\lib\site-packages\django_pyodbc\introspection.py", line 90, in get_table_list return [TableInfo(row[0].lower(), row[1]) for row in cursor.fetchall()] NameError: global name 'TableInfo' is not defined i tryied to correct ..\django-pyodbc\introspective.py with try: from django.db.backends.base.introspection import ( BaseDatabaseIntrospection, FieldInfo, TableInfo, ) instead of try: from django.db.backends.base.introspection import BaseDatabaseIntrospection but i had the second error File "C:\Python27\lib\site-packages\django\db\backends\base\base.py", line 604 , in schema_editor 'The SchemaEditorClass attribute of this database wrapper is still None') NotImplementedError: The SchemaEditorClass attribute of this database wrapper is still None I don't know how to proceed. -
Django & D3 - Best way to link csv files to front-end
I am using Python Django to create an interactive Dashboard. The main reason why I decided to use Django is because I can create users and groups to give different access to different people. Thought this was the better way. I have massive reports built on excel sheets that I can convert to .CSV and machine readable. I read the best way to load data to D3 is through d3.csv(). I've tried that without success and now have tried with d3.json() but still I have used another code sample to try and plot my own but could have any luck. The code is as follows. Important note: In dashboard.html, there is a selector, thus the HTML Template has that extends the "dashboard" template. # app/models.py from django.db import models class wrtes(models.Model): name = models.CharField(max_length=150) date = models.DateTimeField() # app/urls.py from django.conf.urls import url from . import views from .views import graph, oneModel urlpatterns = [ # Dashboard parts url(r'^oneModel/', graph), url(r'^api/oneModel', oneModel, name='oneModel'), ] # app/views.py def graph(request): return render(request, 'app/oneModel.html') def oneModel(request): data = oneModel.objects.all() \ .extra(select={'month': connections[oneModel.objects.db].ops.date.trunc_sql('month', 'date')}) \ .values('month') \ .annotate(count_items=Count('id')) <!-- app/oneModel.html --> {% extends 'app/dashboard.html' %} {% load staticfiles %} {% block content %} <script … -
django mezzanine can't style inputs
I'm using mezzanine for my blog and I want to style the inputs width 100% width and and add a placeholder. But can't figure out how to do this. The inputs are generated with the below code: {% if not request.POST.replied_to %} {% fields_for posted_comment_form %} {% else %} {% fields_for unposted_comment_form %} {% endif %} which outputs: <div class="form-group input_id_name"> <label class="control-label" for="id_name">Name</label> <input id="id_name" maxlength="50" name="name" type="text" value="simon" class="input-xlarge"> <p class="help-block">required</p> </div> Is there a way to apply changes to this input without overriding the backend code? I tried to apply css to #id_name or .form-group but it will not go 100% wide.. I guess because of the class .input-xlarge. How can I remove this class from the input? Or where is this class being generated to the input field? Also want to add a placeholder -
django access database from crispy form
I'm working on a blog for a client that is using crispy form to make their writing's easier. I have the ability to add an image to the blog - only one and at the top of the post. My client wants to add other pictures throughout the post. The crispy form allows them to do this but only by way of a full http link. This means they would have to understand how the admin of the site works to be able to find the pic they want and use it here. Is there a way to have them be able to find the picture from the database and use that pictures url right on this screen? Here is a screenshot of what I mean: -
ERROR __init__() takes exactly 1 argument (3 given) on Django with GAE
Im trying to solve one problem that I have on my admin of one Django App. I have this code: admin_main.py: application = webapp.WSGIApplication([ # Admin pages (r'^(/admin/add_img)', admin.views.AddImage), (r'^(/admin)(.*)$', admin.Admin),]) admin/views.py: class BaseRequestHandler(webapp.RequestHandler): def handle_exception(self, exception, debug_mode): logging.warning("Exception catched: %r" % exception) if isinstance(exception, Http404) or isinstance(exception, Http500): self.error(exception.code) path = os.path.join(ADMIN_TEMPLATE_DIR, str(exception.code) + ".html") self.response.out.write(template.render(path, {'errorpage': True})) else: super(BaseRequestHandler, self).handle_exception(exception, debug_mode) class Admin(BaseRequestHandler): def __init__(self, request,response): logging.info("NEW Admin object created") super(Admin, request, response).__init__() # Define and compile regexps for Admin site URL scheme. # Every URL will be mapped to appropriate method of this # class that handles all requests of particular HTTP message # type (GET or POST). self.getRegexps = [ [r'^/?$', self.index_get], [r'^/([^/]+)/list/$', self.list_get], [r'^/([^/]+)/new/$', self.new_get], [r'^/([^/]+)/edit/([^/]+)/$', self.edit_get], [r'^/([^/]+)/delete/([^/]+)/$', self.delete_get], [r'^/([^/]+)/get_blob_contents/([^/]+)/([^/]+)/$', self.get_blob_contents], ] self.postRegexps = [ [r'^/([^/]+)/new/$', self.new_post], [r'^/([^/]+)/edit/([^/]+)/$', self.edit_post], ] self._compileRegexps(self.getRegexps) self._compileRegexps(self.postRegexps) # Store ordered list of registered data models. self.models = model_register._modelRegister.keys() self.models.sort() # This variable is set by get and port methods and used later # for constructing new admin urls. self.urlPrefix = '' def index_get(self): """Show admin start page """ path = os.path.join(ADMIN_TEMPLATE_DIR, 'index.html') self.response.out.write(template.render(path, { 'models': self.models, 'urlPrefix': self.urlPrefix, })) And when I try to get the page http://localhost:8080/admin, I get … -
Django: regx to identify hashtag
I have a sentence 'this is #classic point' I want convert hashtag wordsi.e. #classic into link so that people can click on it and proceed next. like twitter hashtags I want to use regular expression to identify such pattern and replace it with link. Need help. -
Django 'ascii' codec can't encode character u'\uff1f'
I am still beginner in django. When I save into database, I got this error. 'ascii' codec can't encode character u'\uff1f' in position 14: ordinal not in range(128) I have seen similar question here though but I have tried and it is still not okay. UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128) I believe it happen in this data['english']. Shall I change in views.py or serializer? My view is class DialogueView(APIView): permission_classes = (IsAuthenticated,) def post(self, request): data = request.data serializer = DialogueSerializer(data=request.data) if not serializer.is_valid(): return Response(serializer.errors, status= status.HTTP_400_BAD_REQUEST) else: owner = request.user t = Dialogue(owner=owner, english=data['english']) t.save() # request.data['id'] = t.pk # return id return Response(status=status.HTTP_201_CREATED) My serializer is class DialogueSerializer(serializers.ModelSerializer): sound_url = serializers.SerializerMethodField() class Meta: model = Dialogue fields = ('id','english','myanmar', 'sound_url') def get_sound_url(self, dialogue): if not dialogue.sound: return None request = self.context.get('request') sound_url = dialogue.sound.url return request.build_absolute_uri(sound_url) -
Complex conditional ordering in a query
Okay, so there are two models - Event and Like. Event model has "business" field which links to the certain Business object, which further has "manager" field. Also, Event model has "when" field which describes the date when an event will occur. On the other side, Like model has "event" field which links to the certain Event object, and also "person" and "date" fields which describe who gave like and when it was given to that event. The goal is now to display on user page all liked events by targeted user, and all business events which manager is that user. It can be simply done with this SQL command: SELECT * FROM event INNER JOIN business ON (event.business_id = business.id) WHERE ((event.id IN (SELECT event_id FROM like WHERE person_id = 1)) OR business.manager_id = 1) But, there comes a problem when that results have to be sorted, by already mentioned "date" in Like model and "when" in Event model. The sorting behavior should be as follows: If the Event object derives from Like object then it should be sorted by "date" in that Like object, in other case it should be sorted by "when" in Event. I think that … -
Disable edit object field(row) in admin panel for creator of this object
in admin i want to disable modifying one field for creator of this object, but it must be editable for other users. class Toys(BaseModel): name = models.CharField(max_length=255) tags = models.ManyToManyField(Tag, related_name='Item_tags') price = models.CharField(max_length=255) status = models.BooleanField(default=False) in my example this field is status, how can i customise admin.py to make this field noneditable for creator of this object and editable for other ordinary users? -
Field is required on POST requets with GeoFeatureModelSerializer and ListCreateAPIView
it was hard to find a good title for this thread. I'm developping webservices with django, geodjango (postgis), django-rest-framework and rest_framework_gis. Those webservices will be used in interactive maps. One of my model is the following: class Polygon(models.Model): fk_owner = models.ForeignKey(User, on_delete=models.DO_NOTHING) # the owner of this polygon (User) external_id = models.CharField(max_length=25) # id in data warehouse func_type = models.CharField(max_length=15) # e.g 'field', 'building', ... coordinates = models.PolygonField() properties = JSONField(default={}) # JSON containing attributes and actions The serializer of this model: class PolygonSerializer(GeoFeatureModelSerializer): class Meta: model = Polygon geo_field = "coordinates" fields = ('external_id', 'fk_owner', 'func_type', 'properties') And the endpoint class FieldList(generics.ListCreateAPIView): serializer_class = PolygonSerializer lookup_field = 'external_id' lookup_url_kwarg = 'external_id_field' def get_queryset(self): id_user = User.objects.get(external_id=self.kwargs['external_id_user']).id queryset = Polygon.objects.filter(func_type="field").filter(fk_owner=id_user).all() return queryset def perform_create(self, serializer): user = User.objects.get(external_id=self.kwargs['external_id_user']) serializer.save(fk_owner=user) When I use the following curl request: curl -X POST http://xxx.yyy.zzz/api/v2/users/aZ523AsZm/fields/ -d '{"external_id": "aE15feg64AzaP", "func_type": "field", "coordinates": "POLYGON((62780.8532226825 5415035.177460473, 62941.3759284064 5415283.89540161, 63187.058044587146 5415364.391565912, 63257.96856022246 5414992.852982632, 62780.8532226825 5415035.177460473, 62780.8532226825 5415035.177460473))", "properties": {"a": "b"}}' -H "Content-Type: application/json" I get {"fk_owner":["This field is required."],"external_id":["This field is required."],"coordinates":["This field is required."],"func_type":["This field is required."]} However, when I replace GeoFeatureModelSerializer by a simple ModelSerializer, eveything is fine. Why ? It took me like 1 hour to … -
Django multi database and permission
I would like to make a Django site with two databases with the same model. One for "group1" and another for "group2". A user of the 'group1' can read and write on the database1 and never see database2 and vice-versa. I am thinking of something like this. Is it the good practice ? class groupRouter(object): def db_for_read(self, model, **hints): if "group1" in request.user.groups.all(): return 'db1' else return 'db2' def db_for_write(self, model, **hints): if "group1" in request.user.groups.all(): return 'db1' else return 'db2' Regard -
PyMySQL Python 3 Django VirtualEnv MySQLdb
So I had this running yesterday when I was running the virtualenv out of my home directory. I've ran in to this problem a number of times now without a clear answer. I've done a lot of research on this but there seems to be no black and white answer. Today I moved my virtualenv to /usr/local/virtualenvs to better manage my projects and viola, it's broken again. Error loading MySQLdb module: No module named 'MySQLdb' is the bane of my existence right now. I can't seem to fix it this time. I have even tried duplicating what I did back into my home directory and have the very same problem. I haven't deleted any packages from my system. I installed the very same packages in the virtualenv. At this point I'm lost. I've even written down the steps I took from a fresh install to get to a working virtualenv. I certainly don't want to go back to a fresh install. Please help :) Virtual Environment: Ubuntu Server 16.04 LTS python 3.5 django 1.10.2 pymysql 0.7.9 Thanks in advance. -
How to inject Django template code into template through variable?
I have a model Reservation which I use in many templates. It's handy to create it's own HTML/Django snippet which is being injected into the template through variable/model method. The raw HTML is correct using the method but Django template language isn't interpreted correctly. This is a Reservation method: def get_html_description(self): return """<ul> <li><b>ID:</b> {{ reservation.id }}</li> <hr> <li><b>From:</b> {{ reservation.get_text_destination_from }}</li> <li><b>To:</b> {{ reservation.get_text_destination_to }}</li> <hr> <li><b>Date:</b> {{ reservation.get_date }}</li> <li><b>Time:</b> {{ reservation.get_time }}</li> </ul>""" Now I'm trying to inject this code into the template: <div class="events"> {% for reservation in data.1 %} <div class="event"> <h4>{{ reservation.get_text_destination_from }} to {{ reservation.get_text_destination_to }}</h4> <div class="desc"> {% autoescape off %}{{ reservation.get_html_description }}{% endautoescape %} </div>... ... Unfortunately it renders something like this: Do you know what to do? I've already tried filter |safe and {% autoescape off %} -
Email log error Django on Elastic Beanstalk
Since I migrate my django application on elastic beanstalk I no longer receive any error log email. I am using amazon Simple Email Service to send email. What should I set to receive this kind of email? -
Django Admin Console giving 'str' object has no attribute '__iter__' error
I am trying to make some changes in the fields using Djangos build in Admin console.It gives me 'str' object has no attribute 'iter' error exception when i try to change some fields in the models.These fields are Foreign Keys PROJECT MODEL CAUSES ERROR WHEN I CHANGE THE MANAGER FIELD class Project(models.Model): """Project Model. """ name = models.CharField(unique=True, max_length=255) manager = models.ForeignKey('Employee', blank=True, null=True) project = models.Manager() class Employee(models.Model): """ Employee Model. """ first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.CharField( unique=True, max_length=255, blank=True, null=True) projects = models.ManyToManyField('Project', blank=True) employee = models.Manager() TRACEBACK Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in wrapper 544. return self.admin_site.admin_view(view)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py" in inner 211. return view(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in change_view 1512. return self.changeform_view(request, object_id, form_url, extra_context) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func 63. … -
store user-specific api sessions python in sql db
Using a python package that makes use of pythons request.Session() object. The api is context sensitive so I'd like to store necessary session variables in the db. Using djangos ORM. Is it possible for me to store the entire session object as raw bytes and recall the session based on the user.pk or would it make more sense to store important session variables Thanks!! -
How to save/create rejected data file with vertica copy command using python 3.x
I am copying data from csv file to vertica table using following python code: with open("D:/SampleCSVFile_2kb/SampleCSVFile_2kb.csv", "rb") as fs: my_file = fs.read().decode('utf-8','ignore') cur.copy( "COPY STG.unstruc_data FROM STDIN PARSER FDELIMITEDPARSER (delimiter=',', header='false') ", my_file) This is working fine, but i want to save rejected data too so i used this query instead to save rejected data. COPY STG.unstruc_data FROM STDIN PARSER FDELIMITEDPARSER (delimiter=',', header='false') exceptions 'except.csv' rejected data 'reject.csv'; This copying data in vertica table but does not create file for rejected data. Is this possible to create csv file for rejected data from python? If yes then how this can be done. Thanks for help in advance -:) -
Django: accessing a table via dict-like interface
So I have situation in Django where I have a model called S which can have a series of attributes, but I have no idea currently what attributes will be relevant/required. In order to handle this I am thinking of creating a additional model SAttrib which mimics a dictionary entry and accessing it via a metadata property. See below. class S(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=128, blank=True, null=True) description = models.CharField(max_length=128, blank=True, null=True) created_date = models.DateTimeField(auto_now_add=True, auto_now=False) modified_date = models.DateTimeField(auto_now_add=False, auto_now=True) def __unicode__(self): return smart_unicode(self.name) class Meta: db_table = "stest" def _get_metadata(self): class AD(dict): def __init__(self, id): self.id = id def __getitem__(self, key): return SampleAttrib.objects.filter(sample_id=self.id, attrib_key=key).get().attrib_value return AD(self.id) metadata = property(_get_metadata) class SAttrib(models.Model): s_id = models.ForeignKey("S") attrib_key = models.CharField(max_length=128) attrib_value = models.TextField() class Meta: db_table = 's_attrib' unique_together = (('s_id', 'attrib_key'),) I would like to make it so that I have access the attributes stored in SAttrib via implementing it as a property. So I would be able to access values like so: y = S.objects.get() y.metadata["foo"] But then it becomes a mess and requires a lot of additional code for setting and saving objects / contains etc. s = S.objects.get() s.metadata["foo"] = "spam" ..... Is there a better … -
Not Found: /static/admin/css/base.css
My site is deployed on Heroku. Everything is going good except static files. Static files are there on this path doctor_app/doctor_app/static/. Locally, Admin panel for django is working perfectly. But on heroku, It doesn't find any static files. Surprisingly when i run this command with terminal. heroku run cat doctor_app/static/admin/css/base.css It outputs the content of base.css. which means static files are there I wonder why django is not finding any files ? -
Get a default value for null ForeignKey in Django
How can I get a default value for null ForeignKey in Django. For ex: class Owner(models.Model) name = models.CharField(max_length=200, unique=True) class Entity(models.Model): name = models.CharField(max_length=200, unique=True) owner = models.ForeignKey(Owner) I am using DRF, so I tried this serializer: class EntitySerializer(serializers.ModelSerializer): owner = serializers.SerializerMethodField(read_only=True) def get_owner(self, obj): if obj.owner: return obj.owner_id return -1 class Meta: model = Entity fields = ('id', 'name', 'owner') This works if I change the key owner to owner_id or something else. But I cannot do it as it has dependencies elsewhere.