Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail: cannot import name pages
I'am using Vagrant for virtualization, everything worked fine until today, when my friend cloned a repo which worked fine on my computer he started to getting cannot import name pages Environment: Request Method: GET Request URL: http://127.0.0.1:8017/ Django Version: 1.8.14 Python Version: 2.7.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.humanize', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.sitemaps', 'django.contrib.staticfiles', 'compressor', 'django_common', 'djrill', 'taggit', 'modelcluster', 'wagtail.wagtailcore', 'wagtail.wagtailadmin', 'wagtail.wagtaildocs', 'wagtail.wagtailsnippets', 'wagtail.wagtailusers', 'wagtail.wagtailimages', 'wagtail.wagtailembeds', 'wagtail.wagtailsearch', 'wagtail.wagtailredirects', 'wagtail.wagtailforms', 'wagtail.wagtailsites', 'wagtail.contrib.wagtailsitemaps', 'wagtail.contrib.wagtailfrontendcache', 'django.contrib.gis', 'froala_editor', 'dal', 'dal_select2', 'home', 'accounts', 'ads', 'staff', 'common', 'search', 'blog', 'article', 'center', 'slideshow', 'legacy', 'django_quiz', 'django_quiz.essay', 'django_quiz.quiz', 'django_quiz.multichoice', 'django_quiz.true_false', 'polls', 'wagtailoverrides', 'rate_system', 'dovescore_system', 'social_django', 'django_extensions', 'wagtail.contrib.wagtailstyleguide'] Installed Middleware: ['django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', 'wagtail.wagtailcore.middleware.SiteMiddleware', 'wagtail.wagtailredirects.middleware.RedirectMiddleware'] Traceback: File "/home/vagrant/webapps/dovemed/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 119. resolver_match = resolver.resolve(request.path_info) File "/home/vagrant/webapps/dovemed/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve 365. for pattern in self.url_patterns: File "/home/vagrant/webapps/dovemed/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in url_patterns 401. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/vagrant/webapps/dovemed/local/lib/python2.7/site-packages/django/core/urlresolvers.py" in urlconf_module 395. self._urlconf_module = import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py" in import_module 37. __import__(name) File "/vagrant/dovemed/dovemed/urls.py" in <module> 14. from wagtail.wagtailadmin import urls as wagtailadmin_urls File "/home/vagrant/webapps/dovemed/local/lib/python2.7/site-packages/wagtail/wagtailadmin/urls/__init__.py" in <module> 4. from wagtail.wagtailadmin.urls import pages as wagtailadmin_pages_urls Exception Type: ImportError at / Exception Value: cannot import name pages I'm using wagtail 1.8 and django 1.8.14 -
Filter matching when a set of fields is found together on another object, using Django ORM
In my app, users can interact with a set of objects — and they can also share their interactions with one or more of these objects. For example, say a user occasionally purchases a particular product. These purchases are tracked with a reference to the user and the product: class Product(models.Model): name = models.CharField(max_length=255) description = models.TextField() class Purchase(models.Model): user = models.ForeignKey(User) item = models.ForeignKey(Product) date = models.DateTimeField(auto_now_add=True) The user might also opt to share all their purchases of an item. So I also track which users have shared which products: class Share(models.Model): user = models.ForeignKey(User) item = models.ForeignKey(Product) Given this setup, can I retrieve a list of all shared purchases through Django's ORM using a single query? That is, how would I find every Purchase whose combination of user+item fields match those of any Share object? If I have to I could first fetch all the shares, then loop through them and do an individual query for each: shared_purchases = [] for share in Share.objects.all(): purchases = Purchase.objects.filter(user=share.user, item=share.item) shared_purchases.extend(purchases) I'd prefer not to change my models if I can help it, but it feels like I might be able to get closer if I factored out the (user,item) … -
Having a NoReverseMatch error when attempting to create an `UpdateView` view
I am attempting to allow the user to update the Identity_unique instance and save the updated instance. Problem : The bounded form is rendered, however when I edit the instance and attempt to save it I get this error : What am I doing wrong? Here is my code : models.py from django.db import models from django.contrib.auth.models import User from django.core.urlresolvers import reverse from Identity import settings import datetime class Identity_unique(models.Model): NIS = models.CharField(max_length = 200, primary_key = True) user = models.ForeignKey(settings.AUTH_USER_MODEL) Timestamp = models.DateTimeField(auto_now = True) first_Name = models.CharField(max_length = 80, null = True ) last_Name = models.CharField(max_length = 80, null = True ) location = models.CharField(max_length = 100, blank = True) date_of_birth = models.DateField(auto_now = False, auto_now_add = False, blank = True, null = True) contact = models.CharField(max_length = 15, null = True) def get_absolute_url(self): return reverse('Identity_nest_list', kwargs = {'pk':self.pk}) views.py from django.shortcuts import render, redirect from django.views.generic import TemplateView, UpdateView from nesting.forms import Identity_Form, Symptom_Form from nesting.models import Identity_unique, Symptom_relation class Identity_view(TemplateView): template_name = 'nesting/nesting.html' def get(self, request): form = Identity_Form() Identities = Identity_unique.objects.filter(user = request.user) var = {'form': form, 'Identities': Identities} return render(request, self.template_name, var) def post(self, request): form = Identity_Form(request.POST) content = None if form.is_valid(): … -
Post_save signal fails to update m2m field. It works through shell
I am trying to create a related Site instance using a post_save signal generated from a Contract class and then relate the new building with the contract through a m2m relationship, and I can manage it easily through the shell: contract = Contract.objects.create(name='79w') print(contract.buildings.all() --> '<QuerySet [<Building: 7w9 — Base>]> if I check in the admin and my page the building is in the m2m field. But when I create a new contract through my page or through the admin and the check the list of related Buildings it doesn't appear. This is a simplified verions of my classes and functions App1.models def create_base_building(sender, instance, created, **kwargs): # Creates base building after a new contract. if created: base_building = Building.objects.create( name = "{0} - Base".format(instance.name)) instance.buildings.add(base_building) class Contract(models.Model): name= models.CharField(max_length=30, blank=False, default='') buildings = models.ManyToManyField(Building, related_name='contracts', blank=True) Buildings exist in a second app: App2.models class Building(models.Model): name= models.CharField(max_length=30, blank=False, default='') I have read herehttps://stackoverflow.com/questions/4432385/django-how-to-save-m2m-data-via-post-save-signal that it's caused by an artifact of how the forms code updates m2m info, but I don't understand how to use the m2m signals. Specilly sins the final objective would be to check the form and if there is a building secteled do nothing and if … -
what does format=none reference in djano rest framework apiview?
Docs are here: http://www.django-rest-framework.org/api-guide/views/#get_permissionsself in this example format is set to none but no reference to it: class ListUsers(APIView): """ View to list all users in the system. * Requires token authentication. * Only admin users are able to access this view. """ authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAdminUser,) def get(self, request, format=None): """ Return a list of all users. """ usernames = [user.username for user in User.objects.all()] return Response(usernames) I checked the source code and still no reference to format. Appreciate some clarity -
Failed building wheel for twisted
I made virtualenv, new blank django project and I want to install Channels. I use Python 3.6.3. I typed pip install -U channels and this is OUTPUT: ... Failed building wheel for twisted ... Command "/home/marcin/Documents/django_projects/channels/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-ic8ux9ei/twisted/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-ox6bclm5-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/marcin/Documents/django_projects/channels/include/site/python3.6/twisted" failed with error code 1 in /tmp/pip-build-ic8ux9ei/twisted/ pip list OUTPUT: ... Django (1.11.6) ... pip (9.0.1) ... setuptools (36.6.0) ... wheel (0.29.0) ... I see that I don't have Twisted, so I typed:pip install twisted. This is OUTPUT: ... Failed building wheel for twisted ... Command "/home/marcin/Documents/django_projects/channels/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-a54n37_z/twisted/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-9p23ehnv-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/marcin/Documents/django_projects/channels/include/site/python3.6/twisted" failed with error code 1 in /tmp/pip-build-a54n37_z/twisted/ As You can see the Outputs are almost the same. How can I install Channels? -
Django - how to access form elements to create a string
I have a basic CRUD app and want to be able to use a button to send the data of an individual record. I need to form a string from the detail view data that can then be emailed once a button is clicked. I have the CRUD running and email button working, but I can't figure out where to create the string using object.name, etc. Here's the detail.html: {% extends "base.html" %} {% load static %} {% block content %} <p><a class="btn btn-default" href="{% url 'call_log_call_list' %}">Call Listing</a></p> <table class="table"> <tr><td>name</td><td>{{ object.name }}</td></tr> <tr><td>created</td><td>{{ object.created }}</td></tr> <tr><td>last_updated</td><td>{{ object.last_updated }}</td></tr> <tr><td>address1</td><td>{{ object.address1 }}</td></tr> <tr><td>address2</td><td>{{ object.address2 }}</td></tr> <tr><td>city</td><td>{{ object.city }}</td></tr> <tr><td>zip</td><td>{{ object.zip }}</td></tr> <tr><td>phone</td><td>{{ object.phone }}</td></tr> <tr><td>email</td><td>{{ object.email }}</td></tr> <tr><td>contact_method</td><td>{{ object.contact_method }}</td></tr> <tr><td>notes</td><td>{{ object.notes }}</td></tr> </table> <a class="btn btn-primary" href="{{object.get_update_url}}">Edit Call</a> <a class="btn btn-success" href="{{object.call_log_call_email}}">Email Call</a> {% endblock %} Question: where does object inherit from? Is this standard? Here is the views.py: from django.views.generic import DetailView, ListView, UpdateView, CreateView from .models import Call from .forms import CallForm from django.core.mail import send_mail class CallListView(ListView): model = Call class CallCreateView(CreateView): model = Call form_class = CallForm class CallDetailView(DetailView): model = Call class CallUpdateView(UpdateView): model = Call form_class = CallForm class CallEmailView(DetailView): model = … -
How can I automatically save in django-admin editable listviews (or popup a reminder) on leave
Problem I have a question on how to save in editable listviews in the django-admin. I use django 1.11 with python 3.6. Suppose I have a list of 100-200 Events in a model. In order to bulk edit a boolean field for all entries, I register the model in admin-view as editable list (see code below). For convenience, I slice the task and display 30 entries per page by using the pagination. If I switch to the next page without pressing the save button, the changes will be lost. Now: how can I prevent loss of my input? Is there a django method to save automatically? I can imagine three ways, but I don't know how to implement it in django. Instant save for the respective entry, when its checkbox is checked. Hook on the pagination buttons: When I press any page number, the changes are saved. A Popup with warning or save button, when I leave the page without having saved. Has anybody a suggestion or code snippets for any of the three ways? Or a suggestion for different approach? Thank you! Minimal Example: from django.db import models from django.contrib import admin class Event(models.Model): name = models.CharField(max_length=30) description = … -
HTML - Z-index with transition
I got a problem with my html project. When I hoover an image it gets larger but it does not cover images next to each other. (only left one) https://i.imgur.com/oNP4gHA.png https://i.imgur.com/g2zIoSr.png CSS: .photo { margin: 10px 0; width: 120px; background: white; padding: 10px; opacity: 1; border-radius: 5px; border: 1px solid silver; box-sizing: border-box; justify-content: space-around; flex-wrap: wrap; transform: rotate(5deg); transition: 0.3s all ease-in-out; will-change: transform; align-items: flex-start; display: inline-flex; } .photo img { flex-basis: 100%; width: 100px; } .photo figcaption { margin-top: 10px; } .photo:nth-child(even) { transform: rotate(-5deg) scale(0.8); } .photo:hover { opacity: 1; transform: scale(2.0); z-index: 10; } HTML {% for i in zdjecie %} <figure class="photo" > <img src="{{i.url}}" alt="Kotek Robert"> <figcaption> {{i.title}} </figcaption> </figure> {% endfor %} -
Django model cannot call app module methods
I have a django app with the following structure: . ├── admin.py ├── apps.py ├── Business ├── __init__.py ├── migrations ├── models ├── __pycache__ ├── templates ├── tests.py ├── urls.py └── views In the model folder I have an __init__.py file which contain the following code: from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from web.Business.rockynodeZabbix import Zabbix @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_zabbix_group(sender, instance=None, created=False, **kwargs): if created: Zabbix.component("HostGroup").create(instance.id) The issue it that i cannot import my app web module methods in the models since in several classes in the Business module am calling the model module: import web.models as If I import the app module web.Business.xxxx in my model i get the following error: File "/Users/kheshav/Linux_projects/rockynode.io/App/web/models/__init__.py", line 11, in <module> from web.Business.rockynodeZabbix import Zabbix File "/Users/kheshav/Linux_projects/rockynode.io/App/web/Business/__init__.py", line 1, in <module> from .test import test File "/Users/kheshav/Linux_projects/rockynode.io/App/web/Business/test.py", line 1, in <module> import web.models as models AttributeError: module 'web' has no attribute 'models How do i call my app module function in the model since i want to trigger it when a user is created. -
Django AttributeError: module 'PIL.Image' has no attribute 'init'
I'm new to Django. I'm using version 1.11.6 in a vagrant box with ubuntu I added an ImageField to one of my models. Everything was working fine. Today (after rebooting) the same code throws this error (whenever I call manage.py): `Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 13, in <module> from django.core.management.base import ( ... more files in /usr/local/lib/python3.5/dist-packages/.. from django.core import validators File "/usr/local/lib/python3.5/dist-packages/django/core/validators.py", line 507, in <module> allowed_extensions=get_available_image_extensions(), File "/usr/local/lib/python3.5/dist-packages/django/core/validators.py", line 502, in get_available_image_extensions Image.init() AttributeError: module 'PIL.Image' has no attribute 'init' The exception thrown in the validators.py from django def get_available_image_extensions(): try: from PIL import Image except ImportError: return [] else: Image.init() return [ext.lower()[1:] for ext in Image.EXTENSION.keys()] I installed Pillow as the doc says sudo pip3 install Pillow In the python3 console, I can import Image from PIL correctly, but it doesn't have the init() method. What should I do? Thanks -
Django - Why am I getting this IntegrityError: NOT Null constraint failed: restaurants_restaurantlocation.owner_id?
I am trying to make a website where people can find restaurants and menu items based on their pickiness. Currently I am trying to do it so when I add something to the restaurants through forms I have it associated to an user but when I submit the form I get this error: IntegrityError NOT Null constraint failed: restaurants_restaurantlocation.owner_id Here is my forms.py: from django import forms from .models import RestaurantLocation from .validators import validate_category class RestaurantCreateForm(forms.Form): name = forms.CharField() location = forms.CharField(required = False) category = forms.CharField(required = False) def clean_name(self): name = self.cleaned_data.get("name") if name == "Hello": raise forms.ValidationError("This is an invalid name. You stubid boy.") return name class RestaurantLocationCreateForm(forms.ModelForm): #email = forms.EmailField() #category = forms.CharField(validators = [validate_category], required = False) class Meta: model = RestaurantLocation fields = [ "name", "location", "category" ] def clean_name(self): name = self.cleaned_data.get("name") if name == "Hello": raise forms.ValidationError("This is an invalid name. You stubid boy.") return name My models.py: from django.conf import settings from django.db import models from django.db.models.signals import pre_save, post_save from .utils import unique_slug_generator from .validators import validate_category # Create your models here. User = settings.AUTH_USER_MODEL class RestaurantLocation(models.Model): owner = models.ForeignKey(User) name = models.CharField(max_length=120) location = models.CharField(max_length=120, null=True, blank=True) category … -
Django FieldErro when trying to delete User
I'm having problems deleting a user (just for tests), and I'm not sure what's going on. I'm running python 3.6 and Django 1.11.6. My tests don't use database migrations, they create the database directly from the model, but the same happens when I try to delete an existing entry from the normal, correctly migrated database. First I create a user: user = User.objects.create_user('testing', 'testing@test.com', 'testpass') And the I just call: user.delete() And it crashes inside the delete() method. The user doesn't even need to have a related UserImage added, and it still crashes. Initially I thought that it's caused by the related object, as the exception says "join on 'added' is not permitted", and 'added' is a field on UserImage. Any help is appreciated as I'm looking at it for hours and can't find the cause :( models.py class UserManager(BaseUserManager): def _create_user(self, username, email, password, **extra_fields): if not username: raise ValueError('Username must be set.') email = self.normalize_email(email) user = self.model(username=username, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, email=None, password=None, **extra_fields): return self._create_user(username, email, password, **extra_fields) class User(AbstractBaseUser): class Meta: verbose_name = _('user') verbose_name_plural = _('users') USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] USERNAME_ALLOWED_REGEX = r'\w._-' objects = UserManager() username … -
Grab and manipulate user data without models
I'm not sure if this is even possible, but I would like to grab a user's input, pull it into my views.py, manipulate it, and then use that data in other views. I do not need this data stored in a database, as I won't be referencing it again, and I want to keep this as lightweight as possible. Currently, I'm trying to pull data from espn's fantasy football site using the python library espnff. My homepage consists of a textfield box and a submit button (Think of google.com). I have functions set up that will comb through an espn url such as http://games.espn.com/ffl/clubhouse?leagueId=123456 to grab the leagueID, from there I make use of espnff to grab more info on that league. My ideal use case is someone comes to my site, copies and pastes their league url like the one above, clicks submit and then brings them to https://example.com/{{ leagueID}/ which will display different info that I gather. I have not found a way to do this without submitting the user input to a model. Is possible to avoid using the database? If so how? -
Django: int() argument must be a string
Here's my code, objects = sorted(Game.objects.filter(...), key=lambda x: random.random()) items = Game.objects.exclude(pk__in=objects) But, i'm getting this error, int() argument must be a string, a bytes-like object or a number, not 'Game' How can I fix this problem? -
Django add comment form to detail template
I am developing Movie Review Website in Django.. I have created two models MovieCategory and another MovieDetail. For Movie Category my Model is : class MovieCategory(models.Model): name = models.CharField(max_length=50) slug=models.CharField(max_length=30) def __unicode__(self): return self.name.title() def save(self): self.slug=slugify(self.name) return super(MovieCategory,self).save() class Meta: db_table = "MoviesCategory" For Movie Detail my Model is: class MovieDetail(models.Model): title = models.CharField(max_length=150) description = models.TextField() category = models.ManyToManyField(MovieCategory) image = models.ImageField(upload_to='movie/post',blank=True,null=True) slug = models.CharField(max_length=200) def __unicode__(self): return self.title.title() def save(self): self.slug = slugify(self.title) return super(MovieDetail,self).save() class Meta: db_table = "MovieDetail" My Problem is that I want to add Review form for movie detail page where user can give their Review about movie and they can also see Reviews by other people. I haven't implemented Login Fetaure that I will implement later but can someone now guide me how to add Review form to movie detail page. -
pip install -r requirements.txt [Errno 2] No such file or directory: 'requirements.txt'
I am setting up the base for a django project, I have cloned a repo and I have just created a virtual environment for the project in the same directory. But when I try to run the command 'pip install -r requirements.txt' in the project directory I get this error: [Errno 2] No such file or directory: 'requirements.txt' I believe I'm just running it in the wrong directory, but I don't really know where I should run it. -
prefetch_related for Authenticated user
I'm working on a django web application and i'm in the process of minimizing the amount of individual database hits by using the prefetch_related and select_related methods, i have a certain method in my User model that pulls a couple of different related objects from it. def get_profile_info(self): *fetch data from a couple of models* And then i use this method in my view. def profile(request): profile_info = request.user.get_profile_info() *rest of the view* The problem is, since request.user is not retrieved by the normal query methods, i don't get to use the prefetch_related and select_related along with pulling the user, and i can't find any way to retrieve the related data along with the model of that user. Is there a way to, say, override the retrieving of the user model so i can run the prefetch_related and select_related methods? -
missing accounts/profile page Django
I have extended the User model (using AbstractUser as defined in the docs) and included the contrib.auth urls, so I have a working login/logout urls for example. But I for some reason can't find the 'accounts/profile' url reference and view that is the supposed default in Django, and I grepped throughout the repository. For now I'm OK with the default view if there is one. -
Difficulty converting request.POST value in Django
In my Django application, I have a POST request QueryDict whose values I am trying to change. I understand that QueryDict objects are immutable, so I instantiated a QueryDict item that is mutable. The crux of the problem is that the value is a byte string of comma separated numbers coming in from a AJAX call in the front end of the application, e.g. U"2,4,6,7". Each key value in the QueryDict is a list of byte strings, [U'2', U'4'] so I need to change the single byte U"2,4,6,7" into a list of byte strings [U'2', U'4', U'6', '7']. The problem however is whenever I try to do a split on the string and assign the request POST key value to that new split string, the key value is a list, in a list. e.g. {'expertise': [[U'2', U'4']]}. I tried a contrived solution by iterating through a split list of the values, and pushing them into the key value of the request POST item, but it gives me the error AttributeError: 'unicode' object has no attribute 'push' In a mutable QueryDict object, if each QueryDict item is a list, and it has no value push, than how is it possible to … -
Django module - include dependencies
I'm building my own Django package to publish it to PyPI. It has some JS dependencies. Some are mine, and some are external. What is the best way to include them? I can keep the js files within the plugin. I think this is something that other django packages do, although it's not very clean, isn't it? Besides I need to check if these external files are already loaded by another package to avoid duplication. A second choice would be to publish a npm package along with the python package, that handles the static files properly. -
Populating existing fields in Django model
I have a model and one of it's fields is defined as blank=True, null=True. I changed both to False and wrote a callable function that returns random strings. I set that function as the default= of that field, and then I ran makemigrations and migrate, but I keep seeing blank fields in my table. Is that expected behaviour? And if so, how can I populate all existing fields? I'm using Django 1.10 -
Passing file upload path from the view (django)
I need to pass the name I want to save the file with in Django view. Best way to do this? I need to be able to do this: if request.method == "POST": file = FileForm(request.POST, request.FILES, path="name_of_the_file") I know that I can save it as the Username if I add an attribute to the model with attribute=models.ForeignKey(User) and then define a get_file_path(instance, filename) and incorporate instance.attribute there but what if I want to pass the name from views? Thank you -
Customer User Authentication error : AttributeError: Manager isn't available; 'auth.User' has been swapped for 'user_management.CustomUser'
I am trying to use email for authenication in Django. In other words I am extending django authentication. I followed all the steps and trust me it worked before. Now it stopped working. this is model.py from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager,PermissionsMixin from django.core.mail import send_mail from django.utils.translation import ugettext_lazy as _ #now=time.strftime('%Y-%M-%D %H:%m:%S.%u%Z') import datetime from datetime import timedelta from django.utils import timezone from django.utils.timezone import now tomorrow = timezone.now() + timedelta(days=1) current_time= timezone.now() class CustomUserManager(BaseUserManager): def _create_user(self,email,password,is_staff,is_superuser, **extra_fields): if not email: raise ValueError('The given email must be set') email=self.normalize_email(email) user= self.model(email=email, is_staff=is_staff, is_active = True, is_superuser =is_superuser, last_login=timezone.now(), date_joined=timezone.now(), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email,password=None,**extra_fields): return self._create_user(email,password,False,False,**extra_fields) def create_superuser(self, email,password,**extra_fields): return self._create_user(email,password,True,True,**extra_fields) class CustomUser(AbstractBaseUser,PermissionsMixin): username =models.CharField(max_length =255, unique = True,blank = True,null= True) email =models.EmailField(blank=False, unique =True) date_joined = models.DateTimeField(_('date joined'), default=now) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD ='email' REQUIRED_FIELD =['user_name','date_joined'] objects=CustomUserManager() class Meta: verbose_name=_('user') verbose_name_plural=_('users') def get_absolute_url(self): return "/user/%s" %urlquote(self.email) def get_full_name(self): a=UserProfile.objects.get(email_id=self.id) self.first_name=a.first_name self.last_name= a.last_name if not self.first_name and not self.last_name: full_name =self.email else: full_name = '%s %s' %(self.first_name,self.last_name) return full_name.strip() def get_short_name(self): self.first_name='a' return self.first_name def email_user(self,subject,message,from_email=None): send_mail(subject,message,from_email,[self.email]) #code class UserProfile(models.Model): email = models.OneToOneField(CustomUser,unique … -
URL parameters vs query parameters in Django
I've looked around for a little while now and can't seem to find anything that even touches on the differences. As the title states, I'm trying to find out what difference getting your data via url path parameters like /content/7 then using regex in your urls.py, and getting them from query params like /content?num=7 using request.GET.get() actually makes. What are the pros and cons of each, and are there any scenarios where one would clearly be a better choice than the other? Also, from what I can tell, the (Django's) preferred method seems to be using url path params with regex. Is there any reason for this, other than potentially cleaner URLs? Any additional information pertinent to the topic is welcome.