Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to print extend user profile field OneToOne Django 10.1?
i have a django project, i am used an model to extendend user profile A small fragment of the file my models.py from django.contrib.auth.models import User from django.db import models from django.utils import timezone # Model of User class UserProfile(models.Model): user = models.OneToOneField(User, primary_key=True) avatar = models.ImageField('profile picture', upload_to='static/logos/', null=True, blank=True) karma = models.IntegerField(default=0, blank=True) def set_avatar(self): _avatar = self.avatar if not _avatar: self.avatar="static/logos/default.png" def __str__(self): return self.user.username On my template base.html, i would like to get the avatar user, i can get username, but not avatar picture. A small part of code of my base.html file. {% if user.is_authenticated %} <p>Hi {{ user.username }} !! <img src="{{ user.UserProfile.avatar }}"/></p> {% else %} I am superuser and I register users from /admin/ panel, and upload their images. I check and the image is uploaded correctly in static/logos/ My problem is that I can not print it in my templates. Thanks for your help -
Django - edit an object that already exist?
I'm having a problem when I want to edit my record. it does edit everything ok, but tried to add get_or_create so if exists don't create, but it's not working as expected. Can someone help me? def edit(request, id): models = [hotel, person] for model in models: try: instance = model.objects.get(id=id) if instance == hotel.objects.get(id=id): form = hotelForm(request.POST or None, instance=instance) if form.is_valid(): obj, created = hotel.objects.get_or_create(name=name) if not created: messages.error(request, 'error. Already exists') else: form.save() messages.success(request, 'Success!') return redirect('/') except: try: if instance == person.objects.get(id=id): form = personForm(request.POST or None, instance=instance) if form.is_valid(): form.save() messages.success(request, 'Sucess!') return redirect('/') except: pass return render(request , "edit.html", {'form': form}) note: My model person works ok without the get_or_create but if I want to add it as in the first model hotel it won't work. How can I make it work as expected? -
django 1.10 one app page with a link redirect to another app page
I'm new to django server and trying to build a simple website for user registration. Here is the problem, I create my own app with index.html as my homepage. I also used another user registration app from: https://github.com/pennersr/django-allauth/tree/master/allauth I was trying to add the app to my homepage with a 'sign up' link. Basically, the account part, and ideally, the link can direct to: http://127.0.0.1:8000/accounts/login/ However, when I run the server, it gives me error: Reverse for 'base' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] server result: Both apps work fine individually, but when I try to add the link to my homepage, the error occurs. The related code in index.html file in my first app: <li><a href="{% url 'allauth:base' %}">Log In</a></li> The full path for index.html in my project is: project/app1/templates/app1/index.html The full path for base.html in my project is: project/allauth/templates/base.html I know I probably need to add a url line in my first app's urls.py file, and a view to show it, but how can I do it? Can anyone help me with this, much appreciate. -
Django Project gives error ImportError: No module named DjangoWebProjectNew.settings
I have a Django web application: 1) Django Project folder: wsgi,settings,urls 2) App folder: forms,models,views,templates. But I get the following error on production server: ImportError: No module named DjangoWebProjectNew.settings What is the problem here? -
How to allow users to dynamically set the scheduled time for email reports within a web framework?
Right now, I am using crontab to send out scheduled emails. The way I have been doing it is using a web framework like Django, CakePHP, or Laravel, and then using crontab to call the right django or cakephp console commands at the right time. Then the console commands will do the work of assembling the information together: recipients, body, attachments, and then send out the email. I have already given the powers to my users in terms of editing the recipients. Now they want the power to edit the times (time of the day) and frequency (weekly, daily, every wednesday, etc) the emails get sent out. I am not sure how to allow that within the context of a web framework. Assume that I am using either Python framework like Django and a PHP framework like Laravel. -
Validate a condition that relies on foreign keys in Django admin
I have two models, Book and Page, where Page has a foreign key relation to Book. In admin.py, the webpage to modify a book has inline elements for Page objects: class PageAdminInline(admin.TabularInline): model = Page extra = 1 class BookAdmin(admin.ModelAdmin): inlines = [PageAdminInline] admin.site.register(Book, BookAdmin) In the inline forms, a field allows to set the page number for each page. With this configuration, how can I validate the global condition that all pages numbers of a book should be different? I suppose I have to override a clean() method related to a book model or book somewhere, but I don't know how to access from there the data related to the pages that the user inputs. -
wsgi.py not getting located on django production server
File "passenger_wsgi.py", line 8, in wsgi = imp.load_source('wsgi', 'webapps/DjangoWebProjectNew/wsgi.py') IOError: [Errno 2] No such file or directory What is this whole idea about wsgi.py file...... I know my file is present on the server but the application just wont catch the file. -
Is it possible to use ROS in Django?
I'm currently working on a webapp built on the Django framework. One of the functionalities it needs is to be able to communicate with ROS. However, ROS function need to be run on the main thread and from what I understand django spawns new threads each time. Due to this when I attempt to call ROS functions, I get errors saying that it won't work because it's not on the main thread. I've tried writing a separate python script and importing it into the views and calling it from there, but I still get the same errors. Does anyone know of a workaround to this problem in Django? -
Vagrant - Reaching your django server from host machine
I setup a vagrant VM using puphpet configurator, I installed a number of programming languages including PHP, python, ruby etc. I installed apache2 and mysql for PHP projects but its django that I really need to get up and running. Heres the part of the config file where the network IP and hostname are defined: machines: vflm_zpwmfbk4aw05: id: machine1 hostname: machine1.puphpet network: private_network: 192.168.56.101 forwarded_port: vflmnfp_pjysbxl944a0: host: '9346' guest: '22' memory: '2000' cpus: '1' When I vagrant up then point my hosts browser to 192.168.56.101 I get a blank screen. Which means its connecting to something, otherwise I'd get a 404 screen. I read that to access the django server from your host, you need to run this: python manage.py runserver 0.0.0.0:8000 But when I point my browser to 192.168.56.101:8000, I get the 404 screen. Heres whats in the /etc/hosts file: 127.0.0.1 machine1.puphpet machine1 127.0.0.1 localhost 127.0.1.1 vagrant.vm vagrant ::1 localhost ip6-localhost ip6-loopback ff02::1 ip6-allnodes ff02::2 ip6-allrouters 192.168.3.3 myhost.dev I manually added the last line 192.168.3.3 myhost.dev because I decided to change the settings that were installed by default but it doesn't work. Heres the interfaces file: $ cat /etc/network/interfaces # This file describes the network interfaces available on your … -
How do I make allauth's authentication available on my homepage URL?
So i've installed Django allauth to handle my login authentication. However I don't want a seperate URL for login. I want it to be available on my homepage via Javascript onclick (login box appears when you click a button/no page refresh). But the current allauth URL is located at '/accounts/login'. So as I said I need it located at '/'. How would I do this? Here is my views.py: def boxes_view(request): ... search = request.GET.get('search') posts = Post.objects.all().filter(category=1).order_by('-date') if search: posts = posts.filter( Q(title__icontains=search) | Q(content__icontains=search) ) else: posts = Post.objects.all().filter(category=1).order_by('-date') context = { 'posts': posts, } return render(request, 'polls.html', context) Can I pass it in as context or? How would it be done? -
DJango - NoReverseMatch Error
That is the exception value: Reverse for '' with arguments '()' and keyword arguments '{'id': 1}' not found. 0 pattern(s) tried: [] index.html <p>Estudiante: <a href="{% url 'polls.views.student_detail' id=student.id %}">{{student.stduent_name}}</a></p> The link should go to a route like this "127.0.0.1:8000/polls/1/". The route works fine out of the link. views.py def student_detail(request, id): student = get_object_or_404(Student, id=id) return render(request, 'polls/student_detail.html', {'student': student}) urls.py urlpatterns = [ url(r'^$', views.index), url(r'^polls/(?P<id>[0-9]+)/', views.student_detail), ] Images: Error details Route tree -
My form is not displaying fields and I cant figure out why
I am creating a contact form in django to send an email but the form is not displaying on the webpage. I think the issue may be because the form object may have never been passed to the context correctly, but I have no idea where it is going wrong. The code below is what I have so far. from .forms import * My Views def email(self): if request.method == 'POST': form = Contact(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] email = form.cleaned_data['email'] first_name = form.cleaned_data['first_name'] message = form.cleaned_data['message'] try: send_mail(first_name + ": " + subject, message, email, ['my_email@gmail.com']) except BadHeaderError: return HttpResponse("Invalid Header.") return redirect('thankyou') return render(request, 'Index-App/contact.html', {'form': form}) My Form Class class ContactForm(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea) Urls url(r'^contact/$', views.email, name='contact'), My Template {% block contact %} <form method="POST" action="{% url 'Index-App:contact' %}"> {% csrf_token %} {{ form }} <input type="submit" class="btn-success" value="Send"/> </form> {% endblock %} -
Database structure and queries for a Twitter-like posts timeline
I'm posting this question with a Django tag, because I'm working in this environment, but it's actually more or a generic question: I'd like to show something like my timeline on Twitter, i.e. a list of posts of all the people I am following ordered chronologically. My typical database structure looks like this: Table Name: Users Columns: UserID PK EmailAddress Password TableName: Friends Columns: UserID PK FK FriendID PK FK TableName: Posts Columns: UserID PK FK Content If I wanted to retrieve all posts of all the friends for a given user, it looks like this (this is not supposed to be valid SQL!): SELECT * FROM Posts WHERE UserID IN (LIST OF "Given user friends' IDs") This works - no problem! However, this does so not scale! Let's assume we have a busy website and our given user has 2,000 friends and there are some ten million posts in the database. In such a scenario, the database query would be highly inefficient and slow. Can this be solved with a relational database like PostgreSQL or MySQL? If not, how does e.g. Twitter do it? -
How to add fields to django user profile in this example?
I am using Django-userena to extend user profile behavior. What I am trying to do is either override the edit_profile function in userena/forms.py or handle this from my myapp/forms.py in myapp/models.py I have added the new fields that I would like to include in the form. my app models.py class MyProfile(UserenaBaseProfile): user = models.OneToOneField(User, unique=True, verbose_name=_('user'), related_name='my_profile') storename=models.CharField(null=True, blank=True, max_length=20) streetaddress=models.CharField(null=True, blank=True, max_length=30) city = models.CharField(null=True, blank=True, max_length=20) state = models.CharField(null=True, blank=True, max_length=20) zipcode = models.IntegerField(_('zipcode'), null=True, blank=True) nearbyzips1=models.IntegerField(null=True, blank=True) nearbyzips2=models.IntegerField(null=True, blank=True) my question is what do I add to either forms or views.py in userena to save these attributes? userena/forms.py class EditProfileForm(forms.ModelForm): """ Base form used for fields that are always required """ first_name = forms.CharField(label=_('First name'), max_length=30, required=False) last_name = forms.CharField(label=_('Last name'), max_length=30, required=False) def __init__(self, *args, **kw): super(EditProfileForm, self).__init__(*args, **kw) # Put the first and last name at the top try: # in Django < 1.7 new_order = self.fields.keyOrder[:-2] new_order.insert(0, 'first_name') new_order.insert(1, 'last_name') self.fields.keyOrder = new_order except AttributeError: # in Django > 1.7 new_order = [('first_name', self.fields['first_name']), ('last_name', self.fields['last_name'])] new_order.extend(list(self.fields.items())[:-2]) self.fields = OrderedDict(new_order) class Meta: model = get_profile_model() exclude = ['user'] def save(self, force_insert=False, force_update=False, commit=True): profile = super(EditProfileForm, self).save(commit=commit) # Save first and last name user … -
OperationalError: (1060, "Duplicate column name 'new_description'")
I had an existing model Services which had some fields including. I wanted to add another field to it, so I did this: class Services(models.Model): description = models.TextField() # Already existing field new_description = models.TextField(default=description) # Newly added field When I ran migrations (makemigrations followed by migrate), I got the following error: AttributeError: 'TextField' object has no attribute 'model' I couldn't determine what the error was, so I deleted the newly created migration file, and ran the migrations again. I added the field new_description again and tried running the migrations again and got the following error: OperationalError: (1060, "Duplicate column name 'new_description'") What am I missing and how do I correct this? -
django load modal on click for each link
In my project I have many Buildings, and in the buildings.html I display each Building using a single image (big_image). What I want to do is load a modal every time the user clicks in a Building, this modal allows the user to see additional images of the building. This would be very easy if I loaded each Building's modal when the user entered the page. But if I did that the page would take ages to load (because there are many Buildings), so my idea is to use jQuery's .innerHTML to append the modal html to the page when the user clicks on a Building, but when I do that the only code appended is `{% for building in buildings %}{% if building.pk == 1(or whatever is the pk) %}{% endif %}{% endfor %}` There might be an easier way to achieve that that I dont know Here's my code: buildings.js function loadModal(objectPk){ document.getElementById("loadModal").innerHTML = "{% for building in buildings %}{% if building.pk == "+objectPk+" %} <div class="modal fade mymodal in " id="myModal{{ building.pk }}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title" id="myModalLabel">{{ building.name }}</h4> … -
Picture not showing in main blog page Django
I have recently created blog, all is fine ecxept pictures no showing in main blog page Pictures are visible when I open particular post pictures are shown When I enter main blog page pictures are gone no pictures Pictures are added in admin using WYSIWYG editor froala_editor. I use below to display blog view blog.py {% extends "personal/header.html" %} {% block content %} {% for post in object_list %} <h5>{{ post.date|date:"Y-m-d" }}<a href="{{post.id}}"> <b> {{ post.title }}</b></a></h5> <!--<img src="{{ post.img.url }}" class="img-responsive" >--> {{ post.body|safe|linebreaks|truncatechars:400 }} {% endfor %} {% endblock %} I would be grateful for responses -
Specify PostgreSQL Schema in Django
I am trying to build some DB front-ends using Django since I like the general MVC structure as well as their template system and admin interface. However, I am having trouble with certain aspects of using a PostgreSQL back-end. I've managed to figure out how to specify different schemas (and databases) using the database section of the settings.py file like so: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'MPS': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS': { 'options': '-c search_path=django' }, 'NAME': 'sandbox_manzer', 'HOST': '192.168.2.151', 'PORT': '5434', 'USER': '******', 'PASSWORD': '**********************', } } However, when I try and script some basic tests, as detailed here, I run into a problem. My user can create databases just fine so my test_db gets built, but when the django app goes to build the models into tables I get an error stating that No schema is specified for the test_db. Any help in how I specify schema names for the test_db would be most appreciated. Especially since I intend to build out multiple apps for a single project using different schemas as logical separators. Thanks! -
How to do perform JSON REST Call with Django
What is best way to do an outbound HTTP REST request call in Django? I thought the django REST framework would help me with that, but it seems that the framework is more aimed at "restifying" your own data. Any suggestions/examples are welcome! Thanks. -
Django - Try - Except multiple except error
I need help with this... I have this code : try: hotel.objects.get(id=id).delete() messages.success(request, 'Deleted') except: car.objects.get(id=id).delete() messages.success(request, 'Deleted') except: person.objects.get(id=id).delete() messages.success(request, 'Deleted') except: messages.error(request, 'Error') I ll try to delete hotel , or car. Works great with this method, but I need to delete one more model and if I try to delete a model that's not here I want an Error.. but I can only have one except due to my error: SyntaxError:default 'except' must be the last How can I make it work? Thanks! -
"save() prohibited to prevent data loss" ... on only some machines
I'm working on a project which allows people to enter their game results at Scrabble tournaments. In testing this project, it's helpful to have a script which automatically loads data. For answerers willing to dig a bit into the project, the relevant script is the makerounds.py file in the above Github link. Previously, this script ran as expected, loading the specified players and game results on to the website. To run the script, I used ./manage.py shell < makerounds.py But this no longer works...at least on my machine. Instead, I get the following error: ValueError: save() prohibited to prevent data loss due to unsaved related object 'tourney_round'. On my co-developer's machine, the script works fine. He's using Windows, I'm using OSX. When I pull what he pushes, it usually (but not always!) doesn't work on my machine. When he pulls what I push, it works for him. What could the culprit be? My best guess right now is something to do with the database, which I've fiddled with a bit, e.g. by deleting or flushing db.sqlite3. -
The view polls.views.forms didn't return an HttpResponse object. It returned None instead
Why am I seing this and my views returns a HttpResponse object. This is my view def forms(request): from forms import SearchForm """process the form""" if request.method == 'GET': #create a ew form and populate it with the data form = SearchForm(request.GET) #validate the data if form.is_valid(): #process the data in cleaned_data attribute name = form.cleaned_data['name'] return HttpResponse("Received this word: {}".format(name)) else: form = SearchForm() #return this return render(request, 'polls/form.html', {'form' : form}) As i can see, My view return a HttpResponse and on the branch condition it returns a render. My other views works the same -
How to set up Django 1.9 and Python 3.5 in a virtualenv? [on hold]
I'm fairly new to this. Somebody told me to set it up but left me no instructions. Any help? Thanks! P.s running on ubuntu -
Right way to setup django project on production server
I think I am a little confused about the Django Project Template that appears in Visual Studio 2015 community edition What I get in the template is one application and one project wide folder Project Wide folder contains: settings, urls, wsgi application folder contains: forms, models, views, templates, static And I am all set up with the application running fine. The problem comes when I upload my application on the server. The 2 folders get mixed up when I have to upload on production server. Is this the right way for uploading the application on server? -
Why does docker-compose build not reflect my django code changes?
So I have a Django project I am deploying with docker-compose. There is a simple error in my profile_form.html template with line 3 highlighted. {% include "header.html" %} {% load i18n %} {% load url from future %} 'future' is not a registered tag library So I simple delete the load url line, save profile_form.html, and then try to build a new container reflecting the code change. docker-compose build docker-compose start This did not resolve the issue and I get the same error. I went into the container by running docker-compose exec -i -t <containerid> /bin/bash and examined the profile_form.html and sure enough line 3 is still there. Unless I am missing something completely obvious this tells me that my understanding of docker-compose build is incorrect. As I thought docker-compose build would be able to determine "yes there is a code change in the 'web' directory" and then rebuild the container.