Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
mkproject -t django creates empty directory not a django project
I am just learning how to use virtualenvwrapper and after going through the documentation I found that the mkproject command can create a new virtualenv and a new project. The documentation also suggests that using a -t flag followed by template name would create a project. So I thought this should create a django project: mkproject -t django todolist But when I go to my PROJECT_HOME, all I see is an empty directory called todolist, which was expected to be a django project. I am confused. Is this even possible? Because mkproject command creates a brand new virtual environment where django is not installed. So how could it attempt to create a django project? Please help me understand this. -
DRF: include read_only field in validated_data
Similar to using read_only=True with a default=... on a date field, I'd like to have a model's id field not editable by the user but included in the serializer's validated_data. How would this be achieved? -
Referring from the field of the object to the fields of several other objects
I have a question. How will it go from the start_point and end_point of the Pipeline model to the 3 objects (Factory, OilSump, OilStorage) to the address fields? class Factory(models.Model): title = models.CharField(max_length=200) address = YmapCoord(max_length=200, start_query=u'Россия', size_width=500, size_height=500, unique = True) def __str__(self): return self.title class OilSump(models.Model): title = models.CharField(max_length=200) address = YmapCoord(max_length=200, start_query=u'Россия', size_width=500, size_height=500, unique = True) def __str__(self): return self.title class OilStorage(models.Model): title = models.CharField(max_length=200) address = YmapCoord(max_length=200, start_query=u'Россия', size_width=500, size_height=500, unique = True) def __str__(self): return self.title class Pipeline(models.Model): title = models.CharField(max_length=200) start_point = ???? end_point = ???? -
Django; Is there way to pass parameters from view to js?
I'm not familiar with js at all. I've been working on Django project and I am wondering if there's a way to pass parameter from views.py to js. What I'm creating is upvote function. I want to upvote or downvote depending on whether the user alredy upvoted or not but I'm wondering how I can tell js that. js is like this function upvote(entry) { var $entry = $(entry) //If the user already upvoted, //If not, //select the score and update the score on html var id = $entry.data('id') $.ajax({ url:'/blog/upvote/' + id, method: 'POST', beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRFToken', csrf_token) } }) } html is like this <a href="" onclick="upvote(this)" data-id="{{ post.id }}">Upvote</a> models.py is like this class Entry(Model): ... upvoted = models.ManyToManyField( User, related_name='upvoted', blank=True, ) I want to call functions differently in js depending on whether the user is already associated with the Entry. Is there a preferable way to do this? -
./manage.py runserver with https
./manage.py runserver 0.0.0.0:8000 I am using the line above as part of the code I borrowed from github (https://github.com/ribeiroit/boh-puppet) to run bag of holding installation. So far so good on http but not https. How do I modify the line above to incorporate https? I have already obtained ssl certificate from Comodo and updated my nginx conf.d file but the website won't display in https. Any ideas please shoot my way. Thank you -
Django - child template extended CSS from parent template but fail to use its CSS
The home.html was successfully extended from base.html. However I found that the child template is not making use of its own CSS. I guess it's because the base.html doesn't have a {% block %} tag to allow the children templates to override the CSS. I have no idea where to add the {% block %} tag in base.html. If I just add {% block head %} in base.html, the home.html will not use the CSS from base.html. book/templates/base.html: <head> {% load static %} <title>BookStore</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> <link id="cssFile" rel="stylesheet" type="text/css" href="{% static 'book/master.css' %}"> </head> book/templates/book/home.html: <head> {% block head%} <style> #homePageBooks { /*width: 160%;*/ width: 100%; position: relative; left: 210px; /*margin-left: 100px;;*/ /*margin-right: 100px;*/ margin-top: 60px; } .row1, .row2, .row3 { font-size: 12px; float: left; width: 200px; height: 120px; margin-left: 60px; margin-right: 60px; margin-bottom: 100px; text-align: center; } .bookImg { margin-bottom: 6px; } </style> {% endblock %} </head> -
How do I integrate QUnit with Django and require files under test?
I have a Django 1.11 project and I would like to use QUnit. I would like to call QUnit at the command line. Note the HTML runner. I have the whole setup correctly, but when it comes to testing actual JavaScript units from my Django project, I am stuck. My tests reside inside js_files/**/*_test.js files. How do I load my static files that need testing? My static files reside inside the Django app subfolders (e.g. <app-name>/static/js/**/*.js). -
How to Customise Social Account model in django-allauth
I want to add some additional field to SocialAccount model in allauth.socialaccount.models Not able to find anything in the official documentation. -
Subscription based solution that deals with features
What's the best way to deal with features and quota based subscriptions? Let me explain. For instance lets imagine there are different plans one could subscribe to but each plan has features which other plans might not have. Also each plan has a monthly quota. Using Python (django) what's the best way check whether a customer, which has a subscription, his/her sub has a particular feature or not? I am not sure how to implement this and was wondering whether there are examples out there I could check out to get more firm understanding. -
Django REST framework RetrieveAPIView gets empty "id" parameter and returns 404 error
I use Django 1.11 + Django REST Framework. I'm trying to get detailed data about distinct record using generic RetrieveAPIView from Django REST Framework and server returns "HTTP 404 Not Found" result, i.e. no data. models.py file: class TestPage( models.Model): title = models.CharField( size = 120) counter = models.IntegerField( default = 0) def __unicode__(self): return u'' + self.title serializers.py file: class TestPageSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'title', 'counter',) model = models.TestPage urls.py file: urlpatterns = [ url( r'^admin/', admin.site.urls), url( r'^api/', include( 'rest_framework.urls')), url( r'^api/', include( 'testpages.urls')), ] testpages/urls.py file: urlpatterns = [ url( r'^$', views.TestPageList.as_view()), url( r'^(?P<id>)\d+/$', views.TestPageDetail.as_view()), ] and at last views.py file: class TestPageList(generics.ListAPIView): lookup_field = 'id' queryset = TestPage.objects.all() serializer_class = TestPageSerializer class TestPageDetail(generics.RetrieveAPIView): lookup_field = 'id' queryset = TestPage.objects.all() serializer_class = TestPageSerializer # def get_object( self): # print self.kwargs If I request "http://127.0.0.1:8000/api/" for all records in the list, server returns all records. But if I want to get record by id using "http://127.0.0.1:8000/api/1/" for example, I get the empty result like in the photo below. [![enter image description here][1]][1] If I uncomment get_object()-function in last 2 lines, I can see {'id': u''} in terminal i.e. server gets empty parameter 'id'. What wrong with … -
chain href actions on html django
Noob here. I would like to know how to chain two actions using href. So basically I have a javascript action and additionally I would like to make a link to an other page. <div Id="topnav"> <a class="active" href="javascript:void(0)" "{% url 'Home' %}">Home</a> <a href="javascript:void(0)">News</a> <a href="javascript:void(0)">Contact</a> <a href="javascript:void(0)">About</a> </div> The <a class="active" href="javascript:void(0)" "{% url 'Home' %}">Home</a> does not work. I tryed <a class="active" href="javascript:void(0);{% url 'Home' %}">Home</a> as suggested on another link but it did not work. First it would be good to know if it is possible and if it is, how to do it. -
Check if Redis is down
I'm using Celery with Django. If Redis is down Celery hangs indefinitely, it is a known bug in Celery. An off course I don't want to hang and the user wait, but offer a 'backup' solution, so I need a way to check if Redis is working before calling Celery. In Django I have(for local): CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] so the connection is done automatically. I don't want to maintain a connection with Redis for the check or interfere with Celery if is ok. -
create a column array field that can store json objects in python for postgres database
I have a table in postgreql and i want to add a new column to my table in my python django code but i seem to be running into some problems. This field is meant to be an array of json objects field which means should be able to store this [{"a":"b", "b": "c"}, {"c": "d", "e": "f"}] I wrote this to create the column additional_drivers = ArrayField(ArrayField(JSONField('Additional Drivers')), default=list, null=True) Which it does but when i try to add a record or update an existing record via sql i cannot Update price_ags_pricerequest set additional_drivers = "[{"a":"{'42','n1','n2','43'}"}]" where id = 1; This is my sql query. Not sure if i am creating the column correctly hence cannot save array fields to the column. -
Django Form Wizard: why done() method is not called after submitting?
I'm using a SessionWizardView and I can't understand why the done()method is never called. Instead, after posting my form, in the last step, I can see a POST HTTP 200 on my server, but this does nothing. The get_form() method works as expected. I suspect a distraction error since I have the exact same logic for another view, and this works well. Here is the whole code bellow. The view class DiscountsCreateView(PermissionRequiredCanHandleProducts, ModelInContextMixin, RestaurantMixin, SubSectionDiscounts, SessionWizardView): """ Wizard view to create a discount in 2 steps """ model = Discount # used for model context form_list = [DiscountForm0, DiscountForm1] template_name = "discounts/discount_add.html" def get_form(self, step=None, data=None, files=None): form = super().get_form(step, data, files) if step is None: step = self.steps.current # step0 - name, kind, tax_rate # => nothing special to do, always the same form # step1 - specific fields related to the chosen kind if step == '1': step0_data = self.storage.get_step_data('0') kind = step0_data['0-kind'] # combo => combo, combo_unit_price if kind == Discount.COMBO: form.fields['combo'].queryset = Combo.objects.restaurant(self.restaurant) # NOTE : this is not a scalable way to show/hide fields (exponential) form.fields['rebate_amount'].widget = forms.HiddenInput() elif kind == Discount.REBATE: form.fields['combo'].widget = forms.HiddenInput() form.fields['combo_unit_price'].widget = forms.HiddenInput() return form def done(self, form_list, **kwargs): data … -
Display a read-only GenericForeignKey value in Django admin
I have a Django model with a generic relation to either a User or an Organization. The model looks like this: class Project(models.Model): # ... client_type = models.ForeignKey( 'contenttypes.ContentType', on_delete=models.SET_NULL, blank=True, null=True, limit_choices_to=( models.Q(app_label='users', model='user') | models.Q(app_label='organizations', model='organization') ) ) client_id = models.PositiveIntegerField( blank=True, null=True, ) client = GenericForeignKey( 'client_type', 'client_id', ) # ... I can display the name of whatever is the client of this project in the project admin list, using: @admin.register(models.Project) class ProjectAdmin(admin.ModelAdmin): list_display = ( '__str__', 'client', ) However, I can't find a simple way to display the name of the client in the actual change page of a project. I tried the obvious: fields = ( 'name', 'client', ) But this generates an error about client not being a valid field name. I read the Using generic relations as an inline section of the Django docs, but their example seems...backwards? I just want to display the name of whoever is the client, it doesn't have to be editable. Any suggestions? -
Maintain two different model schema version to connect two different database in Django
In my Django app, I have one model Question which is connected to database db_one. Now I want add and modify few fields in Question model. Until the new Question model schema is tested thoroughly, I want to keep the old Question model schema accessible in UI. Also I am maintaining a separate database db_two for this new schema such that main app is not affected. How can model schema versioning be achieved in Django such that I could select the database based on model version? Or, Is there any better approach to deal with this? -
Django Celery upadate page context every fixed period of time without making another request
after sending a request and visiting a view, I'd like to have it's context data updated every second without refreshing the page. So, probably there's a need of creating a background task which will calculate and update context data every fixed period of time. I read about Celery which may make my problem solved but I haven't been using asynchronous libraries yet. Maybe there is another solution you can recommend beyond asynchronous tasking? Regards, Wojtek -
How to cache template in inclusion_tag
I am trying to cache whole template in inclusion_tag but I've got problem with that. Here is my code of inclusion_tag: @register.inclusion_tag('accounts/helpers/user_info.html', takes_context=True) def user_info(context, username, size=40): request = context['request'] user = cache.get(username) if not user: user = User.objects.get(pk=username) print("cached") cache.set( username, user, settings.USER_LAST_ACTIVITY_TIMEOUT) return {'user': user, 'size': size} and code of html template: {% load static i18n humanize accounts cache %} {% get_current_language as LANGUAGE_CODE %} {% cache 3600 user_info user.pk LANGUAGE_CODE size %} <a class="user-info" href="{{ user.get_absolute_url }}"> <div class="user-avatar-wrapper"> <span class="online-status {{ user.online_status }}"></span> {% if size %} {% avatar user size class="avatar" id="user_avatar" %} {% else %} {% avatar user 40 class="avatar" id="user_avatar" %} {% endif %} </div> <span> {{ user }} <small>{{ user.groups.all|join:", " }}</small> </span> </a> {% endcache %} With this code I cache only user but I want to cache whole template in tag. Could you help me how to do it ? I've tried everything but I do not have idea how to deal with that. -
Cleaning Image field invalidates form in django
I am trying to clean the photo submitted via an ImageField in a form using Pillow and in the following code in django 2.1 def clean_photo(self): photo = self.cleaned_data.get("photo") if photo: if photo.size > 100000: raise forms.ValidationError(u'Image is too large. Upload an image less than 100Kb in size') image = Image.open(photo) if image.size[0] > 250 or image.size[1] > 250: raise forms.ValidationError(u'Image is too large. Upload an image less than 250x250 dimensions') return photo When I dont have this method the form works fine and the picture gets uploaded and saved. However when using this method I get a The UserForm could not be changed because the data didn't validate. error. Would appreciate any help as to why this is happening. Thank you all Sameer -
Django admin add group name to requests
I'm trying to create a little report in Django Admin right now. Is it possible to display the user group name? admin.py class Request_ReviewAdmin(admin.ModelAdmin): list_display = ('date_of_request', 'request_type', 'request_user') def date_of_request(self, obj): return obj.request_date.strftime("%d %b %Y") date_of_request.admin_order_field = 'timefield' date_of_request.short_description = 'Request Date' with this example I display this in the user table, but this is not possible here def group(self, user): groups = [] for group in user.groups.all(): groups.append(group.name) return ' '.join(groups) group.short_description = 'Groups' -
Error: ledger1 object has no attribute Creditledger
This is following line of code for my project >>>ls = ledger1.objects.all() >>>for cm in ls: jr = cm.Creditledger.all() for Creditledger in jr: print(Creditledger) The error I am getting AttributeError: 'ledger1" object has no attribute 'Creditledger' Can anyone please help me on this.. Thank you... -
Running Selenium for an external website from Django
I have a standalone Python-Selenium bot which simulates user interaction in an external website. I would like to write some of the details which get from the website into a database. So I like to integrate the existing bot into Django framework to make writing into the database easier. I wonder whether it is possible to integrate this standalone project into Django. If yes, I would like to know how can I trigger the bot. -
How to lock a transaction in Django?
There is a case when request is sent multiple times to the server with same data. I want to insert that data in database using ORM of Django. In that data there is a field say 'field_imp' which can only be unique. Right now it gives me integrity error as both the request are trying to insert together. How do I avoid this condition? How to send multiple request together? Using terminator open multiple tabs, write the same curl request and send. Model in Django: class MyModel(models.Model) field_imp = models.TextField(unique=True) I am using Django rest Framework for the api generation and its serializers for data's validation. -
Is there any chance to bring back data when I removed field from django model?
Is there any chance to bring back data when I removed field from django model? migrations.RemoveField( model_name='user', name='item', ), -
Django Rest Framework Return 403 in Serializer
How can I return a different error code with django rest framework's serializers? I have in my serializer.py file: def create(self, validated_data): if 'Message' not in validated_data: # If message is blank, don't create the message return PermissionDenied() But when I do that, it just returns 201 with the body {"deleted":null} instead of returning a 403 error. How can I make it return the 403 error?