Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Equivalent Form field for Model field Bigintegerfield in Django
Django has an inbuilt Model field called BigIntegerField, but it does not have a corresponding Form field, and there is only an IntegerField available for use with forms. Is there any problem with this mismatch? I want to store phone numbers in these fields (10-digits), so the IntegerField Model class cannot store all positive 10-digit values as it is only up to 2147483647. -
cant figure out how to hash passowrd django
I am working on a project and I have a form where a user enters username email and passowrd. I want to hash the password and save it. I notices that when i create the user through the admin page, it automatically creates the password and hashes it before it is saved. I want to do the same thing. is there any way for me to do that... This is what I have right now for the view... def signup(request): # the following will determine if the form is submitted or not if request.method == 'POST': form = SignupForm(request.POST) # the following section validates the entire form and processed the data if form.is_valid(): # the following will make sure the data is clean and then store them # into new variables cd = form.cleaned_data username = cd['username'] password = cd['password'] verify = cd['verify'] email = cd['email'] # the folloiwng will make sure the password and verification are matching # before storing the info into the database if password == verify: new_user = User.objects.create( username = username, password = password, email = email, ) # the following will store the username of the account that was just # created in to … -
Django models relationship collision
I'm django learner and i have problem with django relationship concept. I have written two models that have relations with single source model (UserProfile).but one of them does not work properly.The Message class work fine with it's two fields (sender,receiver),but the other class(Class) lead to programing error:relation "CEA_class" already exists where CEA is my app name.I really prefer to have two different field for the class and don't join them as single field.What I'm suppose to do with it? class Message ---->that work fine class Message(models.Model): sender=models.ForeignKey(UserProfile,blank=False,related_name="sender") receiver=models.ForeignKey(UserProfile,blank=False,related_name="receiver") content=models.CharField(max_length=200) priority=models.BigIntegerField(choices=PRIORITY_LIST,default=1) class Class ---->that lead to error class Class(models.Model): subject=models.CharField(max_length=20) time=models.CharField(max_length=20) day=models.CharField(max_length=20) location=models.CharField(max_length=20) students=models.ManyToManyField(UserProfile,blank=True,related_name="students") master=models.ForeignKey(UserProfile,blank=True,related_name="master") -
Django Mock Test - Caching GraphQL Query
The code below is my attempt to cache the response of a graphql query and a test to make sure the content is getting cached. I got this error: 'self' parameter lacking default value and it appears when running the test... Does anyone know what may be the issue? Is it a wrong implementation of mock? I feel like I can't think of any other way to write the test... This is the code that appears on the view: def fetch_cache_key(request): """ Returns a hashed cache key. """ m = hashlib.md5() m.update(request.body) return m.hexdigest() class GraphQLView(StaticApiKeyOrInternalMixin, GraphQLView): """ GraphQL view for clients that use an API key. """ def super_call(self, request, *args, **kwargs): """ Returns dispatch response """ response = super(GraphQLView, self).dispatch(self, request, *args, **kwargs) return response def dispatch(self, request, *args, **kwargs): """ Fetches queried data from graphql and returns cached & hashed key """ cache_key = fetch_cache_key(request) response_text = cache.get(cache_key) if not response_text: response = self.super_call(request, *args, **kwargs) # cache key and value (all text) cache.set(cache_key, response.text, 300) else: response = HttpResponse(content='response_text', content_type='application/json', status=200) return response This is the code that appears in the test: class TestGraphqlView(SimpleTestCase): nosegae_datastore_v3 = True nosegae_memcache = True nosegae_taskqueue = True def setUp(self): self.client … -
Django Rest Framework : Upload Image API
I am trying to upload image to my django website through django rest framework api. but I am getting this error { "detail": "Multipart form parse error - Invalid boundary in multipart: None" } views.py class UploadPhotoViewSet(APIView): parser_classes = (parsers.MultiPartParser, parsers.FormParser) def get(self, request, format=None): model_object = Photo.objects.all() serializer = PhotoSerializer(model_object, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = PhotoSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class PhotoSerializer(serializers.ModelSerializer): thumbnail = serializers.ImageField(use_url=True) source = serializers.ImageField(use_url=True) class Meta: model = Photo fields = '__all__' model.py class Photo(models.Model): type = models.CharField(max_length=100, default='photo', editable=False) project = models.ForeignKey(Project, on_delete=models.CASCADE) title = models.CharField(max_length=100) description = models.TextField() category = models.CharField(max_length=255) def upload_thumb_dir(self, filename): path = '/media/{}/photos/thumbs/{}'.format(self.project.id, filename) return path thumbnail = models.ImageField(upload_to=upload_thumb_dir, default='/default/photo.png', blank=True) def upload_photo_dir(self, filename): path = '/media/{}/photos/{}'.format(self.project.id, filename) return path source = models.ImageField(upload_to=upload_photo_dir) def __str__(self): return self.title -
Celery is not receiving task when running django project with uwsgi
When I'm running my django project with manage.py celery is working. But, when deploying the project with uwsgi it is not. Command to run celery: celery --app=project.celery:app worker --loglevel=INFO To start uwsgi, I'm using following script: #!/bin/bash uwsgi --chdir=~/tender \ --module=project.wsgi:application \ --env DJANGO_SETTINGS_MODULE=project.settings \ --master \ --protocol=http \ --pidfile=/tmp/project-master.pid \ --socket=0.0.0.0:6969 \ --processes=5 \ --uid=1000 \ --gid=1000 \ --harakiri=20 \ --max-requests=5000 \ --vacuum \ --home=~/.virtualenv3/tendervenv \ --daemonize=~/tender.log \ echo "uWSGI started" -
JQuery Infinite scrolling with Waypoints slight error with event listener
def index(request): blocks=Block.objects.all().order_by('-posted_on') page = request.GET.get('page', 1) paginator = Paginator(blocks, 10) try: block_list = paginator.page(page) except PageNotAnInteger: block_list = paginator.page(1) except EmptyPage: block_list = paginator.page(paginator.num_pages) context={ 'block_form':Block_form(), 'comment_form':Comment_form(), 'pieces':Piece.objects.filter(visibility=True).order_by('-created_on')[:10], 'block_list':block_list, 'request': request } return render(request, 'writers_block/index.html', context) I have a paginated Django view, and I've used Waypoints to load more objects after each 10 instances. var infinite= new Waypoint.Infinite({ element: $('.infinite-container')[0], onBeforePageLoad: function() { $('.loading').show(); }, onAfterPageLoad: function() { $('.loading').hide(); } }); But the problem is, with infinite scrolling all my event listeners won't work on instances after the first 10. For eg, click handlers on the first 10 instances work, but no javascript work on the next 10 instances which get loaded. This is does not happen in normal pagination. -
Filtering objects through a range of object attribute in Django-rest-framework
I am making a Rest API in Django Rest Framework for which I have a model which stores data like this- class Commodity(models.Model): def countryname(self): return self.country.country_name country=models.ForeignKey(Country) commodity_name=models.CharField(max_length=255) commodity_type=models.IntegerField(choices=COMMODITY_TYPE) commodity_year=models.IntegerField(default=None) commodity_production=models.IntegerField(default=None) def __unicode__(self): return self.commodity_name +"-"+str(self.country.country_name) Now I want to get all those objects which fall in a range of commodity_year, for example, all those object whose 'commodity_year' is between 1999 to 2014(both inclusive). I have been using Django-filter class for this but got no luck. class CommodityFilter(filters.FilterSet): start_date = DateFilter(name='commodity_year' ) end_date = DateFilter(name='commodity_year') class Meta: model = Commodity fields = [ 'country','commodity_name', 'commodity_type','start_date','end_date'] class CommodityList(generics.ListCreateAPIView): queryset = Commodity.objects.all() serializer_class = CommoditySerializer filter_backends = (filters.DjangoFilterBackend,) filter_class = CommodityFilter permission_classes = [AllowAny] If anyone has a better approach please guide me. -
Django Form gives error on validation - UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 12: ordinal not in range(128)
This is my form class DynamicQuizForm(forms.Form): def __init__(self, patient, *args, **kwargs): super(DynamicQuizForm, self).__init__(*args, **kwargs) question_qset = modelQuizQuestion.objects.filter(patient=patient) counter = 0 for question in question_qset: counter+=1 #Construct choices choice_qset = modelQuizChoice.objects.filter(question=question) main_choices = [] for choice in choice_qset: small_choices = [] small_choices.append(choice.choice) small_choices.append(choice.choice) main_choices.append(small_choices) self.fields[question.question] = forms.ChoiceField(choices=main_choices, widget=forms.RadioSelect(), ) and this is how I am using it if request.method == "POST": quizForm = DynamicQuizForm(patient=patient_qset,data=request.POST) if quizForm.is_valid(): #<------------ gives exception here ..... Any suggestions why this might be happening. I looked at these two links link1 and link2 however it seems like it is a unicode issue and the answers recommend to use decode instead of str. Howeever in my code i am not using str anywhere -
Creating an updating search form
I am trying to create a form that updates results as the user types. I followed the tutorial from the link below, but I am not able to figure out where I am going wrong or how to fix it. Link To Tutorial This is the error that is logged upon inspection in Chrome: jquery.min.js:4 GET //127.0.0.1:8080/student/account/%7B% 404 (Not Found). I am not sure where the '%7B%' is coming from. I am able to print 'q', therefore I am confused on why it is not being appended to the url. Instead of the '%7B%' at the end of the url I should have '?q=search_term' This is my views: @login_required def student_account(request): courses = Course.objects.filter(student=request.user.id) context = {"courses": courses,} if request.is_ajax(): q = request.GET.get("q") if q is not None: courses_searched = Course.objects.filter( Q(name__icontains=search) | Q(professor__first_name__icontains=search) | Q(days__icontains=search) ).distinct() context.update({"courses_searched": courses_searched}) return render(request, 'courses_searched_results.html', context) return render(request, "my_app/student_account.html", context) courses_searched_results.html {% if courses_searched|length %} <ul class="list-group"> {% for course in courses_searched %} <li class="list-group-item"> {{course.name }} <form method="POST" id="add_course" action="{% url 'my_app:add_course' course.id %}"> {% csrf_token %} <button type="submit" class="btn btn-default">Add Course</button> </form> </li> {% endfor %} </ul> {% else %} <div class=”note”> No Courses Found. </div> {% endif %} student_account.html <div> … -
How to filter django tables2 results for unique values of a specific column
I have a django tables2 table working pretty well where it only shows Querysets that have the correct Project Id. I need it to exclude Querysets that have duplicate user_id's though. example: user a, week 1, Project 1 user a, week 2, Project 1 user b, week 1, Project 1 display users that are assigned to Project 1. (needed result is table with rows a & b) What I have so far: #models.py class Allocation(models.Model): user_id = models.ForeignKey(Resource) project_id = models.ForeignKey(Project) week = models.DateField(default=timezone.now) allocated_hours = models.IntegerField(default=0) actual_hours = models.IntegerField(default=0) #tables.py class Project_Resource_table(tables.Table): role = tables.Column(accessor='user_id.resource_type') name = tables.Column(accessor='user_id.resource_name') allocation = tables.Column(accessor='total_allocation') class Meta: model = Allocation exclude = ('id', 'user_id', 'project_id', 'week', 'allocated_hours', 'actual_hours') sequence = ('role', 'name', 'allocation') #view (project_profile.py) def project_properties(request, offset): try: offset = int(offset) except ValueError: raise Http404() project = Project.objects.get(pk=offset) table = Project_Resource_table(Allocation.objects.filter(project_id=offset).order_by('user_id')) return render(request, '../templates/copacity/project_profile.html', { 'table': table, }) I have tried using set() but to no avail. Also tried distinct() but does not work with sqlite3 db. Also tried calculating with a function, but kept getting "Expected table or queryset, not function". Any suggestions on what else to try? -
Django with PostgreSQL
Hi all I am currently working on this project called "The NOC Project". https://kb.nocproject.org/ I am quite new to Django Programming and I can't seem to find how they display the data. I look into the templates but can't seem to find it. Just wondering for those who have done django python with postgresql,are the pulling of data in python or .html? -
Django UpdateView get_context_data function called twice
Here is the thing: I have two models - Group and Storage.And I want to update the data.But my model Group can update my data,and my model Storage can't.So I debug my code,and find the reason why my Storage data can't update: the funtion get_context_data() called twice.Once on the page load,Twice on the form post.But function form_valid isn't called. All same code,but different result.Someone can tell me why this happen? Thanks Code: class Group(models.Model): id=models.AutoField(primary_key=True) name=models.CharField(max_length=100,default='') info=models.CharField(max_length=100,default='') class Storage(models.Model): id=models.AutoField(primary_key=True) disk_size=models.CharField(max_length=100,default="") disk_path=models.CharField(max_length=100,default="") info=models.CharField(max_length=100,default="") class ManagerStorageUpdateView(LoginRequiredMixin,UpdateView): model = models.Storage form_class = forms.StorageCreateUpdateForm template_name = 'new_update_storage.html' success_url = reverse_lazy('manager:storage') def get_context_data(self, **kwargs): context = super(ManagerStorageUpdateView, self).get_context_data(**kwargs) hosts = models.Host.objects.all() storage_hosts = [host.id for host in self.object.hosts.all()] context.update({ 'hosts':hosts, 'storage_hosts':storage_hosts }) return context def form_valid(self, form): host_storage = form.save() hosts_id_list = self.request.POST.getlist('hosts',[]) hosts = models.Host.objects.filter(id__in=hosts_id_list) host_storage.hosts.clear() host_storage.hosts.add(*hosts) host_storage.save() return super(ManagerStorageUpdateView,self).form_valid(form) def get_success_url(self): return self.success_url -
How to render a NVD3 line chart in Django?
I created the linechart content in views.py, and was trying to load the chart to the body of the html file. however, the chart was not loaded. And it only shows the chart data numbers. View.py def index(request): xdata = [1,2,3] ydata = [2,4,6] chartdata = {'x': xdata, 'y': ydata} charttype = "lineChart" chartcontainer = 'linechart_container' lineChartData = { 'charttype': charttype, 'chartdata': chartdata, 'chartcontainer': chartcontainer, template = loader.get_template('index.html') context = {'lineChartData':lineChartData} return HttpResponse(template.render(context,request)) index.html <link media="all" type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.5/nv.d3.css"> <script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script> <script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.5/nv.d3.min.js"></script> <body> {{lineChartData}} </body> -
Install python 3.6 mysqlclient for Django project on Centos
I have successfully installed a Django project on my CentOS 6.9. I have installed the project in a virtual environment which I have created using python3.6 python3.6 -m venv env I have activated the virtual env and I am now trying to run the app using; python manage.py runserver 0.0.0.0:8000 When I run this command I get the following error; Unhandled exception in thread started by .wrapper at 0x7f7f7c5d67b8> Traceback (most recent call last): File "/REMOVED/REMOVED/python3.6/env/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 26, in import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/REMOVED/REMOVED/python3.6/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/REMOVED/REMOVED/python3.6/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/REMOVED/REMOVED/python3.6/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/REMOVED/REMOVED/python3.6/env/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/REMOVED/REMOVED/python3.6/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/REMOVED/REMOVED/python3.6/env/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/REMOVED/REMOVED/python3.6/env/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/REMOVED/REMOVED/python3.6/env/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in … -
Django blog how to display latest post every page if used paginator
I have a problem with display latest posts in my django blog. I used paginator but now I can't eliciting latest posts every page. views.py def post_list(request): post_list = Post.objects.all() page = request.GET.get('page') paginator = Paginator(post_list, per_page=3) try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator(paginator.num_pages) return render(request, 'blog/post_list.html', {'posts': posts,'page': page}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) models.py class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() image = models.FileField(upload_to='images/') created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class Meta: ordering = ('-published_date',) forms.py from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ( 'title', 'text', 'image', ) urls.py urlpatterns = [ url(r'^$', views.post_list, name='post_list'), url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail, name='post_detail'), url(r'^post/new/$', views.post_new, name='post_new'), url(r'^post/(?P<pk>[0-9]+)/edit/$', views.post_edit, name='post_edit'), url(r'^about$', views.about, name='about'), url(r'^projects$', views.projects, name='projects'), ] post_list.html <div class="widget"> <h3> Latest Posts </h3> <ul class="list-group"> {% for post in posts %} <li class="list-group-item"><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title|truncatewords:5 }}</a></li> {% endfor %} </ul> </div> <div class="widget"> Now /?page=1 shows 3 latest posts, /?page=2 shows just one latest post (from 4 available) … -
Stange error when trying to migrate model changes django
I am just trying to migrate model changes that I have made to a django project and all I did was add two new columns to the model. Now I am trying to migrate it and I am getting this error below and I dont know where it came from or how to fix it... none of the files that are causing the errror in the traceback are familiar to me. Can anyone help. Here is the error Running migrations: Rendering model states... DONE Applying tab.0027_auto_20170807_1753...Traceback (most recent call last): File "C:\Users\OmarJandali\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Users\OmarJandali\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\sqlite3\base.py", line 318, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: tab_notification here is my models.py file class Activity(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) #server group = models.ForeignKey(Group, on_delete=models.CASCADE, null=True) #server description = models.CharField(max_length=200) #server status = models.SmallIntegerField(default=1) category = models.SmallIntegerField(default=1) created = models.DateTimeField(auto_now_add=True) #server class Notification(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # server description = models.CharField(max_length=200) # server status = models.SmallIntegerField(choices=NOTIFICATION_STATUS_CHOICES, default=1) # server category = models.SmallIntegerField(choices=NOTIFICATION_CATEGORY_CHOICES, default=1) # server created = models.DateTimeField(auto_now_add=True) # server class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # server first_name = models.CharField(max_length=25, default='first') last_name = models.CharField(max_length=25, default='last') age = models.IntegerField(default=0) city = models.CharField(max_length=45) # user … -
Django file image extension
i need help. I need upload file and file is a image, i need resizer to 50 x 50. I think is a stupid error, but i can't see This my code from django.shortcuts import render from django.template import RequestContext from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from PIL import Image import os from myproject.appupload.models import Document from myproject.appupload.forms import DocumentForm def list(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) if newdoc.docfile.name == '.jgp': size = (50, 50) img = Image.open(newdoc) img.thumbnail(size) img.save() newdoc.save() return HttpResponseRedirect(reverse('list')) else: form = DocumentForm() documents = Document.objects.all() return render( request, 'list.html', {'documents': documents, 'form': form} ) Where is my error? -
Facebook Login and django-social-auth how to debug
I'm using (python-social-auth)[http://python-social-auth.readthedocs.io/en/latest/backends/facebook.html#oauth2] to login to Facebook, the thing is that suddenly it stop working. The error that I'm getting is Login Error: There is an error in logging you into this application. Please try again later.. I updated the code of python-social-auth to ```social-auth-core==1.4.0``, so I know I'm using facebook's 2.9 version. Is there another way to debug what's going on? -
How to keep relative path in Django templates?
I have imported a front-end project including completed .css, .js, .html files into Django templates. They can work when run .html directly. But if run them in Django server, all links with relative path should be modified as Django style such as <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}" /> instead of <link rel="stylesheet" type="text/css" href="css/style.css" />. Is there any method to keep the orginal relative path in .html file and also can run in Django? -
Backend and frontend on separate Heroku instances
I'm building a single page app with an Angular frontend and a Django Rest API on the backend. I intend to deploy the app with Heroku. My understanding is that there are two approaches that I can take: Use nginx as a reverse proxy, allowing communication between the server and the client. Deploy two separate Heroku instances, one for the API (e.g. myapp.com/api) and a second for the Angular App (e.g. myapp.com). The frontend would be hosted at myapp.com and make requests to myapp.com/api. Now for my question: Is one of these approaches better than the other? Is one approach more secure than the other? Note: I'm using Angular 4 with the angular cli. -
Django static_url when script_name set?
So I'm trying to run multiple instances of Django on a server for now, one under /dev, one under /test, etc.. The web server is setting the correct SCRIPT_NAME setting and I can serve pages, templates, the whole admin panel fine, except for static assets. Static assets are served by Django using WhiteNoise. The application is supposed to use the value of SCRIPT_NAME as the static URL, ie all static assets are served from the application root. So far I've tried the following settings against the admin panel: # SCRIPT_NAME = '/dev' Set in env # URL for static assets should be `/` STATIC_URL = '/' # Browser looks for static assets in `/`, drops script_name STATIC_URL = None # Browser looks for static assets in `/`, drops script_name STATIC_URL = `/dev/` # Browser looks for static assets in '/dev/dev/` I'm wondering if I'm missing a setting here or if the problem might be elsewhere. Going by the docs I understand that STATIC_URL = '/' should work? -
Django REST framework - multiple lookup fields?
I have a model that more or less looks like this: class Starship(models.Model): id = models.UUIDField(default=uuid4, editable=False, primary_key=True) name = models.CharField(max_length=128) hull_no = models.CharField(max_length=12, unique=True) I have an unremarkable StarshipDetailSerialiser and StarshipListSerialiser (I want to eventually show different fields but for now they're identical), both subclassing serializers.ModelSerializer. It has a HyperlinkedIdentityField that refers back to the (UU)ID, using a home-brew class very similar to the original HyperlinkedIdentityField but with capability to normalise and handle UUIDs: class StarshipListSerializer(HyperlinkedModelSerializer): uri = UUIDHyperlinkedIdentityField(view_name='starships:starship-detail', format='html') class Meta: model = Starship fields = ('uri', 'name', 'hull_no') Finally, there's a list view (a ListAPIView) and a detail view that looks like this: class StarshipDetail(APIView): """ Retrieves a single starship by UUID primary key. """ def get_object(self, pk): try: return Starship.objects.get(pk=pk) except Starship.DoesNotExist: raise Http404 def get(self, request, pk, format=None): vessel = self.get_object(pk) serializer = StarshipDetailSerialiser(vessel, context={'request': request}) return Response(serializer.data) The detail view's URL schema is currently invoking the view based on the UUID: ... url(r'vessels/id/(?P<pk>[0-9A-Fa-f\-]+)/$', StarshipDetail.as_view(), name='starship-detail'), ... I now want users to be able to navigate and find the same vessel not just by UUID but also by their hull number, so that e.g. vessels/id/abcde1345...and so on.../ and vessels/hull/H1025/ would be able to resolve to … -
Adding Collapsible fields in django-grappelli
The current django-grappelli documentation specifies how to define collapsibles for a ModelAdmin. In the case of ModelAdmin the following example is given: class ModelOptions(admin.ModelAdmin): fieldsets = ( ('', { 'fields': ('title', 'subtitle', 'slug', 'pub_date', 'status',), }), ('Flags', { 'classes': ('grp-collapse grp-closed',), 'fields' : ('flag_front', 'flag_sticky', 'flag_allow_comments', 'flag_comments_closed',), }), ('Tags', { 'classes': ('grp-collapse grp-open',), 'fields' : ('tags',), }), ) From reading the documentation it is not clear where in a Django project the code block above would live. Does it go into [project_name]/[app_name]/admin.py? -
How can I tag/refer user with @ like in facebook or twitter?
There is something for tag user in django? I have a field, and I want that only have a name, can be a tag to an existing user(search with @), or it can just a name(not existing user). In addition to this, I want to bring a user's card if it have @mention, and default card just for not existing user. Thanks in advance.