Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter on values of child objects
I have the following (simplified) data model: class Article(Model): uuid = models.CharField(primary_key=True, max_length=128) class Attribute(Model): uuid = models.CharField(primary_key=True, max_length=128) article = models.ForeignKey(Article, related_name='attributes') type = models.CharField(max_length=256) value = models.CharField(max_length=256) An example usage would be an article with an attribute attached to it with type="brand" and value="Nike". Now I want to write an API which can get all articles with a certain brand, but I can't seem to write the filter for it. This is what I have so far: class PhotobookFilter(df.FilterSet): brand = df.CharFilter(method='filter_brand') class Meta: model = Article def filter_brand(self, queryset, name, value): return queryset.filter('order__attributes') class PhotobookViewSet(AbstractOrderWriterViewSet): queryset = Article.objects.all() serializer_class = ArticlePhotobookSerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = PhotobookFilter The line with queryset.filter is obviously not correct yet. I need to create a filter here that returns all articles that contain an attribute with type="brand" and value=value. How would I do this? -
How to set nginx to forward a view?
I have the same issue as the person who wrote the following post. The solution is not complete though. I get that the web server should not serve my templates directly (otherwise they will be displayed as raw HTML since Django did not process them). My question is...how can I set nginx to forward a view in the following example? nginx: django template index.html can't display well -
Django : No Reverse Match on password reset
I am working on password reset functionality in Django using custom templates. But when I entered mail:id and clicking on reset password I'm facing "No Reverse match error".Please someone help me,I understand this is an old problem, I have followed other answers and tried solving but could not come up with solution.Please find the code below and help me solve this problem. urls.py: from django.conf.urls import url,include from django.contrib import admin from django.contrib.auth.views import password_reset,password_reset_done,password_reset_confirm,password_reset_complete from surveysite.views import home,about,login,loggedin,loggedout urlpatterns = [ url(r'^$', home, name='home'), url(r'^about/$',about, name='about'), url(r'^accounts/', include('registration.backends.default.urls')), url(r'^accounts/login/$', login, name='login'), url(r'^accounts/loggedin/$',loggedin, name='loggedin'), url(r'^accounts/logout/$', loggedout, name='logout'), url(r'^accounts/password_reset/$', password_reset, {'post_reset_redirect' : '/accounts/password_reset/mailed/'}, name="password_reset"), url(r'^accounts/password_reset/mailed/$',password_reset_done), url(r'^accounts/password_reset/(?P<uidb36>[0-9A-Za-z]{1,13})-(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',password_reset_confirm, {'post_reset_redirect' : '/accounts/password_reset/complete/'},name="password_reset_confirm"), url(r'^accounts/password_reset/complete/$',password_reset_complete), url(r'^admin/', admin.site.urls), ] settings.py :Installed Apps: INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'registration', 'django.contrib.admin', ] Password_reset_form.html : {% extends "base.html" %} {% block title %}Password Reset{% endblock %} {% block content %} <h1>Password Reset</h1> <p>To reset your password, enter your email address below, and you'll receive an email with a link to set a new one.</p> <form action="" method="post">{% csrf_token %} {{ form.email.errors }} <p><label for="id_email">Email address:</label> {{ form.email }} <input type="submit" value="Reset Password" /></p> </form> {% endblock %} Password_reset_done.html : {% extends "base.html" %} {% block title %}Password β¦ -
How to call plans for subscribe.html page in djstripe
I have subscribe.html page but the palns are not displaying and i have removed subscribe.html page then it's displaying. please suggest it. -
Assigning null value to a reference field in mongoengine
I have two Document class NameDetail(Document): name = StringField(required=True) class UserDetail(Document): name_detail = ReferenceField(NameDetail) now what if I want to assign Null value to a reference field in my case "name_detail".I have gone through mongoengine documentation and found "CASCADE" and "NULLIFY" to achieve this but this will work and delete the ReferenceField.I need to remove the reference without deleting it. -
deploying django on webhostpython.com
I am new in Python using Django. However, am working on a django project and need to deploy on webhostpython.com but am getting some error 503. My app name before upload to the server is 'prelude'. Below is my settings file; import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'dfgegdg4353gtKDFDer#23345' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [ 'example.com', ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myproject.prelude', 'widget_tweaks', 'mathfilters', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'myproject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR+"/templates",], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'myproject.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'HOST': '', 'PASSWORD': 'etredf', 'USER': 'gbale', 'ENGINE': 'django.db.backends.mysql', 'NAME': 'funakaye', } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', β¦ -
Django autocomplete - request.is_ajax() always returns false
New to Django. Trying to set up a page which has a text box that supports autocomplete. I referred to this post for guidance. For some reason, request.is_ajax() always returns false. url.py urlpatterns = [ url(r'^$', views.search_assist, name='search_assist'), ] views.py def search_assist(request): if request.is_ajax(): q = request.GET.get('term', '') states = State.objects.filter(state_name_full__icontains = q )[:20] results = [] for state in states: state_json = {} state_json['id'] = state.id state_json['label'] = state.state_name_full state_json['value'] = state.state_name_full results.append(state_json) data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) HTML {% extends "giftiply_alpha_test/header.html" %} <div class="ui-widget"> <label for="sassist">Search Assist: </label> <input type="text" id="sassist"> </div> header.html has the following jQuery function. <script> $( document ).ready(function() { assist(); }); function assist(){ $("#sassist").autocomplete({ source: "/search_assist/", minLength: 2, }); } </script> I have seen few other posts on a similar note but the comments / responses on those posts didn't help. Any ideas on why request.is_ajax() always returns false? Appreciate the help. -
Django unit tests not executing django signals from original model
I am creating few django tests and one of the test needs to post the data to certain url as soon as new model gets created or updated and I am using djnago signals for dispatching them in my models.py file. Now when I create new object or the modify existing object from shell, I get the post request to the target url with specified data and thus working completely fine. However, when I write statements to create or update the model in django tests it doesn't do anything, It just create the object in alias database but does not actually send any signal to target url Here is how my django test look like: class ProductEndpointTests(APITestCase): def test_product_create(self): productobject = Product.objects.create(title="pr1", description="good deal", price=19.99) alertobject.save() Models.py: class Product(models.Model): title = models.CharField(max_length=120) description = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=20) def product_post_save(sender, instance, created, *args, **kwargs): product = instance # Post data to given url post_save.connect(product_post_save, sender=Product) Is there anything that I am missing or do I need to add anything in django test in order to dispatch signals from tests? Any help on this would be appreciated. Thanks -
Django can't find my models in Linux but can in Windows
I am somewhat still unfamiliar with Django so please excuse the possible elementary question. am trying to deploy a Django project, but I am having some problems with it. The project works exactly as it should on Windows, however I am getting this error on my Ubuntu VPS: Unhandled exception in thread started by <function wrapper at [...]> Traceback (most recent call last): [...] Stack trace from system/django files File "/home/django/[Project Name]/apps/sale/admin.py", line 8, in <module> from .forms import SaleRequestFormAdmin File "/home/django/[Project Name]/apps/sale/forms.py", line 6, in <module> from apps.listing.models import Listing ImportError: No module named listing.models My structure for the project is like this (with irrelevant components removed or shortened): . βββ apps β βββ [...] β βββ listing β β βββ admin.py β β βββ api.py β β βββ apps.py β β βββ forms.py β β βββ __init__.py β β βββ migrations β β β βββ [...] β β βββ models.py β β βββ tests.py β β βββ views.py β βββ sale β β βββ admin.py β β βββ api.py β β βββ apps.py β β βββ forms.py β β βββ __init__.py β β βββ migrations β β β βββ [...] β β βββ models.py β β βββ tests.py β¦ -
Ubuntu 14.04 - How to configure Xampp to run Python Django
I would like to run python django in my local server. I have installed Xampp and running php in it (which is located at /opt/lampp/htdocs/). How i can configure it to run python. Doing some research reveled that i need to install mod_wsgi in apache. And i need to install libapache2-mod-wsgi. But i think it is specific for apache2? Will it work on Xampp? -
How to compare two string on template in django?
I am trying to compare two string in template but always it is showing result in else.Here i am adding my code where trans_his.trans_type= Debit but it always shows credit {% if trans_his.trans_type == "Debit" %} <td>debit {{data.amount}}</td> {%else%} <td>credit {{data.amount}}</td> {%endif%} -
Django template pass array increase counter value inside template tag
I want to pass array value counter value inside django template . {% for scene in scenes %} <hotspot name="skin_btn_prev{{forloop.counter}}" name1="{{ iterator.next }}" keep="false" style="skin_hotspotstyle_navigate" ath="-180" x="55" y="0" scale="0.5" alpha="0.5" linkedscene="{{scenes.1.dbobj.getStrID}}" onclick="lookat(0, 34, 120);" /> {% endfor %} linkedscene="{{scenes.1.dbobj.getStrID}}" I want to pass here the counter value . when I run the for loop here I want to pass the value like 1,2,3,4,5....till last loop run. How can I do this ? -
django output wrong media url
Django version is 1.10.3 Static file server is nginx Debug mode off The output media url has an absolute path in the server. eg: http://127.0.0.1:8001/home/ken/hc/media/uploads/q/2017/03/01/hjqtye.png The correct url is: http://127.0.0.1:8001/media/uploads/q/2017/03/01/hjqtye.png How can i fix it? THX. The relevant code as below. settings.py INSTALLED_APPS = [ 'grappelli', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'ckeditor_uploader', 'imagekit', 'debug_toolbar', 'gunicorn', 'Website', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static') STATICFILES_DIRS = [(os.path.join(BASE_DIR, 'collected_static'))] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' CKEDITOR_UPLOAD_PATH = "uploads/" #CKEDITOR_UPLOAD_PATH = os.path.join(BASE_DIR, MEDIA_ROOT, 'uploads') Nginx conf file server { listen 8001; server_name 127.0.0.1; access_log /var/log/nginx/hc.access.log; error_log /var/log/nginx/hc.error.log; location / { #uwsgi_pass 127.0.0.1:8010; #include uwsgi_params; proxy_pass http://127.0.0.1:8010; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /media/ { alias home/ken/hc/media/; expires 1h; access_log off; #add Cache-Control 'public'; } location /static/ { alias home/ken/hc/collected_static/; expires 1h; access_log off; #include /etc/nginx/mime.types; #add Cache-Control 'public'; } } -
Django - Is it possible to show image on page without make it static?
I'm building a web page to modify images(cropping, scaling, etc..) based on the meta data which is the output of my python scripts. In each meta data specify the index of the particular image in the field (ex: meta data: [idx: 01, ..,..] then image01 will be operated.) However in my case, there are tons of image source(dataset_01, dataset_02, ...) and in each image dataset it contains 10000 images. Now my solution is to put the image dataset into the static folder and command python manage.py collectstatic` However it took tons of time as django has to collect all the 10000 image source everytime I add a new image dataset. I'm just wondering is there any possible that I don't have to collect those images as static file and just directly open the image files in the folder? -
Django inserting large dataset into model - linewise vs bulk?
I am working on a project where I need to insert large files into models (sometimes several gigabytes). Because the files can be large the approach I am taking is to read it linewise, and then insert it into the Django model. However, when an error is encountered in the process, how do I cancel the whole operation? What is the proper way to make sure that the rows already inserted are deleted/removed when an error is encountered. The other alternative is to create all the model objects in one go and insert it in bulk, is this feasible for large datasets? How would it work. Here's my code: class mymodel(models.Model): fkey1 = models.ForeignKey(othermodel1,on_delete=models.CASCADE) fkey2= models.ForeignKey(othermodel2,on_delete=models.CASCADE) field 1= models.CharField(max_length=25,blank=False) field 2= models.DateField(blank=False) ... Field 12= models.FloatField(blank=False) And inserting data into the model from excel: wb=load_workbook(datafile, read_only=True, data_only=True) ws=wb.get_sheet_by_name(sheetName) for row in ws.rows: if isthisheaderrow(row): #determine column arrangement and pass to next break for row in ws.rows: if isthisheaderrow(row): pass elif isThisValidDataRow(row): relevantRow=<create a list of values> dictionary=dict(zip(columnNames,relevantRow)) dictionary['fkey1']=othermodel1Object dictionary['fkey2']=othermodel2Object TransactionData(**dictionary).save() -
Django Rest Framework default image field value returns Validation
we our using REST and there is a feature of a site management. Where the a name, description, title and icon will come from the API. We also have an admin interface on another front-end app that makes changes on the API. Here is models.py: class Website(models.Model): icon = models.ImageField() name = models.CharField(max_length=100) second_name = models.CharField(max_length=100) description = models.TextField() Here is serializers.py: class WebsiteSerializer(serializers.ModelSerializer): class Meta: model = Website fields = '__all__' Here is the views.py: class WebsiteViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): model = Website queryset = Website.objects.filter() permission_classes = [] renderer_classes = [renderers.JSONRenderer] serializer_class = WebsiteSerializer def list(self, request): serializer = self.get_serializer(self.queryset.first()) data = serializer.data return Response(data) My issue is the icon. It works fine when you are updating the icon. However it returns 'The submitted data was not a file. Check the encoding type on the form.' validation error when you did not change the icon.. This is an example of what is being returned when you get the data of the API: { "id": 1, "icon": "http://192.168.0.110:8000/upload/%E5%B1%8F%E5%B9%95%E5%BF%AB%E7%85%A7_2017-02-23_%E4%B8%8B%E5%8D%886.02.42_zbAld6c.png", "name": "Hello", "second_name": "World", "description": "Bacon Loren Ipsum Porsum" } I think the issue here is that when we do not change the icon on the front-end, the URL string value β¦ -
Django Pandas to JSON need help figuring out looping issue
This is an internal application which is in pieces currently. However what I'm working on is creating a feature where the end user can upload an excel file which is referred to as a promptlist. The result is the promptlist is parsed out and necessary bits are used to create JSON as well as included to build modules and their nodes. The JSON piece is based on language. A spreadsheet can have a generic column called 'prompt text' which is english and it can have numerous other language related columns 'spanish prompt' 'russian prompt' 'french_canadian prompt' etc. I'll never know how many languages will be on the spreadsheet. Another rule is that Language is a project key and in order for the column to be parsed the language has to be already added as part of the project when the enduser creates the project shell. That's how I am able to determine the 'unknown' column names etc. What's happening is only 1 language is parsed out to create the language prompts. When I need a loop or during the BIG loop all languages are parsed out as their own language related object. I'm not sure how to get this to β¦ -
Error message while setting up VirtualEnv for Django on Mac - what to do?
let me mention first that I just started to learn Django and it seems like I am already failing by setting it up. I went to the steps recommended on the 'First steps in Django' page, even bought the book 'mastering Django' and I am also aware that this question has probably be answered already but so far I couldn't find a solution according to my problem. So what happens is basically that I installed pip, I installed virtualenv and Django. When I try to create a virtualenv I get the following error message: M-MacBook-Air:django m$ virtualenv first Using base prefix '/Users/m/anaconda' New python executable in /Users/m/Desktop/python/django/first/bin/python dyld: Library not loaded: @loader_path/../lib/libpython3.5m.dylib Referenced from: /Users/m/Desktop/python/django/first/bin/python Reason: image not found ERROR: The executable /Users/m/Desktop/python/django/first/bin/python is not functioning ERROR: It thinks sys.prefix is '/Users/m/Desktop/python/django' (should be '/Users/m/Desktop/python/django/first') ERROR: virtualenv is not compatible with this system or executable According to the scripts, tutorials etc. I should find the following folder in my new created virtualenv: \Include \Lib \Scripts \src but in my case it's just \bin \include \lib The obvious question: why is that? I use Python3.5, pip9.0.1 and virtualenv15.1.0. I start Python via Anaconda, downloaded Homebew once but deleted it and also β¦ -
Python/Django request.FILES['']
I know this is easier than I'm making it... I want to get the data and filename for a file = request.FILES['test'] Im going to be storing the image into a fire database. My question is, do I need up save the image to my python server before I can save it to the firebase DB? If I need to save it to the server db, then what is the correct way to do this? I was under the impression that I could just get the image data and pass that along to the firebase db. Any help would be greatly appreciated. Thank you, Denis Angell -
django-imagekit replace preview image with alternative src
I am using django-imagekit to upload images. I allow the user to preview their image before saving the image to the DB, because the image will be resized. The issue I have is that if the user uploads a non image (say a word doc, .xml file, etc) , then the preview will display the image with an incorrect source, as displayed below: Here is the template code of the preview of a non image file: <img id="id_employment_history_logo_preupload_preview" class="upload_file_border logo_preview_dimensions" data-placement="right" src="data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,UEsDBBQABgAIAAAAIQCGY0RLxwEAAE0IAAATAAgCW0NvbnRlbnRfVHlwZXNdLnht/X+kVzZe0dx1VYRI71Xtun5V9HdqGJ3LS55mtAAABMAEwDQBAAASKUAAAAA" tabindex="-1" style="display: inline-block;"> How can I display an alternative preview image or image src when the user attempts to upload a non image file type? I have seen this SO thread, but it does not work. -
Django - How to efficiently add a list to a many-to-many model field
I have three models. Posts, Tags and Subscribers. There is a many-to-many relationship between Posts and Subscribers and another many-to-many relationship between Tags and Subscribers. There is a ForeignKey relationship between Posts and Tags. I want to add all the subscribers for a given post to it's associated tag. I am able to achieve this by doing the following. But is there a more efficient way to do this than to iterate through two for loops ? all_subscribers = post.subscribers.all() for tag in tags: for subscriber in all_subscribers: tag.subscriber.add(subscriber) tag.save() Please note that I am using a toy example above for simplicity. -
django admin actions with intermediate page Httresponseredirect doesn't work
I'm newbie in django. I would like to make admin action with intermediate page. I use django 1.7. According to django 1.7 admin action with intermediate page should return HttpResponseRedirect. But in my case just page refresh happens. My code is listed below, and if you need here is link to my github repository . Please help me to understand the reason of such behavior. def update_group(modeladmin,request,queryset): if 'change_group' in request.POST: form=UpdateGroupForm(request.POST) if form.is_valid(): group=form.cleaned_data['group'] updated_group=queryset.update(student_group=group) counter=queryset.count() modeladmin.message_user(request,u"Π£ %s ΡΡΡΠ΄Π΅Π½ΡΡΠ² Π±ΡΠ»ΠΎ Π·ΠΌΠ½Π΅Π½Π½ΠΎ Π³ΡΡΠΏΡ Π½Π° %s")%(counter,group) if not form: form= UpdateGroupForm() return HttpResponseRedirect ('/students/change_group.html',{'students':queryset,'form':form,'title':u'ΠΠΌΡΠ½Π° Π³ΡΡΠΏΠΈ'}) update_group.short_description=u'ΠΠ΅ΡΠ΅ΠΌΡΡΡΠΈΡΠΈ Ρ Π³ΡΡΠΏΡ' class StudenAdmin(admin.ModelAdmin): #action_form = UpdateGroupForm - use it only if you need to change action form actions = [update_group] list_display = ['last_name','first_name' ,'ticket','student_group'] list_display_links = ['last_name','first_name'] list_editable = ['student_group'] ordering = ['last_name'] list_filter = ['student_group'] list_per_page = 10 search_fields = ['last_name','first_name' ,'ticket','notes'] def get_view_on_site_url(self, obj): return reverse ('students_edit',kwargs={'pk':obj.id}) -
Django form is valid if one validator is valid
I am working on this form in django class EmailOrPhoneForm(forms.Form): phone_or_email = forms.CharField( validators=[validate_phonenumber, validate_email], ) it has two validators but I want the form to return true if one of them is valid , Phone number or Email. how can I do this without writing a single validator that does it all ? -
Does Django Atomic Transaction lock the database?
When you do: @transcation.atomic def update_db(): do_bulk_update() while the function is running, does it lock the database? I'm asking regarding django's atomic transaction: https://docs.djangoproject.com/en/1.10/topics/db/transactions/#autocommit-details -
How do I get objects to order themselves while also being order with respect to a parent object?
So I am trying to order a child element (called "NotebookPost"). I want these objects to list themselves in order by date. But I also need them to only show in their respective spots, so they need to be order by a parent element (called "NotebookYear"). After all the ordering is in place i need them to be sorted based by year and put into two accordions (The year is not really separated by year but actually separated by the games seasons ( from September to April). They should end up looking like this on the page... but in order, based on the DateField and the ForeignKey relation.