Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Internal Server Error - OpenSSL
I am trying to setup my Django App on Google Compute Engine VM instance using Apache & mod_wsgi. But Everytime I try to restart my apache server & hit the website, I get an Internal Server Error. On Refreshing the web url again, I see no such error. Steps to Re-pro: 1) sudo service apache2 restart 2) Hit www.example.com Stack Trace on Console File "/usr/local/lib/python2.7/dist-packages/oauth2client/transport.py", line 153, in new_request credentials._refresh(orig_request_method) File "/usr/local/lib/python2.7/dist-packages/oauth2client/client.py", line 765, in _refresh self._do_refresh_request(http_request) File "/usr/local/lib/python2.7/dist-packages/oauth2client/client.py", line 792, in _do_refresh_request body = self._generate_refresh_request_body() File "/usr/local/lib/python2.7/dist-packages/oauth2client/client.py", line 1501, in _generate_refresh_request_body assertion = self._generate_assertion() File "/usr/local/lib/python2.7/dist-packages/oauth2client/service_account.py", line 386, in _generate_assertion key_id=self._private_key_id) File "/usr/local/lib/python2.7/dist-packages/oauth2client/crypt.py", line 97, in make_signed_jwt signature = signer.sign(signing_input) File "/usr/local/lib/python2.7/dist-packages/oauth2client/_openssl_crypt.py", line 97, in sign return crypto.sign(self._key, message, 'sha256') File "/usr/local/lib/python2.7/dist-packages/OpenSSL/crypto.py", line 2656, in sign _openssl_assert(final_result == 1) File "/usr/local/lib/python2.7/dist-packages/OpenSSL/_util.py", line 61, in openssl_assert exception_from_error_queue(error) File "/usr/local/lib/python2.7/dist-packages/OpenSSL/_util.py", line 48, in exception_from_error_queue raise exception_type(errors) Error: [('rsa routines', 'RSA_setup_blinding', 'BN lib'), ('rsa routines', 'RSA_EAY_PRIVATE_ENCRYPT', 'internal error')] If I refresh the url www.example.com again, I would get the website working again. Please suggest some steps to resolve this. Thanks, -
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB LESPACE, but settings are not configured
I’m using Django 1.9.1 with Python 3.5.2 and I'm having a problem running a Python script that uses Django models. C:\Users\admin\trailers>python load_from_api.py Traceback (most recent call last): File "load_from_api.py", line 6, in <module> from movies.models import Movie File "C:\Users\admin\trailers\movies\models.py", line 5, in <module> class Genre(models.Model): File "C:\Users\admin\trailers\movies\models.py", line 6, in Genre id = models.CharField(max_length=10, primary_key=True) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\fi elds\__init__.py", line 1072, in __init__ super(CharField, self).__init__(*args, **kwargs) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\db\models\fi elds\__init__.py", line 166, in __init__ self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\conf\__init_ _.py", line 55, in __getattr__ self._setup(name) File "C:\Program Files (x86)\Python35-32\lib\site-packages\django\conf\__init_ _.py", line 41, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TAB LESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing s ettings. here's the script: #!/usr/bin/env python import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "trailers.settings") os.environ["DJANGO_SETTINGS_MODULE"] = "trailers.settings" import django django.setup() import tmdbsimple as tmdb from movies.models import Movie #some code... I can't really figure out what's wrong. Any help is appreciated! -
Delete all django.contrib.messages
I recently realized that a module in our Django web app was using django.contrib.messages. However, the template's context processor did not have the django.contrib.messages.context_processors.messages processor added. I'm worried that when I push this to production, users will see all their old messages for all pages that had generated them. Is there a way to clear these messages for all users from the django shell? -
Extract field value from a URL string in Django/DRF
Suppose I have the following #models.py ... class Vote(models.Model): voted_obj = models.ForeignKey(Item) ... #serializers.py ... class VoteSerializer(serializers.ModelSerializer): voted_obj = serializers.HyperlinkedRelatedField(queryset=Item.objects.all(), view_name='item-detail') ... When creating a new vote I need to make sure that a user has not already voted on that particular item. Assuming that I send the following JSON request {... 'voted_obj': '/item/45/' // or any other string representing the url of voted_obj ... } is there a way to extract 45 from the request other than directly using python regular expression module? (i.e. is there a way provided by Django/DRF?) -
Django templates does not exist
So I work on windows and I try to load my websit home page. However I get the ''Templates doesnot exist '' errors I don't know why, TemplateDoesNotExist at / home/home.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.10.1 Exception Type: TemplateDoesNotExist Exception Value: home/home.html Exception Location: C:\Python35\lib\site-packages\django\template\loader.py in get_template, line 25 Python Executable: C:\Python35\python.exe Python Version: 3.5.2 Python Path: Here is my Tracerback you can see there that Django cannot even load some templates to be tested with. I'v seen others who have the same problem but at leat there was a list of tried template me I don't even have this. here is my home/views.py class IndexView(View): template_name = 'home/home.html' # not logged in def get(self, request): return render(request, self.template_name) here is my templates variable in my setting.py TEMPLATE = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] in my code and my structure is this and you can see that I added Home in the installed_app yet after changing the path root of project, changing my python version (3.5 instead of 2.7) put a templates folder on the same level of my manage.py … -
django user not showing up in admin page
I'm working on Tango With Django and have come across an issue that I can't seem to figure out. In my tango_with_django_project/urls.py file the tutorial for Django 1.9 indicated I should insert this class above the url patterns: class MyRegistrationView(RegistrationView): def get_success_url(self,request, user): return '/rango/' I noticed immediately that the self, request, user was was highlighted. When I ran the registration page, everything worked well. At least until I submitted the user. I got this long error: TypeError at /accounts/register/ get_success_url() takes exactly 3 arguments (2 given) In the above code in my urls.py file when I take out the request from the get_success_url(), I am able to register the user. In fact, the user shows up in the page as being a valid user, and I'm able to logout from that user, then log back in with no issues. Only thing is that they don't show up in my admin page. Also the get_success_url is still showing highlighting for self, user. Here is my settings file: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR =os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ … -
Convert HTML input's name in array style to normal dictionary?
Say i have python dictionary with keys like: {'product[1][properties][1][id]': 213} It's valid HTML input tag "name" attribute in "array" style, used for POST, and GET (query-string encoded): <input type="hidden" name="product[1][properties][1][id]" value="213"> <input type="hidden" name="product[1][properties][2][id]" value="214"> With python3, how can i dynamicaly decode it to "correct" structure: {'product': [{'properties': [{'id': 213}] }] } And vice-versa? I believe Django framework has shortcut for this, but i thought there must be solution in one of python3 standard library functions... -
Jquery works only if it is repeated in Django child template
I have a details.html that extends base.html. In base.html I have the scripts block tag with all the scripts, jQuery being first. base.html {% block scripts %} <script src="{% static "assets/js/jquery.js" %}" type="text/javascript"></script> <script src="{% static "assets/js/map.js" %}" type="text/javascript"></script> ... {% endblock scripts %} details.html {% extends 'base.html' %} {% block scripts %} {{ block.super }} <script type='text/javascript'> $(function(){ // custom code )}; </script> {% block scripts %} When inspected in Google Chrome all the scripts from base.html and details.html are loaded correctly, but custom code does not work. If in details.html I repeat after {{ block.super }} custom code works normally. Why the custom code does not work if jQuery import is not repeated? Help appreciated. details.html that works {% extends 'base.html' %} {% block scripts %} {{ block.super }} <script src="{% static "assets/js/jquery.js" %}" type="text/javascript"></script> <script type='text/javascript'> $(function(){ // custom code )}; </script> {% block scripts %} -
OpenSSL: EC_KEY_generate_key FAIL
I have few issues related to PyElliptic package in Python. Can you please help in resolving these, if possible ? (tried a lot, but couldnt figure out the exact solution) The python code which initiates this error: print("Salt: %s" % salt) server_key = pyelliptic.ECC(curve="prime256v1") # ----->> Line2 print("Server_key: %s" % server_key) # ----->> Line3 server_key_id = base64.urlsafe_b64encode(server_key.get_pubkey()[1:]) Value of "Salt" is getting displayed in 100% of the cases. Any/All of the below Errors shows up because of pyelliptic.ECC() call. (Line2) Exception('[OpenSSL] EC_KEY_generate_key FAIL ... error:00000000:lib(0):func(0):reason(0)',) (Ref. File Link: https://github.com/yann2192/pyelliptic/blob/master/pyelliptic/ecc.py#L214 ) extern "Python": function Cryptography_rand_bytes() called, but @ffi.def_extern() was not called in the current subinterpreter. Returning 0. Requirements.txt(partial) cryptography==1.5 pyelliptic==1.5.7 pyOpenSSL==16.1.0 On Running the command: sudo pip freeze --all |grep setuptools, I get: setuptools==27.1.2 According to: https://github.com/yann2192/pyelliptic/issues/39, it says that pyelliptic version 1.5.7 has some issues with old versions. (Not sure if this is applicable here or not.) Please let me know if any more detail is required. This problem seems to be basically due to some Old/Incompatible packages(related to PyElliptic, Cryptography, PyOpenSSL and/or setuptools) installed on the VM. Can someone please suggest a solution to resolve these issues ? Thanks, -
Django custom field validation fails
I am trying to implement a custom field in Django, but I can't get it to work properly. I am very confused by the API and the tutorial. Maybe I understand some things incorrectly, but to me it seems erroneous. class VersionField(models.CharField): description = "Semantic versioning with tpml.Version" def __init__(self, *args, **kwargs): kwargs['max_length'] = 30 super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs['max_length'] return name, path, args, kwargs def from_db_value(self, value, expression, connection, context): if value is not None: try: value = Version(value) except ValueError as exc: raise ValidationError(exc) return value def to_python(self, value): if value is not None and not isinstance(value, Version): try: value = Version(value) except ValueError as exc: raise ValidationError(exc) return value def get_prep_value(self, value): return str(value) The problem I have is when a value is saved with this field. I get object of type 'Version' has no len() due to the MaxLengthValidator in models.CharField (which VersionField subclasses). I see this part of code in the traceback: """ Convert the value's type and run validation. Validation errors from to_python and validate are propagated. The correct value is returned if no error is raised. """ value = self.to_python(value) self.validate(value, model_instance) self.run_validators(value) # << return … -
disable django clasical auth and force ldap auth
I've got a django project where I've connected to an LDAP and I'm adding some users manually via the admin page with my superuser login. The first user I added I created using the correct LDAP password. Then to make sure I was logging in with the ldap user and not the django authentication method I changed the ldap password for the newly created user. I can now login with both the ldap password and the original one. Is there a way to disable django authentication method and force ldap? -
How can admin post content visible by other users in django 1.8?
First of all, I'm new to django, this is my first projet so I have minimum knowledge. I'm working with django 1.8 and I have made a basic website. My problem is the following: You know how when you visit a website and the content is updated by the admin ? (news, schedule or reminder of deadline if you're a uni student) Is there a way to do that so the admin uses only an interface without touching the code ? I mean, supposing that the admin knows nothing about django and has a website in which he wants to uploads "news" or "announcements" that will be visible by all users or he can edit/delete old posts... I would appreiate it if you can guide me by giving me useful links to doumentations, tutorials or existing projects on github to see how it atually works. Thank you for your help. -
Django Model reference assignment in loop
Is the following code correct? The e should refer to a new object in the beginning of each for iteration, after try/except blocks are executed. I suspect some interference with an old object, because there is a bug which I cannot reproduce now. from webapp.models import Profile .... for e in Profile.objects.all(): if not e.profile_link in profile_data: e.delete() try: for key, employee in profile_data.iteritems(): #e still holds old reference try: #edit DB object if exists e = Profile.objects.all().filter(profile_link=key)[0] except Exception: #or create a new one e = Profile(profile_link=key) #modify e using employee e.save except Exception: #handle exception -
Django - Sending emails using class based view
I have been making a website containing a listview and formview. I have a form.py which looks like this : from django import forms class ContactForm(forms.Form): name = forms.CharField(required=True) email = forms.EmailField(required=True) message = forms.CharField(required=True) and the views.py : from django.shortcuts import render from .forms import ContactForm from django.views.generic import ListView from django.views.generic.edit import FormMixin from blog.models import Post from django.core.mail import EmailMessage class PostListAndFormView(FormMixin,ListView): queryset = Post.objects.all().order_by("-date")[:2] template_name = 'personal/index.html' form_class = ContactForm success_url = 'personal/index.html' This view also deals with a Listview functionality which you can ignore. My HTML template is: <form action="/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="SEND MESSAGE" /> </form> Finally urls.py : from django.conf.urls import url,include from . import views from homepage.views import PostListAndFormView urlpatterns = [ url(r'^$', PostListAndFormView.as_view(), name='PostListAndFormView'), ] What I want to do here is take the data from the form and send an email to my address with the entered data. Someone help me do this. -
Conditionally require only one of field or inline in Django admin
I need to validate a model such that either a field is set or an inline item is added. A related SO question deals with two fields, but i need to check an inline. So far i am trying to achieve this in a custom form's clean() method: Model classes: class Client(models.Model): full_name = models.CharField(max_length=100) class Trip(models.Model): name = models.CharField(max_length=100, unique=True) clients = models.ManyToManyField(Client, through='TripClient') b2b_operator = models.ForeignKey(B2BOperator, null=True, blank=True) class TripClient(models.Model): trip = models.ForeignKey(Trip) client = models.ForeignKey(Client) # some more fields ModelAdmin classes: class TripForm(forms.ModelForm): class Meta: model = Trip exclude = () def clean(self): cleaned_data = super(TripForm, self).clean() b2b_operator = cleaned_data.get('b2b_operator') num_clients = ??? #how to get this? if num_clients == 0 and b2b_operator is None: raise ValidationError("Add at least one client or set B2B operator.") return cleaned_data class TripClientInline(admin.StackedInline): model = Trip.clients.through class TripAdmin(admin.ModelAdmin): form = TripForm inlines = [TripClientInline] I need to check if b2b_operator is set or at least one inline item is added, and raise a ValidationError otherwise. How to check if at least one inline item is added in the form on TripAdmin's save? -
ImportError: No module named durationfield.db.models.fields.duration (Python, Django 1.9)
I'm trying to put a duration field in my models and I'm following the instructions here. First problems I run into is that I can't seem to import the module. Doesn't this come standard with Django? from durationfield.db.models.fields.duration import DurationField ImportError: No module named durationfield.db.models.fields.duration -
How to integrate customer specific translation in django app
We developped an app that will be used by several customer. The translation is working great. django.po & django.mo are generated and fields are translated in the app. However for the same language we may have different translations according to the customer. We would like to have something like like: customer1.po & .mo customer2.po & .mo And in the django setting a parameter telling customer1 or customer2 thus django would use the one or the other translation file. I've searched for changing the name of django.po to customer1.po but django seem to only look at django.po/mo files. Does someone knows a trick to do that ? -
Django Count of Items in a Field
models.py class Event(models.Model): name = models.CharField(max_length=20, unique=True) distance = models.IntegerField() date = models.DateField() class Category(models.Model): name = models.CharField(max_length=20, unique=True) description = models.CharField(max_length=20, unique=True) isnew = models.BooleanField(default=False) class Result(models.Model): event = models.ForeignKey(Event) category = models.ForeignKey(Category) score = models.IntegerField() I want to do a query to return a count of each unique Category in the Result table, for a given Event. What I'm doing now is something like: results = Result.objects.filter(event=myevent) categorycountdict = {} for r in results: if r.category in categorycountdict: categorycountdict[r.category] += 1 else: categorycountdict[r.category] = 1 Is there a better way, perhaps by query instead of python. -
Dependencies betwee fields in Django form
I have a form with two fields, which are based on two models. What I need? If you select a specific category, you can select only the sub-categories, which binds to a specific category. Forms category = forms.ModelChoiceField( label='Category', queryset=Category.objects.all(), widget=forms.Select, required=False) subcategory = forms.ModelChoiceField( label='Subcategory', queryset=SubCategory.objects.all(), #may be something like SubCategory.objects.filter(??????) widget=forms.Select, required=False) -
RedisClusterException when trying to write using Celery
My environment: I have three Ubuntu servers. One server is used as a load balancer using Nginx. The other two servers contain the exact same project (are identical apart from redis where one box is the master and other is the slave). The Programs/Applications I'm using Python, Gunicorn, Django, Celery, Redis, Sentinel What My project does: I have a URL which takes in a GET request, does some logic regarding the request and saves into redis. def save(key, value): conn = redis_cluster_connect() print conn conn.set(key, value) conn.set('bar','foo') This was working fine when my connection was: def redis_connect(): print 'redis connected' return redis.Redis(host="xxx.xx.xxx.x", port=6380, db=1) # CHANGE TO THE REDIS PORT THAT IS ACTIVE But when I use the cluster connection: def redis_cluster_connect(): startup_nodes = [{"host": "xxx.xx.xxx.x", "port": "6380"}] rc = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True) return rc The Error I get: [2016-09-15 13:28:59,682: INFO/MainProcess] Received task: testapp.tasks.mobilise_stops[cc64c425-bd37-4896-b6ab-4319de5fb743] [2016-09-15 13:28:59,684: WARNING/Worker-1] Oh no! Task failed: RedisClusterException("ERROR sending 'cluster slots' command to redis server: {'host': 'xxx.xx.xxx.x', 'port': '6380'}",) [2016-09-15 13:28:59,685: ERROR/MainProcess] Task testapp.tasks.mobilise_stops[cc64c425-bd37-4896-b6ab-4319de5fb743] raised unexpected: RedisClusterException("ERROR sending 'cluster slots' command to redis server: {'host': 'xxx.xx.xxx.x', 'port': '6380'}",) Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File … -
Django Invalid HTTP_HOST header on Apache - fix using Require?
A couple weeks ago, I had a wonderful time setting up an Apache and Django configuration to work while forcing SSL and operating behind an AWS load balancer. Now that it is all working nicely, I'm still constantly receiving the common "Invalid HTTP_HOST header" error, and trying to figure out the right way to go about fixing it. Searching has brought me to the following answer regarding the Apache configuration: How to disable Django's invalid HTTP_HOST error? Which recommends placing the following settings inside the <Directory></Directory> block in the VirtualHost file: SetEnvIfNoCase Host .+ VALID_HOST Order Deny,Allow Deny from All Allow from env=VALID_HOST} This works, but according to Apache (https://httpd.apache.org/docs/2.4/howto/access.html) this method is deprecated. I've read through the Apache docs but when I tried using the following code it just shut down access to the site and gave me a "Not Authorized" error. <RequireAll> Require host example.org </RequireAll> Not entirely sure what I'm missing. I know I can solve the problem using the first answer, just trying to figure out the "right" way using code that isn't deprecated. Site is using WSGIDaemonProcess to run the Django App and has the following set to force the SSL through AWS RewriteEngine On … -
Handling CORS when using django, angular and gulp
I have a project which I am building on top of Django and using AngularJS 1 to handle the front-end. Furthermore I am trying to use Gulp so I can enjoy some browser Sync features. Below is a piece of code that I am using to fire the Gulp server but at the same time using the Django server as a proxy. gulp.task('browser-sync', function() { browserSync.init({ proxy: "localhost:8000" }); }); However I am running into an issue with CORS. The error message I am getting is the following: XMLHttpRequest cannot load http://localhost:8000/static/js/data.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The data.json file in question is the one I am using as a source of data for my front-end developoment as I have not created my back-end yet. Here is an example of how i am getting data from the JSON file using Angular's $HTTP: marksApp.factory('getSubjectsService', ['$http',function($http){ return { getSubjectNames : function(stdNum){ return $http.get('http://localhost:8000/static/js/data.json') .then(function(data){ return data.data; }); } }; }]); -
Using Django on_delete.SET(callable()), does 'callable()' get called before object is deleted?
So, I'm writing up some code for handling webcomic pages, and I want to have it so that each page model has a ForeignKey that refers to the next and previous page in the series. If a page gets deleted, I would like to pass in a callable to on_delete.SET(), and use that callable to set the 'next' page of the previous page of the page that is getting deleted to the next page of the page that is getting deleted. (In other words, reset the values of the pages before and after the deleted page, in the same way as one would reset the pointers in a doubly linked list.) Obviously, I can't do that if the page is deleted before on_delete.SET() gets called. Would it be a good idea to try and overload the django delete() method on the page model so that I actually get the value required by SET() first, stash it somewhere, delete the page, and then supply the stashed value to on_delete.set()? Is there a better way to go about doing this? Thank you for your time. -
Convert a django queryset to json tree
Assume I have two tables in my model: class Country(models.Model): CountryName = models.CharField(max_length=20) class City(models.Model): CityName = models.CharField(max_length=20) Country = models.ForeignKey(Country) And in my view I make a json: list = City.objects.annotate(CountryName=F('Country__CountryName')).values('CityName', 'CountryName').prefetch_related('Country') return HttpResponse(json.dumps([any_entry for any_entry in list])) In result I receive something like: {[{CityName: 'Vancouver', CountryName: 'Canada'}, {CityName: 'Montreal', CountryName: 'Canada'}, {CityName: 'Dallas', CountryName: 'USA'}]} While I want something like: {[ { CountryName: 'Canada', Cities: [{CityName: 'Vancouver'}, {CityName: 'Montreal'}] }, { CountryName: 'USA', Cities: [{CityName: 'Dallas'}] } ]} Or at least: { Canada: ['vancouver','Montreal'], USA: ['Dallas'] } -
Django - Tango With Django upload picture
I'm on chapter 9 in Tango With Django - creating user authentication. In the registration page I have the option of uploading a picture. In my admin file everything looks good after I register myself. I show up in the User Profiles, and it even shows the image I uploaded: Picture: Currently: profile_images/earth.jpeg Clear. However when I click on that picture this is the error message I get: Page not found (404) Request Method: GET Request URL: http://localhost:8000/admin/rango/userprofile/1/change/profile_images/earth.jpeg/change/ Raised by: django.contrib.admin.options.change_view user profile object with primary key u'1/change/profile_images/earth.jpeg' does not exist. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. models.py: from __future__ import unicode_literals from django.db import models from django.template.defaultfilters import slugify from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length=128, unique=True) views = models.IntegerField(default=0) likes = models.IntegerField(default=0) slug = models.SlugField(unique=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) class Meta: verbose_name_plural = 'categories' def __str__(self): return self.name class Page(models.Model): category = models.ForeignKey(Category) title = models.CharField(max_length=128) url = models.URLField() views = models.IntegerField(default=0) def __str__(self): return self.title class UserProfile(models.Model): user = models.OneToOneField(User) website = models.URLField(blank=True) picture = models.ImageField(upload_to='profile_images', blank=True) def …