Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can we deploy a django app onn google cloud?
I am having trouble deploying a developed django app on google console. Firstly it renames all the files of the app to some random name. Also when I try to hit the website .appspot.com I get an internal error. Have created app.yaml file: # [START runtime] runtime: python27 entrypoint: gunicorn -b :$PORT mysite.wsgi threadsafe: true # [END runtime] handlers: - url: /static static_dir: website/static - url: /.* script: main.application libraries: - name: django version: 1.11 Also have created appengine_cofig.py file: # Copyright 2015 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # [START vendor] from google.appengine.ext import vendor vendor.add('lib') # [END vendor] Thanks for the help in advance.... -
Django admin CSRF 403 error
I have multiple django servers (API backend for mobile clients) running behind a load balancer. But when accessing django admin some times I'm getting 403 forbidden error. Is it related to csrf cookie ? My load balancer setting is, Session Stickiness - None Algorithm - Roundrobin -
Whitenoise giving errors on jquery-ui.css when doing collectstatic
I'm trying to install the jquery-ui-dist package, and when I run collectstatic, whitenoise seems to have trouble when a url is inside quotations in a stylesheet. The error I get is: MissingFileError: The file 'jquery-ui-dist/"images/ui-icons_555555_256x240.png"' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x7fb16b7000b8>. The CSS file 'jquery-ui-dist/jquery-ui.css' references a file which could not be found: jquery-ui-dist/"images/ui-icons_555555_256x240.png" Please check the URL references in this CSS file, particularly any relative paths which might be pointing to the wrong location. I see that it seems to think it's looking for a bad filename, as it keeps the quotations around it, and I assumed that the reason was because the source file has url("images/ui-icons_555555_256x240.png") when the quotations are unnecessary, so I ran sed -i 's/\"images\/ui-icons_555555_256x240.png\"/images\/ui-icons_555555_256x240.png/g' jquery-ui.css on the source file, which removed the quotation marks, but I still get the error. I'm assuming there is a problem with either whitenoise or the jquery-ui-dist package, but until the problem is fixed on their end, I at least need a temporary solution, and I'm not even sure where the actual problem lies. -
django model relation does not exist
I am trying to add an Image to a Product model but I am getting this error DoesNotExist at /admin/startupconfort/startupproductimage/add/ StartupProductImage matching query does not exist. error models from stdimage.models import StdImageField class StartupProductImage(TimeStampedModel): product = models.OneToOneField(StartupProduct, related_name='image', on_delete=models.CASCADE, primary_key=True, ) picture = StdImageField(upload_to='startup-product/%Y/%m/%d', verbose_name="pics", blank=True, variations={ 'large': (600, 400), 'thumbnail': (250, 250, True), 'medium': (300, 200), }) product class StartupProduct(TimeStampedModel, VoteModel): startup = models.ForeignKey( Startup, null=False, blank=False , related_name='brand_product') category = models.ForeignKey( Category, null=False, blank=False , related_name='product_category') title = models.CharField(verbose_name=_(u"Title"), max_length=32) shortdesc = models.CharField(max_length=80, null=False, blank=False, verbose_name='shortdesc') slug = AutoSlugField( unique_with=('created', 'startup'), ) price = models.IntegerField(default=28) quantity = models.PositiveIntegerField(verbose_name=_(u"Qty"), default=1, validators=[MaxValueValidator(10),MinValueValidator(1),] ) -
Django datetime/timedelta incompatible type
I'm trying to subtract 2 datetimes from my csv file. Purchase Is a column in csv file. orders["Closed"] = pd.to_datetime(orders["Purchase"]).dt.minute.apply(lambda x: x + 15) first = orders.loc[x]["Check Closed"] second = pd.to_timedelta(orders[(orders["ID"] == x)]["Purchase"]) duration_time = (first - second).time() return duration_time x - is client's ID from another csv file. When I'm trying to run this code, I have: incompatible type for a datetime/timedelta operation [__rsub__]. Is it problem, that "Closed" is a timedelta, so I couldn't subtract datetime and timedelta, and how can I solve this. Thanks. -
How can I use the values_list in Wagtail (django)?
hi sorry for my poor English Why wagtail search return PostgresSearchResult after search ? i want PageQuerySet like Django postgres search backend because I can not use values_list after search i want to get list of page path ( because i want to find pages parents(Category Page) by path ) and i can't use values_list before search because it does not work i know, i can use Forloop but this takes about 5 seconds for each run My code is very simple : Django Way : #Work ProductPage.objects.filter(title__search="phone").values_list('path') Wagtail Way : #NotWork :( ProductPage.objects.search(query).values_list('path') -
django: RelatedManager for chained relations objects
So I've got models: class Parent(models.Model): name = models.CharField(max_length=100) class Child(models.Model): parent = models.ForeignKey('Parent', on_delete=models.CASCADE) name = models.CharField(max_length=100) class Grandchild(models.Model): parent = models.ForeignKey('Child', on_delete=models.CASCADE) name = models.CharField(max_length=100) class ParentPhoto(models.Model): person = models.ForeignKey('Parent', on_delete=models.CASCADE) image = models.ImageField() class ChildPhoto(models.Model): person = models.ForeignKey('Child', on_delete=models.CASCADE) image = models.ImageField() class GrandchildPhoto(models.Model): person = models.ForeignKey('Grandchild', on_delete=models.CASCADE) image = models.ImageField() Please ignore the bad database/models design (it's just an analogy to my complex real-life application). I want to add a RelatedManager for Parent named maybe family_photo_set that would return a Queryset containing all Photos for himself, his Children and all Children' Grandchildren. How do I achieve that? A simple RelatedManager allows me to only filter somehow a Parents' parentphoto_set, not really adding the rest of family members. -
Account Kit web login error
I set up AccountKit login page according to the Facebook documentation here. The problem is when I try to login using an email, on the last step after clicking 'Log in' it gives me an error which isn't very descriptive: signin.html: {% extends 'web/landing_base.html' %} {% load staticfiles %} {% block main_content %} <p>Sign in</p> <button onclick="emailLogin()">Email</button> <script src="https://sdk.accountkit.com/en_US/sdk.js"></script> <script> // initialize Account Kit with CSRF protection AccountKit_OnInteractive = function () { AccountKit.init( { appId: "{{ facebook_app_id }}", state: "{{ csrf_token }}", version: "{{ account_kit_api_version }}", redirect: "{{ redirect_url }}", debug: true } ); }; // login callback function loginCallback(response) { if (response.status === "PARTIALLY_AUTHENTICATED") { var code = response.code; var csrf = response.state; // Send code to server to exchange for access token } else if (response.status === "NOT_AUTHENTICATED") { // handle authentication failure } else if (response.status === "BAD_PARAMS") { // handle bad parameters } } // email form submission handler function emailLogin() { AccountKit.login('EMAIL', {}, loginCallback); } </script> {% endblock %} views.py: def signin(request): template = loader.get_template('web/signin.html') context = { 'facebook_app_id': <facebook_app_id>, 'account_kit_api_version': 'v1.1', 'redirect_url': 'http://127.0.0.1:8000/web/products/', } return HttpResponse(template.render(context, request)) AccountKit app configuration: Any advice what could cause the issue? -
python how to create errors manually and handle network errors
I'm using the requests library (within a django app) to consume an api. (eg to validate some data, payment details, address details etc....) However I'm working with an api that doesn't use http status codes (eg if it is a failed response I don't get a http 500 but a 200 instead and the details that it failed are in the response. It also uses custom internal status codes.). I've created a handler to handle the exceptions for the various endpoints I need to interact in this api. However I'm not clear on a couple of things: 1) how to manually create an error and log it (with traceback etc..) and raise it when the api (eg below when status returns false), how can I include the full traceback and the status, status_code, message, and data? Is it best to pass these into the custom error and raise this. (not sure how to get traceback too)? 2) What's the best way to test the below code, (ie that I get the right error raised, when api is down, returns 500, or doesn't return a json response, or if a json response but returns status as false etc...? (In a manual … -
Show more function when display object in django template
I want to display multiple images (from a table in my database) in my django template via model object. However, the number of images could be thousands. I wonder if there exists a way to add "show more" function that allows my template to display images batch by batch without having reload the entire page? (like when you use google image search) -
form is failing to submit the data in django
I created one form to sign up the patient. All the data are correct but it fails to submit the data It works successfully without any error. When submit button is clicked, page is redirected to "Invalid data" which is else statement in views.py file. I checked all of the data of models.py and forms.py,but could not able to find what is going wrong. I tried the solution by adding {{ psform.errors }} in template file. But it didn't work. models.py class PatientSignup(models.Model): GENDER = [ ('Male', 'male'), ('Female', 'female'), ] STATE = [ ('Gujrat', 'Gujrat'), ('Maharastra', 'Maharastra'), ] CITY = [ ('Valsad', 'Valsad'), ('Surat', 'Surat'), ('Rajkot', 'Rajkot'), ] pid = models.AutoField(verbose_name='Patient Id', primary_key=True, auto_created=True) pname = models.CharField(verbose_name='Enter Name', max_length=50, default=NameError) email = models.CharField(verbose_name='Enter Email', max_length=100,unique=True) gender = models.CharField(verbose_name='Select gender',max_length=6, choices=GENDER) age = models.PositiveIntegerField(verbose_name='Enter age',default=5, null=True) state = models.CharField(verbose_name='Select State',max_length=20, choices=STATE) city = models.CharField(verbose_name='Select City',max_length=30, choices=CITY) password = models.CharField(verbose_name='Enter Password',max_length=12) confirmPassword = models.CharField(verbose_name='Confirm Password',max_length=12) date = models.DateTimeField(auto_now_add=True) view.py class signup(TemplateView): template_name = 'personal/signup.html' temp = 'personal/log.html' def get(self, request): #this works successfully def post(self, request): psform = PatientSignupForm(request.POST) if psform.is_valid() and psform.cleaned_data['password'] == psform.cleaned_data['confirmPassword']: psform.save() args = {'psform': psform} return render(request, self.temp, args) elif psform.cleaned_data['password'] != psform.cleaned_data['confirmPassword']: return HttpResponse("Password and … -
Fill requirements.txt from PyCharm virtual environment
I am trying to fill a requirements.txt for my PyCharm Django project that has a virtual environment. I am using pip freeze > requirements.txt This creates lots of entries as shown here but does not have entries for packages I have added such as djangorestframework, Django-crispy-forms etc. What do I have to do to get all my packages listed? At the moment my requirements.txt looks like this: altgraph==0.10.2 amqp==2.1.4 appdirs==1.4.3 awsebcli==3.10.0 backports.ssl-match-hostname==3.5.0.1 bdist-mpkg==0.5.0 billiard==3.5.0.2 blessed==1.14.1 bonjour-py==0.3 botocore==1.5.26 cement==2.8.2 click==6.7 colorama==0.3.7 coreapi==2.3.0 coreschema==0.0.4 defusedxml==0.4.1 django-appconf==1.0.2 dockerpty==0.4.1 funcsigs==1.0.2 futures==3.1.1 itypes==1.1.0 Jinja2==2.9.6 jmespath==0.9.2 kombu==4.0.2 macholib==1.5.1 MarkupSafe==1.0 matplotlib==1.3.1 modulegraph==0.10.4 numpy==1.8.0rc1 oauthlib==2.0.1 olefile==0.44 openapi-codec==1.3.1 packaging==16.8 pathspec==0.5.0 pbr==3.0.1 progressbar2==3.20.0 psycopg2==2.7.3.2 py2app==0.7.3 PyJWT==1.5.0 pyobjc-core==2.5.1 pyobjc-framework-Accounts==2.5.1 pyobjc-framework-AddressBook==2.5.1 pyobjc-framework-AppleScriptKit==2.5.1 pyobjc-framework-AppleScriptObjC==2.5.1 pyobjc-framework-Automator==2.5.1 pyobjc-framework-CFNetwork==2.5.1 pyobjc-framework-Cocoa==2.5.1 pyobjc-framework-Collaboration==2.5.1 pyobjc-framework-CoreData==2.5.1 pyobjc-framework-CoreLocation==2.5.1 pyobjc-framework-CoreText==2.5.1 pyobjc-framework-DictionaryServices==2.5.1 pyobjc-framework-EventKit==2.5.1 pyobjc-framework-ExceptionHandling==2.5.1 pyobjc-framework-FSEvents==2.5.1 pyobjc-framework-InputMethodKit==2.5.1 pyobjc-framework-InstallerPlugins==2.5.1 pyobjc-framework-InstantMessage==2.5.1 pyobjc-framework-LatentSemanticMapping==2.5.1 pyobjc-framework-LaunchServices==2.5.1 pyobjc-framework-Message==2.5.1 pyobjc-framework-OpenDirectory==2.5.1 pyobjc-framework-PreferencePanes==2.5.1 pyobjc-framework-PubSub==2.5.1 pyobjc-framework-QTKit==2.5.1 pyobjc-framework-Quartz==2.5.1 pyobjc-framework-ScreenSaver==2.5.1 pyobjc-framework-ScriptingBridge==2.5.1 pyobjc-framework-SearchKit==2.5.1 pyobjc-framework-ServiceManagement==2.5.1 pyobjc-framework-Social==2.5.1 pyobjc-framework-SyncServices==2.5.1 pyobjc-framework-SystemConfiguration==2.5.1 pyobjc-framework-WebKit==2.5.1 pyOpenSSL==0.13.1 pyparsing==2.2.0 python-dateutil==1.5 python-openid==2.2.5 pytz==2013.7 PyYAML==3.12 requests-oauthlib==0.8.0 scipy==0.13.0b1 semantic-version==2.5.0 simplejson==3.10.0 six==1.10.0 social-auth-app-django==1.2.0 social-auth-core==1.3.0 sqlparse==0.2.3 tabulate==0.7.5 termcolor==1.1.0 uritemplate==3.0.0 vboxapi==1.0 vine==1.1.3 virtualenv==15.1.0 wcwidth==0.1.7 websocket-client==0.40.0 xattr==0.6.4 zope.interface==4.1.1 -
How can I set up Django Crontab in Docker container?
I have in management/commands file myfile.py and I set it up in this way TIME_ZONE = 'UTC' CRONJOBS = [ ('21 22 * * *', 'django.core.management.call_command', ['myfile']), ] I have added django-crontab to the requirements.txt and 'django_crontab' in INSTALLED_APPS. This file should add data to the PostgreSQL database however it doesn't work. Any ideas why? Maybe I should use Celery scheduler instead? -
ValueError at /post/ No JSON object could be decoded
This is my json: { "documents": [ { "score": 0.5, "id": "1" } ], "errors": [] } I want to know how can I fetch 'score' without converting it into the dictionary?Because when I try to use json.loads it give me the following error: ValueError at /post/ No JSON object could be decoded This is the code which I am using. def GetSentiment(documents): "Gets the sentiments for a set of documents and returns the information." headers = {'Ocp-Apim-Subscription-Key': accessKey} conn = httplib.HTTPSConnection(uri) body = json.dumps(documents) conn.request("POST", path, body, headers) response = conn.getresponse() return response.read() documents = {'documents': [ {'id': '1', 'language': 'en', 'text': caption}, ]} result = GetSentiment(documents) resp_dict = json.loads(result) print resp_dict score = resp_dict["documents"][0]["score"] return score -
Django combine multiple querysets (same model)
I have list of querysets (all for same model): result_elms = [] if city_list: for city in city_list: result_elms.append(results.filter(address__city__icontains=city)) I know that I can use | operator to combine querysets from same model. But how can I apply it for all elements from result_elms list? -
A bug in 'Request and response objects' documentation?
In the first section of Request and response objects | Django ,documentation | Django It says: When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function. Each view is responsible for returning an HttpResponse object. Amongst the second sentence, 'the HttpRequest' in passing the HttpRequest as the first argument, its link refers to 'class HttpRequest[source]¶'. It is obvious that it's the object not the class are passed as the first argument. However, the HttpRequest is used instead of the object or the HttpRequest object. If a Bug, it' easy to debug, whereas I checked multiple versions of documentation, they stay the same. If not a Bug, how to explain it? -
django set img src statically using defaul
i am new to django i have two different img tags in my form like this (if user has saved profile image its image will be shown and if not a default image is shown) {% if widget.value.url %} <img src="{{ widget.value.url }}" alt="" id="profile_image" height="200px" width="200px"> {% else %} <img src="{% static 'utils/user.png' %}" id="profile_image" alt="" height="200px" width="200px"> {% endif %} now i want to merge these two using something like this <img src={{widget.value.url|default:{% static 'utils/user.png' %}}} id="profile_image" alt=""height="200px" width="200px"> but that has error and i have tried different types but none works how can i do that exactly? tnx -
How to ad something every third post django
how to put one banner in every post in this ads enter image description here -
How do I thoroughly delete an old image file when a user updates the form's imagefield?
I have two modelforms--one includes a standard ImageField and the other is an inlineformset of ImageFields. The normal standard ImageField renders on the page with the option for "Clear[ing]" while the inlineformset ImageFields render with an optional "Delete" tickbox. Either Clear or Delete will remove the image from the User's profile, but the actual image file will remain in storage, as well as the URL to the image. I am trying to remove all associations to the image once the User updates his Profile form by "clearing" or "deleting" the image. I found FieldFile.delete which I believe just requires me to call .delete() on the instance, but I'm not sure how to conditionally check whether the user is updating the form with the "delete" box or "clear" box ticked. Here are the two models containing the image fields: class Profile(models.Model): profile_photo = models.ImageField( upload_to=profile_photo_upload_loc, null=True, blank=True, verbose_name='Profile Image', ) class CredentialImage(models.Model): profile = models.ForeignKey(Profile, default=None, related_name='credentialimage') image = models.ImageField( upload_to=credential_photo_upload_loc, null=True, verbose_name='Image Credentials', ) The ModelForms: class ProfileUpdateForm(ModelForm): class Meta: model = Profile fields = [ "profile_photo", ] class CredentialImageForm(ModelForm): image = ImageField(required=False, widget=FileInput) class Meta: model = CredentialImage fields = ['image', ] CredentialImageFormSet = inlineformset_factory(Profile, CredentialImage, fields=('image', ), extra=2) … -
Request and response objects
In Django Documentation, Request and response objects | Django documentation | Django When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Amongst the sentence,creates an HttpRequest object is to create an instance. Is it more fancy to mention instance as object to perform as a professional programmer ? -
RelatedObjectDoesNotExist at /register_trainee/succesfull User has no profile
I was Trying to Extend User Model Using a One-To-One Link when I was trying to create a User Object This Error Popped Up here is my models.Py: class Profile(models.Model): phonenumber = models.OneToOneField(User,on_delete=models.CASCADE) and here is my views.py: def trainee_succesfull(request): new_trainee = User() d = request.POST new_trainee.first_name = d['firstname'] new_trainee.last_name = d['lastname'] new_trainee.profile.phonenumber = d['phonenumber'] new_trainee.password = d['password'] new_trainee.save() return render(request, 'trainee/message.html') I know that this question has been answered before but I could not fix the error by looking at the solutions. I would really appreciate It IF someone Can Help. -
Django allauth facebook login failed to redirect back when in an in-app-browser
Problem When in an in-app-browser, like Google Hangout, Telegram or LINE messenger, the user won't be redirected back to my website after a success login through facebook login dialog. It just shows a blank page. Everything works fine when using iPhone Safari app or Android Chrome app. Environment I am using Django==1.11.3 and django-allauth==0.34.0 (which utilizes Facebook Graph API v2.5), and here are my settings.py SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'SCOPE': ['email', 'public_profile', 'user_friends'], 'METHOD': 'js_sdk', 'LOCALE_FUNC': lambda request: 'zh_TW', 'VERIFIED_EMAIL': True } } Anyone experienced the same issue? -
Type object error while trying to inherit a form.Models base class with UserCreationForm base class
I was trying to inherit a form class object which uses forms.ModelForm into a different form class object which inherits from UserCreationForm. I undertand that when form models are been inherited, only one Meta supersedes. However, I still gave it a shot as that's the only way to achieve the business logic I am trying to arrive at. The codes below, pls kindly look through and suggest a work around: class AddressMixin(forms.ModelForm): class Meta: model = Subscriber fields = ['address_one', 'address_two', 'city', 'province'] widgets = { 'address_one':forms.TextInput(attrs={'class':'form-control'}), 'address_two':forms.TextInput(attrs={'class':'form-control'}), 'city': forms.TextInput(attrs={'class':'form-control'}), 'province': forms.TextInput(attrs={'class':'form-control'}), } class SubscriberForm(AddressMixin,UserCreationForm): first_name = forms.CharField(required=True, widget=forms.TextInput(attrs={'class':'form-control'})) last_name = forms.CharField(required=True, widget=forms.TextInput(attrs={'class':'form-control'})) email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'class':'form-control'})) username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'})) password1 = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})) password2 = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'type':'password'})) Heres the error I am getting, AttributeError at /subscribe/signup/ type object 'Subscriber' has no attribute 'USERNAME_FIELD' Again, I understand the error is refering to the subscriber model not having username as an attribute, because the AddresMixin Meta supersedes. However the AddressMixin model contains some business logic methods that needs to be submit during registeration, hence, it needs to pass through the same form. Any advice will help, while I keep trying to figure it out. -
Not redirecting after requests.post django
I'm currently using django rest framework api and I have a form to enter some api information in. I'd like to redirect after I submit my form while still POSTing the data to the API url using the requests library. However the HttpResponseRedirect isn't triggering a redirect for some reason Here is my views.py from rest_frame.requests import reverse import requests def entry_new(request): if request.method == 'POST': form = EntryForm(request.POST) if form.is_valid(): url = reverse("entry-list",request=request) r = requests.post(url, data=request.POST, cookies=request.COOKIES) ## THIS IS WHAT ISN'T FIRING - it goes back to entry_new's URL HttpResponseRedirect(reverse('index2')) else: form = EntryForm return render(request, 'entry_new.html', {'form': form}) class entry_ViewSet(viewsets.ModelViewSet): queryset = Entry.objects.all() serializer_class= EntrySerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def perform_create(self, serializer): serializer.partial = True serializer.save(created_by=self.request.user, modified_by=self.request.user, modified_date=datetime.now()) my serializers.py class EntrySerializer(serializers.ModelSerializer): created_by = serializers.ReadOnlyField(source='created_by.username') modified_by = serializers.ReadOnlyField(source='modified_by.username') class Meta: model = Entry fields = '__all__' my urls.py router = DefaultRouter() router.register(r'entry', views.entry_ViewSet, base_name="entry") urlpatterns = [ url(r'^index2/$',views.index_two, name='index2'), url(r'^cat_new/$', views.category_new, name='cat_new'), url(r'^entry_new/$', views.entry_new, name='entry_new'), url(r'^api/', include(router.urls)), ] -
Django Media Files Not Uploading to S3 Amazon from main site
I'm stuck and confused trying to get this work. I'm running Django on Heroku, using Python 2.7.14 using Django-Storages 1.6.5 trying to upload to Amazon S3. Deploying my site, I can use the Admin site in Django and upload a file to S3 with no problem. Using the non-admin site, I try to upload a media file and it doens't work. The file upload field is is denied by Amazon. Static works with no issue. Why would the Admin site be able to upload media files and the main site not be able to, when they use the same models?