Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Method Not Allowed (POST)
In views: def article_add(request): print request.user, " is adding an article" if request.method == "POST": web_url = request.POST['web_url'] Uploadarticle(web_url) return redirect('myapp:index') In html: <form class="navbar-form navbar-right" role="form" method="post" action="{% url 'myapp:article_add' %}" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <div class="col-sm-10"> <input id="article_url" name="web_url" type="text"> </div> </div> <button type="submit" class="btn btn-default"> + </button> </form> In url.py: url(r'^$', views.article_add, name='article_add') What i'm trying to do here is to pass the url value through html to view, call the function to upload the database, redirect the user to the same home page as refresh then the newly added item will show up. Somehow everytime I submit I got a blank page, in terminal I got an errors says: Method Not Allowed (POST): / "POST / HTTP/1.1" 405 0 -
Django. Not properly delete a record
I'm having a problem hope you could help me please. I got this models: MODELS = ( ('A', 'A'), ('B', 'B'), ) class person(models.Model): nombre = models.CharField(max_length=128) model = models.CharField(max_length=128,choices=MODELS, default=True) def __str__(self): return self.nombre class person_A(models.Model): person = models.ForeignKey(person, on_delete=models.PROTECT, null=True) hobbies = models.CharField(max_length=40, default='') def __str__(self): return self.person.nombre class person_B(models.Model): person = models.ForeignKey(person, on_delete=models.PROTECT, null=True) age = models.IntegerField(default=10) def __str__(self): return self.person.nombre As you can see I have person A, Person B which will be saved in my database. Here's my view: def get_person(request): titulo = 'Person' qs_a = person_A.objects.all() qs_b = person_B.objects.all() qs = chain(qs_b,qs_a) form = person_aForm(request.POST or None) form2 = personForm(request.POST or None) form4 = person_bForm(request.POST or None) context = { "qs_a": qs_a, "qs_b":qs_b, "qs":qs, "form2":form2, "form":form, "form4":form4, "titulo":titulo, } form2_valid = form2.is_valid() form_valid = form.is_valid() form4_valid = form4.is_valid() if form2_valid: person = form2.save() if form_valid: person_a = form.save(commit=False) person_a.person = person person_a.save() messages.success(request, 'Se ha guardado satisfactoriamente') return redirect("get_person") if form4_valid: person_b = form4.save(commit=False) person_b.person = person person_b.save() messages.success(request, 'Se ha guardado satisfactoriamente') return redirect("get_person") return render(request, "person.html", context) Here as you can see is being saved my form for Person A or Person B. Here's my delete function: def delete_person(request,id): try: qs = … -
How to extend Django User model with two different profiles?
Is it possible to create two different profiles and have them both extend Django User Model. I am trying to create a student profile and a teacher profile, how should I go about doing this? -
Django: Return to template along with template variables
I am using Django to build a student-teacher portal. I have two groups of users - teachers and students. If user is a teacher, i need to provide a different template (a form for selecting student's registration number). I followed this link to do the same. Here are the code snippets: home.html {% if is_teacher %} <p style="color:blue; text-align:center; font-size:160%"><b>Course taken: <span style="color:green"><a href="course/">IT000</a></span></b></p> <form action="/" method="post" align="center"> {% csrf_token %} <div align="center">{{ form }}</div> <input type="submit" value="Get student's results!" class="btn btn-primary" style="margin-top:10px"/> </form> {% else %} <p style="color:blue; text-align:center; font-size:160%"><b>Performance for the subject <span style="color:green"><a href="course/">IT000</a></span> is shown below.</b></p> {% endif %} views.py @login_required(login_url="login/") def home(request): is_teacher = request.user.groups.filter(name='teachers').exists() if is_teacher: if request.method == 'POST': form = Regno(request.POST) if form.is_valid(): selected_reg = Student.objects.filter(regno=request.POST.get('regno')) return render(request, 'home.html',{'selected_reg': selected_reg,'form':form}) else: form = Regno() return render(request, 'home.html', {'form': form,'user':request.user,'is_teacher':is_teacher}) else: selected_reg = Student.objects.filter(regno=request.user) return render(request, 'home.html', {'user':request.user,'is_teacher':is_teacher,'selected_reg':selected_reg}) Here, Regno is a Form for the teacher to enter student's registration no. When a teacher initially logs in, he is displayed the form. However, after he submits the form, it is not displaying the form. It executes the {% else %} part of the template. How do I make sure the is_teacher template variable … -
Django Celery Beat Periodic Tasks
I am trying to run a periodic task with django celery, and it is dynamically added by users using custom arguments. I have the following code to start the task. I only want it to run once as it takes a while for it to set up, and I have an infinite while loop that constantly checks for changes on a website. schedule, created = IntervalSchedule.objects.get_or_create(every=100,period=IntervalSchedule.DAYS,) PeriodicTask.objects.create(interval=schedule, enabled=True, name=name,task='scanner.tasks.texting', args=json.dumps([phone_number, carrier_address]),) The problem is that when I create the task, it is not started and needs to wait for the interval before starting. Is it possible to start the tasks when the object is created? Otherwise, I could change the interval to just a second to start immediately. The problem with this implementation is that it will start the thread every second, even though I just want to run it once, and let it keep running in the background. Does anyone have a solution to this? -
'User' object has no attribute '__getitem__' on create object
Trying to insert data into a python model with a foreign key using the create object and getting a 'User' object has no attribute 'getitem' models.py from future import unicode_literals from django.db import models from ..loginRegistration_app.models import User class PostManager(models.Manager): error_list = [] def post_in(self, postData, user_id): if len(postData['post']) < 1: context = {'status':0} return context else: curr_user = User.objects.get(id = user_id) # print curr_user.last_name self.create(secrets = postData['post'], users_id = curr_user['id']) class Like(models.Model): like = models.BooleanField() users = models.ForeignKey(User, related_name = 'user_likes') created_at = models.DateTimeField(auto_now_add = True) upated_at = models.DateTimeField(auto_now = True) class Secret(models.Model): secret = models.TextField(max_length = 1000) likes = models.ForeignKey(Like, related_name = 'all_likes') users = models.ForeignKey(User, related_name = 'user_secrets') created_at = models.DateTimeField(auto_now_add = True) upated_at = models.DateTimeField(auto_now = True) objects = PostManager() views.py from django.shortcuts import render, redirect from .models import Secret from django.contrib import messages def index(request): if 'user_id' not in request.session: return redirect('main:home') # put query to display most recent secrets return render(request, 'dojo_secrets_app/index.html') def post_it(request): post_this = Secret.objects.post_in(request.POST, request.session['user_id']) return redirect('secrets:home') error: TypeError at /secrets/post_it 'User' object has no attribute '__getitem__' self.create(secrets = postData['post'], users_id = curr_user['id']) -
Retriving object from a manytomany field
I am still trying to wrap my head around the ORM. I am trying to set this up so that a user can follow many networks. I set the modal up as a many to many field. Now when a user writes a post he can pick from one of the "networks" he follows to post it to. How would I return all the networks the user follows? I'm looking through the documentation but it just isn't clicking. The model is below and I am using the Django authentication. class SubNetwork(models.Model): sub_name = models.CharField(max_length=40) followers = models.ManyToManyField(User) def __str__(self): return self.sub_name def number_of_followers(self): self.number = self.followers.count() return self.number def number_of_posts(self): self.total_posts = self.fishingreport_set.count() return self.total_posts -
How to export a HTML view page as ppt using Django ,angularJS and BIRT.?
I have tried pptx, but my college said specific to go with BIRT. But its a jar file and i am using Django and angularJS so not sure how to bind BIRT with Django. -
Setting environment variables in Django site on Nginx server
I have a Django site on an Ubuntu VPS running Nginx. I wanted to secure my postgres password and Django secret key and followed this guide to do so: https://ultimatedjango.com/learn-django/lessons/handling-sensitive-keys/ afterwards nothing seemed to break on the site and I could still make changes and view everything so I assumed it had all worked. I have since then noticed that when I first login to the server I get this warning about the Django secret key added in my .bashrc file: -bash: /home/david/.bashrc: line 19: syntax error near unexpected token `)' -bash: /home/david/.bashrc: line 19: `export SECRET_KEY=2nv#wlp)3h-p32y-hidden-rest-of-key-for-secruity' so I guess this is happening because I didn't add the key as a string? If so why is the site still running esp. when I didnt add the postgres password as a string either? Also if I try to run any kind of migrations now I get this message: File "/home/david/myproj/myproj/settings.py", line 21, in <module> CRMEASY_DB_PASS = get_env_variable('CRMEASY_DB_PASS') NameError: name 'get_env_variable' is not defined thanks -
Why python dict is parsed in specific way in django template
I am creating a dict and return to django template parsing = dict() for idx,title in enumerate(titles): link = parsing.setdefault(idx, {}) link.setdefault('title', title) link.setdefault('image', title) # print(link['image']) return render(request, "blog/intro.html", {'parsing':parsing}) But can't understand why only this code works in template. Only with 1. Why? {% for el in parsing.items %} {{ el.1.title }} {% endfor%} -
Listing ForeignKey associated instances within template (queryset within a queryset)
I have a site which catalogs local hikes, and users can log that they have been on the hike. I have a search page which contains the hikes, and one of the fields I'm trying to display is a list of all the people who have been on the hike. I've got this figured out within the individual detail page of the hike, but can't figure out how to create a new queryset within the queryset which is printing the hikes, in order to display this info on a search page. Here's some code: models.py: class Hike(models.Model): ... class UserLog(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) hike = models.ForeignKey(Hike, on_delete=models.CASCADE) views.py: def hike_list(request): qs = Hike.objects.all() ... some other filters here ?-->users = UserLog.objects.filter(id=qs.id) template: {% for qs in qs %} {{ hike.name }}{{ hike.other_details_and_stuff }} ?----> {% for users in hikes %}{{ user.name }}{% endfor %} {% endfor %} Here's the working code within the individual hike's detail page: views.py: def hike_detail (request, slug) users = UserLog.objects.filter(climb__slug=slug) How do I call on the slug from each individual item in the queryset, then run a queryset on that? -
Django filter __in returns first match instead of all
I have a model Location with a field tag: class Location(models.Model): tag = models.CharField(max_length=10, unique=True) In my code I have a list of tags read in from a file: in_tags = row['tags'].split(',') which creates in_tags having the value ['GB_31', 'GB_32', 'GB_33'] My query looks like this: location_set = models.Location.objects.filter(tag__in=location_list) It's returning a QuerySet with only one location object, the one with tag='GB_31'. I've tried removing the first element, in case the other tags were missing or malformed, and it again returned only the first match. I went into the database and executed the query SELECT * FROM `location` WHERE `tag` IN ('GB_31', 'GB_32'); It returned both locations, as expected. I'm running django 9.2 with python 3.4.4 -
API POST method returns newly created object through DRF'S Browsable API html form but does not work when posted via RAW JSON
I have a ListCreate Generic view that handles listing and creating new ad data. Ad data is successfully created when submitted through DRF's Browsable API HTML Form. But when I try to submit it as a raw JSON format. It does not respond, not even returns an error. class AdListView(ListCreateAPIView): queryset = Ad.objects.all() def get_serializer_class(self): if self.request.method == 'POST': return AdCreateSerializer return AdListSerializer # auto save the owner of the newly created Ad def perform_create(self, serializer): user = self.request.user person = Person.objects.get(id=user.id) serializer.save(person=person) And here are my serializers. class AdListSerializer(serializers.ModelSerializer): class Meta: model = Ad fields = ('id', 'person', 'title', 'price', 'description') class AdCreateSerializer(serializers.ModelSerializer): def create(self, validated_data): print(validated_data) print(self.context['request'].user) return Ad(**validated_data) class Meta: model = Ad fields = '__all__' Please help me fix this. -
Django Matching query does not exist
I cant figure out what is happening here. I want to retrieve an object then add a user to myobject.followers. But I can't get it to work. I am pretty new to Django. What is happening here? models.py class SubNetwork(models.Model): sub_name = models.CharField(max_length=40) followers = models.ManyToManyField(User) def __str__(self): return self.sub_name def number_of_followers(self): self.number = self.followers.count() return self.number def number_of_posts(self): self.total_posts = self.fishingreport_set.count() return self.total_posts views.py def follow(request, pk): if request.method == 'POST': report = SubNetwork.objects.get(id=pk) return redirect('sub/subs/') urls.py urlpatterns = [ url(r'^subs/', views.all_subs, name="all_subs"), url(r'^(?P<sub_name>\w+)', views.sub, name='sub_name'), url(r'^follow/(?P<pk>[0-9]+)', views.follow, name='follow'), ] html <form method="POST" action="{% url 'subnetworks:follow' sub.id %}"> {% csrf_token %} <input type="submit" value="UP"> </form> error Environment: Request Method: POST Request URL: http://127.0.0.1:8000/sub/follow/1 Django Version: 1.10.5 Python Version: 3.6.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'TheFishNetwork', 'accounts', 'subnetwork', 'posts', 'markdownify'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/swapnil/python_envs/fishenv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/home/swapnil/python_envs/fishenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/swapnil/python_envs/fishenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/swapnil/PycharmProjects/fishnetwork/subnetwork/views.py" in sub 13. subnetwork = SubNetwork.objects.get(sub_name=sub_name) File "/home/swapnil/python_envs/fishenv/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method 85. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/swapnil/python_envs/fishenv/lib/python3.6/site-packages/django/db/models/query.py" in get 385. self.model._meta.object_name Exception Type: DoesNotExist at /sub/follow/1 Exception … -
Django counting one to many relationship
So i have two tables, Post and Category Code: model.py class Category(models.Model): category = models.CharField(max_length=100) def __str__(self): return self.category class Post(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=40) category = models.ForeignKey(Category) content = models.TextField() created_date = models.DateTimeField(default=timezone.now) class Meta: ordering = ['-created_date'] def __str__(self): return self.title + ' - ' + str(self.created_date.date()) And I want to implement category list in template. For example I have few categories Sports(2) 2-number of how many posts are within sports category template code: <h3>Categories</h3> <ul class="nav navbar-stacked"> {% for category in categories %} <li><a href="#">{{ category }}<span class="pull-right">( {{ **post.category.count** }} )</span></a></li> {% endfor %} </ul> How can I achieve this? -
how to implement custom script into django in admin page? python
I know that I am allowed to add customized JS into django admin BUT can I just add something like <script>var a = 'b';</script> into django admin? Now I am using something like meta Media: js = ['/site_media/choice.js'] the reason I dont want to use the above is, I have a script which is like the above and the script will run differently in different admin model pages. for example in the above choice.js I have a function run() in model admin A I will want this page to use run('abc') but in model admin B I want this page to use run('eee') if adding js instead of just typing out script, that means I will have to create quite a lot js Can someone give me a hand of this? (currently using django 1.10.5) -
create group for device in django-rest-framework
There is a relation of one-to-many between Device and Device Group. A device can be on only one group(same device cannot be on multiple group) and a group can have multiple devices. I have designed the model according to the relation. How can i create a group for device? class Device(BaseDevice): description = models.TextField(blank=True, null=True) device_group = models.ForeignKey('DeviceGroup', null=True, blank=True) class DeviceGroup(models.Model): name = models.CharField(max_length=250, blank=False, null=False) serializers class DeviceGroupSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField() class Meta: model = DeviceGroup fields = ('name',) class DeviceSerializer(serializers.ModelSerializer): id = serializers.UUIDField(source='token', format='hex', read_only=True) device_group = DeviceGroupSerializer(required=False) class Meta: model = Device fields = ('id', 'name', 'description', 'ios','device_group') -
read Many to many relation field during save
i'm trying to make some operations during model save with many-to-many relation field of the same model class Article(models.Model): name = models.CharField(max_length=50, default="New article") text = models.CharField(max_length=200) post_to = models.ManyToManyField(Account) def __unicode__(self): return self.name def save(self, *args, **kwargs): super(Article, self).save(*args, **kwargs) print self.post_to.all() instead of print self.post_to.all() could be some function to work with self.post_to.all() query set the problem is that when i create new article and press SAVE button the query set is empty <QuerySet []> after that i enter into this article and press SAVE again the query set is not empty <QuerySet [<Account: Template>]> I think that problem in time when object is saved but i can't get how to read this field during creation. -
How to serve static files to AWS when deploying Django app (`python manage.py collectstatic` didn't work)?
Yesterday, I created this post: DjangoRestFramework browsable api looks different locally vs when deployed on server? Basically, when I did python manage.py runserver, this showed up: But after I deployed it to AWS (eb deploy), this is what I see when I access the site: The answer to the post above mentioned that it is because my static files were missing. So I searched how to deploy static files on AWS and came across this tutorial: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html#python-django-update-app Under the "Create a Site Administrator" section, it mentions that in order to serve static files, I must first define STATIC_ROOT in settings.py (so I did: STATIC_ROOT = os.path.join(BASE_DIR, "ebdjangoapp/static/")) and then I did eb deploy. However, the site still looks the same as the first image (without static files). How come the static files still aren't showing up? Note, I searched around and came across this post: Django app deployment not loading static files and the answer says: "You then need to serve settings.STATIC_ROOT at settings.STATIC_URL via your web server of choice, very commonly nginx as a reverse proxy behind your Apache-mod_wsgi app server." But I have no idea how web servers (nginx, reverse proxy, Apache-mod_wsgi) works. I have a Django app … -
How to install packages to docker's python?
How to install packages to docker's python? For example, I need lmxl. Inside django application in docker I run pip install lxml and terminal responses that requirement is already satisfied (because it's installed in OS X python 2.7 packages), but in fact it's not installed in docker's python packages. So, how to apply pip install something to docker? -
How to pass request to django form?
How to pass request to django form? I am creating a django update profile form where user could change profile email. I want to check if email in form belongs to logged user if not then I want to check if this email is used by others users before setting it as new users email. Here is my code and this self.request.user.email doesn't work: def clean_email(self): email = self.cleaned_data.get("email") owns_email = (email != self.request.user.email) if User.objects.filter(email__icontains=email).exists() and owns_email: raise forms.ValidationError("This email aldready registered.") return email So maybe there is better solution to solve my problem? -
Heroku postgres: potential brute force attack
I have a Django app running on Heroku using Heroku Postgres. I was looking at the latest log (something I don't do very often) and something strange caught my eye. There were all these fatal database errors as shown below: 2017-02-25T20:31:18+00:00 app[postgres.346]: [DATABASE] [5-1] LOG: could not accept SSL connection: EOF detected 2017-02-25T20:31:18+00:00 app[postgres.347]: [DATABASE] [5-1] FATAL: no pg_hba.conf entry for host "x.x.x.x", user "postgres", database "postgres", SSL off 2017-02-25T20:31:19+00:00 app[postgres.348]: [DATABASE] [5-1] LOG: could not receive data from client: Connection reset by peer 2017-02-25T20:31:20+00:00 app[postgres.349]: [DATABASE] [5-1] FATAL: no pg_hba.conf entry for host "x.x.x.x", user "postgres", database "postgres", SSL off 2017-02-25T20:31:20+00:00 app[postgres.350]: [DATABASE] [5-1] FATAL: password authentication failed for user "postgres" 2017-02-25T20:31:20+00:00 app[postgres.350]: [DATABASE] [5-2] DETAIL: Connection matched pg_hba.conf line 10: "hostssl all all 0.0.0.0/0 md5" 2017-02-25T20:31:21+00:00 app[postgres.351]: [DATABASE] [5-1] FATAL: no pg_hba.conf entry for host "x.x.x.x", user "postgres", database "postgres", SSL off 2017-02-25T20:31:22+00:00 app[postgres.352]: [DATABASE] [5-1] FATAL: password authentication failed for user "postgres" 2017-02-25T20:34:21+00:00 app[postgres.641]: [DATABASE] [5-1] FATAL: password authentication failed for user "root" 2017-02-25T20:34:21+00:00 app[postgres.641]: [DATABASE] [5-2] DETAIL: Connection matched pg_hba.conf line 10: "hostssl all all 0.0.0.0/0 md5" 2017-02-25T20:34:22+00:00 app[postgres.642]: [DATABASE] [5-1] FATAL: no pg_hba.conf entry for host "x.x.x.x", user "root", database "root", SSL off 2017-02-25T20:34:23+00:00 app[postgres.643]: … -
How reuse function __str__ in mdoel.py for each class model
Hello everyone I start use Django Framework and I have a question. Django's documentation says, when I create class(model) in the end of class I should write function to return string value for my object, it all look like this: class NameClass(models.Mode): field_name_1 = models.SomeTypeField() field_name_2 = models.SomeTypeField() field_name_3 = models.SomeTypeField() ... field_name_n = models.SomeTypeField() def __str__(self return self.field_name_1, ...self.field_name_n In this case I wrote function for return string value, cause I have a lot of fields in my models and write each of them in __str__ function it will be a lot of work. So my function look like this: def __str__(self): fields ='' for x in self._meta.fields: fields = fields + string.split(str(x),".")[2]+' ' return fields Now question. How can I reuse this function in each class(model) in model.py, without copy paste this function? For example. I have a lot of classes(mdoels): class FirstModel(models.Model): ... def __str__(self): ... class SecondModel(models.Model): ... def __str__(self): ... class ThirdModel(models.Model): ... def __str__(self): ... class EtcModel(models.Model): .... def __str__(self): And I don't want copy paste my function everytime, may exist some way to use it like a global function or another way to solve it. -
Django wsgi - 504 when uploading big files
I have a Django app set up together with Apache and mod_wsgi. This app will serve pretty big files that will be uploaded by admins via the admin panel. My problem is that big files (bigger than 15gb ish) triggers a 504 error when uploaded. The Apache error log reads: [Fri Feb 24 12:54:56.455187 2017] [wsgi:error] [pid 18263] [client 2001:700:300:34:c9c3:2908:2c90:f44:52116] Timeout when reading response headers from daemon process 'processName': /path/to/wsgi.py, referer: https:/mydomain.com/admin/appname/modelname/add/ My understanding is that Django requires the entire file to be uploaded, before it sends a response. Because of the time it takes to upload the file, the process times out. With that said, the 504 errors is not triggered before the entire file is uploaded. I have found others that have the same problem as me, but I have yet to find a solution to the problem. Does anyone have a suggestion on how I might make this work? I have done a bit of reading on the Django FileUploadHandler class. Would it be possible to create a custom FileUploadHandler that responds to the request instantly, and then handles the upload asynchronously with Celery? -
Tables aren't showing up when I run migrate using Django and Heroku
I have a Django project with some models. I ran python manage.py makemigrations locally, added the migrations file to the master branch, then pushed to heroku. Then when I run heroku run python manage.py migrate, the migration completes successfully. However, when I connect to the database, none of my tables are there. Here's a screenshot of what I did: What's going on here? Thanks!