Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - airports
when i tried to import my airport file in my django project, i get the following: INFO Downloading: airports.dat Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/init.py", line 350, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/init.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/airports/management/commands/airports.py", line 50, in handle with open(self.download(), 'rt') as f: File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/airports/management/commands/airports.py", line 64, in download response.raise_for_status() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/models.py", line 909, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat why is that happening? thanks a lot -
GET request stops the rest of the Java Script code from working
I have a home page that process the gender of the user by his/her name after clicking on a button and opens up ether a male chatbot page or female. This is the JavaScript code: function new_name(uname,new_G){ var user_info ={ user_name : uname, user_gender : new_G}; $.ajax({ type: "POST", url: "http://gadgetron.store/chat/user_api/", data: user_info, }); setTimeout(function(){ $.ajax({ type: 'GET', url: 'http://gadgetron.store/chatbot/run_python_new_name/',});}, 400);} function find_gender(){ var user_info = $.parseJSON($.ajax({ type: "GET", url: "http://gadgetron.store/chat/user_api/", dataType: "json", async: false}).responseText); var last = user_info[user_info.length - 1]; return last;} function gender_script(){ $.ajax({ type: 'GET', url: 'http://gadgetron.store/chatbot/run_python_gender/', });} function post(name){ var user_info ={ user_name : name}; $.ajax({ type: "POST", url: "http://gadgetron.store/chat/user_api/", data: user_info,});} $('.btn-xl').click(function(){ if(document.getElementById('radio01').checked == false && document.getElementById('radio02').checked == false ){ alert("--ارجوا الاختيار--"); } else{ var n = $('.message-input').val(); if ($.trim(n) == ''){ alert("--ارجوا كتابة اسمك الاول--"); document.getElementById('radio02').checked=false; document.getElementById('radio01').checked=false;} else{ var name = $('.message-input').val(); post(name); setTimeout(function(){gender_script();}, 500); setTimeout(function(){ var gender=find_gender(); if(gender.user_gender=="M"&&document.getElementById('radio01').checked){ window.open('http://gadgetron.store/male_chatbot'); $('.message-input').val(null); document.getElementById('radio01').checked=false;} else{ if(gender.user_gender=="M" && document.getElementById('radio02').checked){ alert("--اسمك يدل انك ذكر!! ارجوا اعادة الاختيار--"); document.getElementById('radio02').checked=false;} else{ if (gender.user_gender== "F" && document.getElementById('radio02').checked){ window.open('http://gadgetron.store/female_chatbot'); $('.message-input').val(null); document.getElementById('radio02').checked=false;} else { if (gender.user_gender== "F" && document.getElementById('radio01').checked){ alert("--اسمك يدل انكِ انثى!! ارجوا اعادة الاختيار--"); document.getElementById('radio01').checked=false;} else{ if(gender = "N" && document.getElementById('radio01').checked){ alert("--اسمك جديد !! يبدو انه مذكر--"); var new_gender= "M"; new_name(name,new_gender); … -
Django view model annotate error
I have a view defined as a Django model, database engine Postgres 9.5. When I try to query using annotations on it, I get the following error: ProgrammingError: column "booklatestpublish.book_id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT "booklatestpublish"."id", "booklatestpubl... Django only includes the primary key in a GROUP BY condition, and although the column is in my case unique on the view, I have no way to mark it as such. I need a way to explicitly include the entire list of columns in the GROUP BY clause. I have tried distinct(*list_of_fields), but it throws an error "it's not supported". The solution which works is adding values before the annotations, but this will return tuples and I need the results passed as objects (this is just the get_queryset method on a DRF view). The last solution would be to create a custom view, but it would involve extra work and I was wondering if there any options I missed. Below is a equivalent of my situation and the queries executed in the database. Thank you in advance. class Published(models.Model): book = models.ForeignKey(Book) publish_date = models.DateTimeField() class BookLatestPublish(BaseViewModel): """ create view … -
coding backend of an iOS app using Windows
Can I use Windows10 for developing backend for an iOS app I do have the frontend of an iOS which is obviously coded in objective-c. How is Django for developing the backend for the iOS mobile app. If I use Django for backend on Windows then the frontend won't work so, is there anyway that I can code the backend on Windows10 for iOS -
Heroku terminates worker performing http chunking (streaming)
According to the heroku Docs, it allows long responses as long as data is being sent every 55sec. Heroku supports HTTP 1.1 features such as long-polling and streaming responses. An application has an initial 30 second window to respond with a single byte back to the client. However, each byte transmitted thereafter (either received from the client or sent by your application) resets a rolling 55 second window. If no >data is sent during the 55 second window, the connection will be terminated. My the worker app, which is returning a StreamingHttpResponse every few seconds, is being terminated after exactly 30sec app[web.1]: [2017-03-24 16:26:24 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:24) app[web.1]: [2017-03-24 16:26:24 +0000] [24] [INFO] Worker exiting (pid: 24) heroku[router]: sock=backend at=error code=H18 desc="Server Request Interrupted" method=POST path="/createRepos" host=managegithub.herokuapp.com request_id=96d4d31e-f9ff-46c0-b727-04ca0dfae2a3 fwd="89.127.160.122" dyno=web.1 connect=6ms service=30690ms status=503 bytes= protocol=https app[web.1]: [2017-03-24 16:26:25 +0000] [31] [INFO] Booting worker with pid: 31 Why is the worked terminated while it is continually responding with data every few seconds? -
Django sitemap : 'module' object has no attribute 'get_urls'
getting this error that's stopping me from progressing. Followed standard setup for a sitemap and got the following error: AttributeError at /sitemap.xml 'module' object has no attribute 'get_urls' my urls.py: from django.conf.urls import url, include from django.contrib import admin from django.contrib.sitemaps.views import sitemap import blog.views as PostSiteMap sitemaps ={ 'post' : PostSiteMap } urlpatterns = [ url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap') ] views.py: class PostsSiteMap(Sitemap): changefreq = "daily" priority = 1.0 def items(self): return Post.objects.all() def lastmod(self, obj): return obj.date def location(self, item): return reverse(item) Post models.py: class Post(models.Model): title = models.CharField(max_length = 140) body = RichTextUploadingField() date = models.DateTimeField() tags = models.ManyToManyField('Tags') thumbnail = models.ImageField(upload_to="images/", null = False , default='images/place.png', blank = True, width_field="width_field", height_field="height_field") height_field = models.IntegerField(default = 0, null = True, blank = True) width_field = models.IntegerField(default = 0, null = True, blank = True) def __str__(self): return self.title def recent_posts(self): d = datetime.utcnow().replace(tzinfo=pytz.UTC) - timedelta(days=30) if self.date > d: return True else: return False def get_absolute_url(self): return "/blog/%i/" % self.pk anybody have any ideas why? thanks! -
Django REST framework: deserializing an existing foreign key fails
I have Foo objects that are "owned" by an Organization. I get the current Organization from the logged-in User in my request handler: models.py: class Organization(models.Model): name = models.CharField(max_length=255) class Foo(models.Model): ... some other fields ... organization = models.ForeignKey(Organization, on_delete=models.CASCADE) serializers.py: class FooSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) organization = OrganizationSerializer(read_only=True) """ Create and return a new instance, given the validated data """ def create(self, validatedData): return OverlayDesign.objects.create(**validatedData) """ Update and return an existing instance, given the validated_data """ def update(self, instance, validatedData): instance.organization = validatedData.get('organization', instance.organization) instance.save() return instance views.py: def createFoo(request): data = JSONParser().parse(request) # Get the organization of the logged-in user data["organization"] = OrganizationSerializer(request.user.account.organization).data serializer = FooSerializer(data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status=201) return JSONErrorResponse(serializer.errors, status=400) When I create a new Foo, I want it to be owned by the current Organization. The problem is that I don't understand why the Organization is not deserialized? No matter what I do I just get: django.db.utils.IntegrityError: null value in column "organization_id" violates not-null constraint How should I deliver the current Organization to the FooSerializer ? -
simple django unit tests
i am trying to make unit test . my unit test is not working now.... plz help me. this is my test.py from django.test import TestCase from django.contrib.staticfiles.testing import StaticLiveServerTestCase from django.core.urlresolvers import reverse class SimpleTest(TestCase): def setUp(TestCase): MyUser.objects.create(email="hsjo12@student.com", username="DAEN",password="123456789", Nationalityty= "Albania", Mother_language= "Albanian", Wish_language= "English", Profile_image="profile_images/a2.jpg", status_message="Hello I am David") def test_secure_page(TestCase): self.client.login(email="hsjo12@student.com", password='123456789') response = self.client.get('/LanguageExchange/') user = MyUser.objects.get(email="hsjo12@student.com") self.assertEqual(response.context['email'], "hsjo12@student.com") i am trying to make unit test . my unit test is not working now.... plz help me. this is my view of login.. def user_login(request): if request.method == 'POST': username = request.POST.get('email') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('register')) else: messages.warning(request,"Make you sure to Check ID and Password", extra_tags='alert') return HttpResponseRedirect(reverse('register')) else: messages.warning(request,"Make you sure to Check ID and Password", extra_tags='alert') return HttpResponseRedirect(reverse('register')) else: messages.warning(request,"Make you sure to Check ID and Password", extra_tags='alert') return HttpResponseRedirect(reverse('register')) -
is it possible to pass data from multiple models to one view and filter data by id in django
this is image of template where data should display in the image i managed to display student information from another model but the below circled area should display data from another model and the data varies from student by student. the model contains subjects and each student has different subjects according to their department . i tried foreignkey method but had no luck.please help me with this i don't know how to explain this more specific. -
updating ImageField with new image using python function
I have been trying to create an image editor app using django since on screen controls are not possible in django templates I have started using function in views.py to do the same but I'm stuck at updating ImageField database with new image my views.py file is def padding(request, meme_id): meme = Meme.objects.filter(id = meme_id) if not meme: return HttpResponse("404 meme not found") else: old_im = meme.photo old_size = old_im.size new_size = (old_size[0],old_size[1]+300) new_im = Image.new("RGB", new_size) new_im.paste(old_im,((new_size[0]-old_size[0])/2,new_size[1]- old_size[1])/2) # here i have to update meme.photo with new new_im -
IndexError: cannot do a non-empty take from an empty axes. df = df.reset_index()
getting following error when I was doing: df = df.reset_index() IndexError: cannot do a non-empty take from an empty axes. My Dataframe has multi index and has some columns with Nan values. Please suggest. Thanks in advance. -
sorl_thumbnail doesn't work
When i'm trying to add thumbnail anywhere on my site(most importantly to my post template) I'm getting the following errors: Error during template rendering In template /home/cruel/PycharmProjects/silverak/ak47/templates/ak47/frontsite.html, error at line 0 'Settings' object has no attribute 'TEMPLATE_DEBUG' ... sqlite3.OperationalError: no such table: thumbnail_kvstore template below: {% load thumbnail %} <div class="jumbotron"> <h2 class="text-center"> <a href="{{ post.get_absolute_url }} " class="center-block"> {{ post.title }} <div class="image-container center-block"> {% if post.image %} {% thumbnail post.image 800 as im %} <img src="{{ im.url }}" class="image"> {% endthumbnail %} {% endif %} </div> </a> </h2> </div> -
DRF: data structure in serializer or view?
Given the models below, I've been trying to figure out how to return the data structure I have in mind (also below) using Django REST Framework. How would this be accomplished within a serializer, or does such a data structure need to be built within a view using traditional Django-style queries? About Basically, a word is created, users submit definitions for that word, and vote on each definition (funniest, saddest, wtf, etc.) models.py from django.db import models class Word(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) word = models.CharField() timestamp = models.DateTimeField() class Definition(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) word = models.ForeignKey(Word, on_delete=models.CASCADE) definition = models.CharField() timestamp = models.DateTimeField() class Vote_category(models.Model): category = models.CharField() class Vote_history(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) definition = models.ForeignKey(Definition, on_delete=models.CASCADE) timestamp = models.DateTimeField() vote = models.ForeignKey(Vote_category, on_delete=models.CASCADE) Expected Query Result Structure word: 'hello', definitions: { { user: 'alice', definition: 'an expression of greeting', votes: { funny: 3, sad: 1, wtf: 7 }, votes_total: 11 }, etc... } Thanks! -
Django static web page(flatpages), SEO, Search Engine
I'm a newbie of program. I'm using django to make a website. It's closing finished and exciting. But I have some questions. How to generate static web pages from dynamic pages, I mean make pages which have only HTML content,not includes any dynamic tag. Is it use flatpages app of django? Because html content has friendly for search engine. If i use flatepages app to generate pages, Is it friendly SEO of search engine? How do I let my pages index into google,bing,etc and show right content or else rather than django tags.?? Thank you -
handle multiple checks effectively
I am developing a feature where the user has to request for invitation if he/she wants to sign up on the site. When the request is accepted by the admin, the user gets to sign up, otherwise it shows them an error saying they are not invited at this time, and saves a email so we can follow up with him/her and if he again try to signup with that email, the same error should be shown. To be generic, I used the condition INVITE_MODE = True in settings, so if we disable the invitation feature using INVITE_MODE=False, all the users should get to sign up. List of checks in point 1) Check if email exists or not in invitation(if a user has requested for invitation or not)- if email exists but is not approved yet show error "Your invitation is waiting for approval" 2) If email does not exist, and user submits multiple time with same email, show 'You have been added to the invite list' and save to the invitation database 3) what else you will consider(I might have miss something for better design for end user) Here is my signup form and I am using Django allauth … -
How to invoke a Django views.py function on button click without redirecting to a page?
I am working on bookmarking of articles. I want to add the article in bookmarks when a button Add To Bookmarkis clicked. Using Django, the conventional way of doing it would be redirecting to the bookmarks page by passing the slug of the article, and handling the information in the views.py. But I don't want to redirect to the bookmark page, instead want to add it in the article page itself. How can I invoke a function that handles the bookmark information on button click? -
Django customize registration for custom user model
I am using Django-rest-auth for authentication and django-allauth for registration. I modified user model to have my custom user model as following: class CustomUser(models.Model): #Field for refering the default user user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) age = models.IntegerField(null=True) profession= models.CharField(max_length=50) While registering I want to ask user to fill out all the fields (i.e. First name, Last name, Age, Profession, Email and Password). So far I have a Register serializer that will ask First and last name along with Email (I am doing Email based registration and not with Username): class RegisterSerializer(serializers.Serializer): email = serializers.EmailField(required=allauth_settings.EMAIL_REQUIRED) first_name = serializers.CharField(required=True, write_only=True) last_name = serializers.CharField(required=True, write_only=True) password1 = serializers.CharField(required=True, write_only=True) password2 = serializers.CharField(required=True, write_only=True) def validate_email(self, email): email = get_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( _("A user is already registered with this e-mail address.")) return email def validate_password1(self, password): return get_adapter().clean_password(password) def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError( _("The two password fields didn't match.")) return data def get_cleaned_data(self): return { 'first_name': self.validated_data.get('first_name', ''), 'last_name': self.validated_data.get('last_name', ''), 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', ''), } def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) setup_user_email(request, user, []) user.save() return user Which I register in … -
Writing Object.get which pulls data based off under input
Trying to create an input box for my users to type their name in and retrieve their results from a questionnaire in the database done earlier. I know I'm to use Question.objects.get (Question is my database name) But I'm not sure how to create so that it works off what the user inputs only how to filter results. my Models.py is below and would like this to work off last_name in my code. class Question(models.Model): first_name = models.CharField(max_length=15) last_name = models.CharField (max_length=15, primary_key=True) Thanks for the help -
Django CSRF Token Missing Only in Production
I am getting a missing CSRF_Token error that only occurs in production mode on my server. However everything works great when I am running it from my computer terminal using the runserver command. I've read through many of the other questions pertaining to this with no luck. It seems that my case is slightly different than others, since it works locally but not in production. I get the error when submitting an Ajax form that submits to the "submit" in views.py. Does anybody know what could be causing this? Also, looking at my cookies in Production mode, the CSRF_Token is not even there to begin with. Locally it is. Thanks for any help. Here is my views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request, 'index.html') def submit(request): #Receive Request inputone = request.POST['randominfo'] inputtwo = request.POST['randominfo2'] #Some more code here that setups response. #Deleted since Im posting to StackOverflow return response Code Pertaining to the Ajax Submit $(function () { $.ajaxSetup({ headers: { "X-CSRFToken": getCookie("csrftoken") } }); }); function getCookie(c_name) { if (document.cookie.length > 0) { c_start = document.cookie.indexOf(c_name + "="); if (c_start != -1) { c_start = c_start + c_name.length + 1; c_end = document.cookie.indexOf(";", … -
Improper User Redirect Django
When the user logs in, it doesn't redirect them back to the list page (homepage), but rather stays on the login page. When the user logs in the url is http://127.0.0.1:8000/login/ After login the url is: http://127.0.0.1:8000/login/aircraft_list.html How do I redirect them back to list page? def login_view(request): title = "Login" form = login_form(request.POST or None) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) login(request, user) return HttpResponseRedirect("aircraft_list.html") return render(request, "account/form.html", {"form":form, "title":title}) -
Django unit test celery
In django application I have a view wich runs the Celery task. Inside the celery task I do some actions with database using Django ORM. I call my test case something like this: class MyViewTestCase(APITestCase): def test_my_view(self): self.client.post('url',data) my test case does all orm manupulations inside the test DB. But inside celery task all orm actions are happening on product database. I use celery 4. Is there option to make celery work with test django database? -
How do I hide a folder from Amazon S3?
I'm looking to set up Amazon S3 with my Wagtail site, and I'm having difficulty finding a way to make Amazon S3 ignore the node_modules folder within the static folder that I am uploading. The following page explains that you can use something like this to make it ignore a directory: ignore: - ^backup/ http://docs.aws.amazon.com/AWSImportExport/latest/DG/IgnoreTips.html Is that the only thing that has to go in your file? What should the file be called and where does this file go within your file structure? I couldn't see anything about it on the page. I don't feel like their documentation is that great. -
Django : ModelForm with conditions
I'm trying to create a form variable. As default Player have the level 0 and he can just change is name. Later when he is level 1, he can change is name and is avatar. When he is level 3, he can change is name, is avatar and is job. Etc... Models.py: class Player(models.Model): level = models.SmallIntegerField(default=0) name = models.CharField(max_length=50) avatar = models.URLField(default='http://default-picture.com/01.png') job = models.TextField(null=True) Fomrs.py: class ProfileForm(forms.ModelForm): class Meta: model = Player fields = ['name', 'avatar', 'job'] widgets = { 'name': forms.TextInput(), 'avatar': forms.TextInput(), 'job': forms.Textarea(), } Views.py: def game(request, id): user = get_object_or_404(Player, id=id) if request.method == 'POST': form = ProfileForm(request.POST, instance=user) if form.is_valid(): form.save() return HttpResponse('Success') else: form = ProfileForm(instance=user) return render(request, "page/template.html", {'form': form}) Template.html: {{ form }} It's possible to add condition for the render of the form before send it to the render engime ? Or I need to do it in my Template with conditions ? I just when to allow the instanced object to have more or less positibilies in terms of one of these parameters (in the exemple is the level of the player). -
error PYTHON_EGG_CACHE while uploading django
I am trying to upload my django project live...and i am getting this error continously pkg_resources.ExtractionError: Can't extract file(s) to egg cache The following error occurred while trying to extract file(s) to the Python egg cache: [Errno 13] Permission denied: '/opt/bitnami/.tmp/simplejson-2.0.9-py2.7-linux-x86_64.egg-tmp/simplejson/tmpuYcIYB.$extract' The Python egg cache directory is currently set to: /opt/bitnami/.tmp Perhaps your account does not have write access to this directory? You can change the cache directory by setting the PYTHON_EGG_CACHE environment variable to point to an accessible directory. -
Django - Update one field after form submitting
I'm looking for update my Django form after user submission. I filled my BirthCertificateForm with some data and I just have one field which is not filled : social_number. Why ? Because after submitting form, I created a unique social number from data form. So, I would like to update my previous form and add this social number according to the good field and validate it. My models.py file looks like : class BirthCertificate(models.Model): lastname = models.CharField(max_length=30, null=False, verbose_name='Nom de famille') firstname = models.CharField(max_length=30, null=False, verbose_name='Prénom(s)') sex = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe') birthday = models.DateField(null=False, verbose_name='Date de naissance') birthhour = models.TimeField(null=True, verbose_name='Heure de naissance') birthcity = models.CharField(max_length=30, null=False, verbose_name='Ville de naissance') birthcountry = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance') fk_parent1 = models.ForeignKey(Person, related_name='ID_Parent1', verbose_name='ID parent1', null=False) fk_parent2 = models.ForeignKey(Person, related_name='ID_Parent2', verbose_name='ID parent2', null=False) mairie = models.CharField(max_length=30, null=False, verbose_name='Mairie') social_number = models.CharField(max_length=30, null=True, verbose_name='numero social') created = models.DateTimeField(auto_now_add=True) And my views.py file have 2 functions : First function : # First function which let to fill the form with some conditions / restrictions @login_required def BirthCertificate_Form(request) : # Fonction permettant de créer le formulaire Acte de Naissance et le remplissage query_lastname_father = request.GET.get('lastname_father') query_lastname_mother = request.GET.get('lastname_mother') if request.method == 'POST': form = …