Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model audit mixin
Hello I wanted to know how to create a few fields and convert them into a mixin. Let's say I have the following. class Supplier(models.Model): name = models.CharField(max_length=128) created_by = models.ForeignKey(get_user_model(), related_name='%(class)s_created_by') modified_by = models.ForeignKey(get_user_model(), related_name='%(class)s_modified_by') created_date = models.DateTimeField(editable=False) modified_date = models.DateTimeField() def save(self, *args, **kwargs): if not self.id: self.created_date = timezone.now() self.modified_date = timezone.now() return super(Supplier, self).save(*args, **kwargs) I want to create a mixin to avoid writing every time the last 4 fields into different models. Here is the mixin I would create: class AuditMixin(models.Model): created_by = models.ForeignKey(get_user_model(), related_name='%(class)s_created_by') modified_by = models.ForeignKey(get_user_model(), related_name='%(class)s_modified_by') created_date = models.DateTimeField(editable=False) modified_date = models.DateTimeField() def save(self, *args, **kwargs): if not self.id: self.created_date = timezone.now() self.modified_date = timezone.now() return super(Supplier, self).save(*args, **kwargs) class Supplier(AuditMixin): name = models.Charfield(max_length=128) How can I make sure that the related_name is relevant to the class the mixin is included into? Also in the save function, How can I make sure the class the mixin is included into is returned (as per the last line)? Thank you! -
webpack-dev-server not found Django with angular2
I am using Django and Angular2 with webpack.The problem is that django not found webpack-dev.server.js which is declare in index.html like as <% if (webpackConfig.metadata.isDevServer && webpackConfig.metadata.HMR !== true) { %> <!-- Webpack Dev Server reload --> <script src="/webpack-dev-server.js"></script> <% } %> I am totally new with webpack integration with django so can you tell how to integrate django with webpack,which I use in angular2 Or how to provide webpack-dev-server.js file for django. -
Django: How to display author of query of posts?
I'm trying to make individual pages for each author showing their name and posts. I can't seem to get the username displayed. views.py class UserProfileView(generic.ListView): template_name = 'howl/user-profile.html' context_object_name = 'user_howls' def get_queryset(self): author = self.request.user u = User.objects.get(username=author) return Howl.objects.filter(author=u) models.py class Howl(models.Model): author = models.ForeignKey(User, null=True) content = models.CharField(max_length=150) Here is where I'm stuck. user-profile.html {% extends 'howl/base.html' %} {% block content %} <h1>User: {{user_howl.author}}</h1> {% for user_howl in user_howls %} <ul> <li>{{user_howl.content}}</li> </ul> {% endfor %} {% endblock %} The content is displayed just fine, but the heading just says "User: ", how do I give it a context without using a for loop? I've tried: {% for author in user_howls.author %} <h1>User: {{author}}</h1> {% endfor %} and {% if user_howls.author %} <h1>User: {{user_howl.author}}</h1> {% endif %} Still the same outcome, displaying "User: " -
What's the proper structure for my celery tasks in my Django app
My current structure is practice_server\ -bin\ -djcelery\ -include\ -lib\ -src\ -requirements.txt -tasks.py if I run celery worker -A tasks it works but I if I try to follow the way the tutorial suggest like this app1/ - app1/tasks.py - app1/models.py app2/ - app2/tasks.py - app2/models.py and I move my tasks into my blog app like this practice_server\ -bin\ -djcelery\ -include\ -lib\ -src\ -blog\ models.py views.py tasks.py and i run celery worker -A tasks I get this error Traceback (most recent call last): File "/Users/ray/Desktop/myheroku/practice/bin/celery", line 11, in <module> sys.exit(main()) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/celery/__main__.py", line 30, in main main() File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/celery/bin/celery.py", line 81, in main cmd.execute_from_commandline(argv) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/celery/bin/celery.py", line 793, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/celery/bin/base.py", line 309, in execute_from_commandline argv = self.setup_app_from_commandline(argv) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/celery/bin/base.py", line 469, in setup_app_from_commandline self.app = self.find_app(app) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/celery/bin/base.py", line 489, in find_app return find_app(app, symbol_by_name=self.symbol_by_name) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/celery/app/utils.py", line 235, in find_app sym = symbol_by_name(app, imp=imp) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/celery/bin/base.py", line 492, in symbol_by_name return symbol_by_name(name, imp=imp) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/kombu/utils/__init__.py", line 96, in symbol_by_name module = imp(module_name, package=package, **kwargs) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/celery/utils/imports.py", line 101, in import_from_cwd return imp(module, package=package) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in … -
Django cycles and template variables
I have a list of Standard objects of unknown length. I'm trying to split it into three columns when I display them in a template. (before, it was just one big column). I'm looking at using cycle to do that. This works: {% for standard in standard_list %} {% cycle '<div class="col-sm-4"> <div class="panel panel-default" style="width:300px; ">' '' '' '' '' '' '' '' '' '' '' %} {% autoescape off%} <div class="panel-body" style="margin-bottom:2px;">{{standard.Name}} ... </div> {% cycle '' '' '' '' '' '' '' '' '' '</div></div>' %} {% endautoescape %} {% endfor %} ...to split it into 3 columns, each 10 high. So that's my proof-of-concept, but it needs to scale correctly. In the view, I tried a few things, but one being: L = int(ceil(len(standard_list)/3) - 1) cycleopen = " '' " * L This makes a string with the correct number of '', which I then try to use like this: {% for standard in standard_list %} {% cycle '<div class="col-sm-4"> <div class="panel panel-default" style="width:300px; ">' cycleopen %} {% autoescape off%} <div class="panel-body" style="margin-bottom:2px;">{{standard.Name}} ... </div> {% cycle cycleopen '</div></div>' %} {% endautoescape %} {% endfor %} I get a bunch of the '' displaying in … -
How to display parent model with its child model in a template
Here is my structure: model.py class Doctor(models.Model): name = models.CharField(max_length=50) room_no = models.IntegerField() floor_no = models.IntegerField() contact_no = models.CharField(max_length=50, blank=True, null=True) notes = models.CharField(max_length=70, blank=True, null=True) class Meta: managed = False db_table = 'doctor' class DoctorSpecialization(models.Model): doc = models.ForeignKey(Doctor, models.DO_NOTHING) spec = models.ForeignKey('Specialization', models.DO_NOTHING) class Meta: managed = False db_table = 'doctor_specialization' class Specialization(models.Model): title = models.CharField(unique=True, max_length=45) class Meta: managed = False db_table = 'specialization' I would like to display this on my template just like on this post: In django How to display parent model data with child model data in change list view? But the problem is i have many to many relationship structure. I am new to django please your help is highly appreciated. -
Custom create method to prevent duplicates
I would like to add some logic to my serializer.py. Currently it creates duplicate tags (giving a new ID to the item, but often it will match a tag name already). If the field "name" in Tag class exists already, I want it to f In plain english if exists: # Find the PK that matches the "name" field # Add FK to Movie Class else: # Create the "name" inside of Tag class # Add FK to Movie Class The data being posted looks like this: { "title": "Test", "tag": [ { "name": "a", "taglevel": 1 } ], "info": [ ] } Models.py class Tag(models.Model): name = models.CharField("Name", max_length=5000, blank=True) taglevel = models.IntegerField("Tag level", blank=True) def __str__(self): return self.name class Movie(models.Model): title = models.CharField("Whats happening?", max_length=100, blank=True) tag = models.ManyToManyField('Tag', blank=True) def __str__(self): return self.title Serializers class MovieSerializer(serializers.ModelSerializer): tag = TagSerializer(many=True, read_only=False) class Meta: model = Movie fields = ('title', 'tag', 'info') def create(self, validated_data): tags_data = validated_data.pop('tag') movie = Movie.objects.create(**validated_data) for tag_data in tags_data: movie.tag.create(**tag_data) return movie -
How can I get uploaded text file in view through Django?
I'm now making web app. This app gets text file having not-organized data and organize it. I'm now using Django in Python3. I already made form data in templates. Teplates > <form action="/practice/kakao_reader/" method="post"enctype="multipart/form-data">{% csrf_token %} > File: > <input type="file" name="file"/> > <input type="submit" value="UPLOAD" /> > </form> But I have difficulty in getting uploaded file through VIEW. The first code that I've tried was View.py def kakao_reader(request): f = codecs.open(request.FILES['file'], encoding = 'utf-8') data = f.read() And I get invalid file: InMemoryUploadedFile: this error. The specific Error is Environment: Request Method: POST Request URL: http://localhost:8000/practice/kakao_reader/ Django Version: 1.10 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'elections', 'practice'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Python35\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "C:\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python35\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Django\mysite\practice\views.py" in kakao_json 43. f = codecs.open(request.FILES['file'], encoding = 'utf-8') File "C:\Python35\Lib\codecs.py" in open 895. file = builtins.open(filename, mode, buffering) Exception Type: TypeError at /practice/kakao_reader/ Exception Value: invalid file: How can I fix it? thank you. -
Adding Maps in Django with sql database
I need a particular application that requires google maps and it done using postgresql . Can we add maps in django using mysql database ? Is there any snippet for that ? -
Django template rendering + react.js
I'm not fond with rest api + client rendering. I'd like to do initial server rendering with django templates. I'd like React.js be responsible for events handling and client rendering (such as appending new comments) All examples I've seen append react components to some div. Is there a way to attach react components to an existing DOM instead? Is there a guide/sample app which does initial server rendering and use react.js for interactivity? -
Django rest framework, should be able to override get_queryset and not define queryset attribute?
I am confused. Looking through the ViewSet source code it looks like I should be able to not define a queryset in a viewset and then just override the get queryset function to get whatever queryset I want. But my code fails with this error: AssertionError: `base_name` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute. So even if I override the queryset attribute I still need to set it to some fake attribute in the beginning... this works, but it feels weird to define the queryset and then just override it a second later. class StudyQuestion(viewsets.ReadOnlyModelViewSet): queryset = Model.objects.all() serializer_class = ModelSerializer permission_classes = (permissions.IsAuthenticated, ) def get_queryset(self): """""" return Model.objects.order_by('-word__frequency') -
How can I get Upload and get text file through Django?
I'm now making web app. This app gets txt file having not-organized data and organize it. I'm now using -
Filtering between related objects in admin panel
Is there a way to pick the shown objects in the admin panel? for example I have two users, egg and aegon. If I'm looking at the user egg's profile under User transactions I can see all transactions, those for aegon aswell. But I'd like to filter this to only show egg's transactions. models: class transaction(models.Model): amount = models.IntegerField() holding = models.ForeignKey(holding, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return "amount: " + str(self.amount) + " - ip : " + str(self.holding.name) + " - user: " + str(self.user.username) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) ip = models.IntegerField(default=0) ingameName = models.CharField(max_length=50, default='NotSet') userprofit = models.IntegerField(default=0) user_transactions = models.ForeignKey(transaction, on_delete=models.CASCADE, blank=True, null=True) admin: class UserProfileInline(admin.StackedInline): model = UserProfile can_delete = False verbose_name_plural = 'profile' class UserAdmin(UserAdmin): inlines = (UserProfileInline, ) -
Django datatable and enum
I have a campaign model as follows: id campaign objective platform 1 Hello Word MOBILE_APP_ENGAGEMENT Facebook 2 Hi There VIDEO_VIEWS_PREROLL Twitter Model: class Campaign(Model): id = models.TextField(primary_key=True) name = models.TextField(default="") objective = models.TextField(null=True) platform = enumfields.EnumField(Platform, max_length=10, null=True) The campaign holds both Twitter and FB campaigns. The objective field was a free text, but I am not happy with it. I would like to create 2 different enums: class FacebookObjective(Enum): MOBILE_APP_ENGAGEMENT MOBILE_APP_DOWNLOAD class TwitterObjective(Enum): VIDEO_VIEWS_PREROLL TWEET_ENGAGEMENTS and somehow use them on the same column. but not sure how to do it. I thought to use enum, because I need the other uses to use it easily in the code. e.g: TwitterObjective.VIDEO_VIEWS_PREROLL -
Using Node App in Django Project
I am trying to use the Node App Codebox in a new Django project. It seems to me there are already some libraries with kinda do what i want but they all seem to be deprecated (Django-Node). From what i can tell Codebox also only runs on a very old node version (0.10) that might lead to some problems aswell. So i was wondering if any of you guys have any experience. Thanks in advance! -
Insert statment created by django ORM at bulk_create
kind of new to python and django. I am using bulk_create to insert a lot of rows, and as a former DBA i would very much like to see what insert statments are being executed. i know that for querys you can use .query but for insert statments i can't find a command. is there something I'm missing or is there no easy way to see it(a regular print is fine by me)? -
TypeError: object takes no parameters in Django Rest Framework ModelSerializer
I pass my model instances to StopSearchSerializer but it returns: TypeError at /api/v1/search/stop/ object() takes no parameters Am I doing something wrong? views.py > StopSearchView class StopSearchView: class v1(APIView): versioning_class = Versions.v1 model = models.Stop serializer = serializers.StopSearchSerializer def get(self, request, format=FORMAT): """ Searching Stops GET q:int - Query String """ q = request.GET.get("q") if q is None: return Response(status=400) stops = self.model.objects.filter(label__icontains=q) if len(stops) == 0: return Response(204) serializer = self.serializer(stops, many=True) # Error occurs here according to Django error page. if serializer.is_valid(): return Response(serializer.data) serializers.py > StopSearchSerializer class StopSearchSerializer: class v1(serializers.ModelSerializer): """ Searching Stops Version: 1.x """ class Meta: model = models.Stop fields = ["code", "label"] Environment Python 3.5.1 Django 1.9.9 Django Rest Framework 3.4.6 -
FieldDoesNotExist with OneToOne
I want to make gallery for users based on Photologue app. In order to connect users' profiles to photologue's models I want to use OneToOne. Also I want to ... lets say 'override' photologue's get_absolute_url, which is used by templates. # models from photologue.models import Gallery from profiles.models import UserProfile class GalleryExtended(models.Model): gallery = models.OneToOneField(Gallery) user = models.ForeignKey(UserProfile, verbose_name=_('user'), on_delete=models.CASCADE) def get_absolute_url(self): return reverse('profiles_user:profiles_gallery-details', args=[self.user.user_url, self.gallery.slug]) # views from photologue.views import Gallery from profiles.models import UserProfile from .models import GalleryExtended, PhotoExtended def get_user_gallery_queryset(self): user = get_object_or_404(UserProfile, user_url=self.kwargs['user_url']) gallery = Gallery.objects.filter(galleryextended__user=user) return gallery class ProfileGalleryDateView(object): date_field = 'date_added' allow_empty = True get_queryset = get_user_gallery_queryset # site.com/username/gallery (shows photos + images with a filter by year) class ProfileGalleryPhotoArchiveIndexView(ProfileGalleryDateView, ArchiveIndexView): template_name = 'galleries/gallery_n_photo_archive.html' So in view if I do gallery = Gallery.objects.filter(galleryextended__user=user) templates start to use Photologue's get_absolute_url (I do not use the corephotologues url url(r'^photologue/', include('photologue.urls', namespace='photologue')), as I integrate the app in my own url schema) Is it possible to revert to something like this gallery = GalleryExtended.objects.filter(user=user).***(get fields from Gallery)*** and avoid django.core.exceptions.FieldDoesNotExist: GalleryExtended has no field named 'date_added' in order to start using get_absolute_url from GalleryExtended? I know, it can easily be solved by extending photologues model via inheritance, … -
Django rest_framework IsAdminUser not behaving
I have a viewset in rest framework that is not behaving like I would expect. If I login with a non-staff user and navigate to the api-url/users I can see all the users listed there. The IsAuthenticated permission is working, because if I logout I cget an error saysing that I am not authenticated. Am I using these permissions wrong? I have done the tutorial and looked through the docs, but I can't find anything to tell me why this shouldn't work views: class UserViewSet(viewsets.ModelViewSet): """Viewset for viewing users. Only to be used by admins""" queryset = LangaLangUserProfile.objects.all() serializer_class = UserSerializer filter_backends = (filters.DjangoFilterBackend, ) filter_fields = '__all__' permissions_classes = (permissions.IsAdminUser, ) class LanguageViewSet(viewsets.ReadOnlyModelViewSet): """Viewset for Language objects, use the proper HTTP methods to modify them""" queryset = Language.objects.all() serializer_class = LanguageSerializer filter_backends = (filters.DjangoFilterBackend, ) filter_fields = '__all__' permissions_classes = (permissions.IsAuthenticated, ) urls: router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'language', views.LanguageViewSet) serializers: class UserSerializer(serializers.ModelSerializer): """Serializer for User objects""" class Meta: model = LangaLangUserProfile fields = '__all__' class LanguageSerializer(serializers.ModelSerializer): """Serializer for the Language model""" class Meta: model = Language fields = '__all__' depth = 2 -
django rest framework jwt authentication with email and password
I have a django project and i use django rest framework for my REST APIs and use JWT for authentication. I was wondering if its possible to configure JWT to authenticate users by email and password instead of username and password. I figure i can extend and override key parts of the JWT (which will be as if i was writing JWT from scratch) but i was wondering if there is a configurable way of doing so. Thanks. -
1062, "Duplicate entry '3' for key 'user_id'"
Whenever I try to create a user through the admin panel I get this error. I've not idea why. There's only one user in auth_user in my database. error: django.db.utils.IntegrityError: (1062, "Duplicate entry '3' for key 'user_id'") my models: class transaction(models.Model): amount = models.IntegerField() holding = models.ForeignKey(holding, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return "amount: " + str(self.amount) + " - ip : " + str(self.holding.name) + " - user: " + str(self.user.username) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ip = models.IntegerField(default=0) ingameName = models.CharField(max_length=50, default='NotSet') userprofit = models.IntegerField(default=0) user_transactions = models.ForeignKey(transaction, on_delete=models.CASCADE, blank=True, null=True) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(create_user_profile, sender=User) -
Refreshing a specific div every few seconds in django using javascript
I am trying to refresh the content of a table in my html page using javascript every few seconds in the django framework. Here is my code: urls.py url(r'^specialScoreboard/$', views.specialScoreboard.as_view(), name='specialScoreboard'), url(r'^specialScoreboardDiv/$', views.specialScoreboardDiv , name='specialScoreboardDiv'), views.py class specialScoreboard(generic.ListView): template_name = 'CTF/specialScoreboard.html' context_object_name = 'teams' @method_decorator(login_required) @method_decorator(never_ever_cache) def dispatch(self, request, *args, **kwargs): if getAnyActiveGame and request.user.is_staff: return super(specialScoreboard, self).dispatch(request, *args, **kwargs) else: return HttpResponseRedirect(reverse('CTF:no_active_game')) def get_queryset(self): """ ordering teams by score """ game = getAnyActiveGame() teams = get_teams_from_game(game) return sorted(teams, key=lambda a: a.get_score(game), reverse=True) def specialScoreboardDiv(): game = getAnyActiveGame() teams = get_teams_from_game(game) sortedList = sorted(teams, key=lambda a: a.get_score(game), reverse=True) return render_to_response('CTF/specialscoreboardDiv.html' , {'sortedList' :sortedList}) scoreboardRefresh.js + scoreboardDiv.html < script > var scoreboardURL = '{% url ' CTF: specialScoreboardDiv ' %}'; function refresh() { $.ajax({ url: scoreboardURL, success: function(data) { $('#scoreboardDiv').html(data); } }); }; $(document).ready(function($) { refresh(); setInterval("refresh()", 3000); }) < /script> <div class="panel panel-info"> <div class="panel-heading">Scoreboard</div> <div class="panel-body"> <div class="table-striped"> <table id="scoreboardDiv" class="table table-hover"> <thead> <tr> <th>#</th> <th>Team Name</th> <th>Score</th> </tr> </thead> <tbody> {% for team in teams %} <tr> <td>{{forloop.counter}}</td> <td>{{team.name}}</td> <td>{{team|getScoreTeam}}</td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> I keep getting 500 error when refreshing the page, internal server error. Could someone enlighten the reason this is … -
Django Auth Views Not Logging Users in
I have a custom admin-compliant User model according to the example in the django documentation. When I try logging in through the Django Auth Login, it says username and password do not match. In the command-line, I get a 200 response code [11/Sep/2016 08:26:38] "POST /accounts/login/ HTTP/1.1" 200 4014 My User model is set up to use Email and Password to login not Username. I log in fine through the admin page. I would like to know why this is happening and how to fix this. Thank you -
Django: How to implement user profiles?
I'm making a Twitter clone and trying to load profile pages. My logic was to start simple and find all tweets that match a certain author and load those tweets on a page as the user's profile. I really don't know where to start. urls.py url(r'^users/(?P<username>\w+)/$', views.UserProfileView.as_view(), name='user-profile'), models.py class Howl(models.Model): author = models.ForeignKey(User, null=True) content = models.CharField(max_length=150) views.py class UserProfileView(DetailView): """ A page that loads howls from a specific author based on input """ model = get_user_model() context_object_name = 'user_object' template_name = 'howl/user-profile.html' user-profile.html {% block content %} <h1>{{user_object.author}}</h1> {% endblock %} I'm currently getting an error that says "Generic detail view UserProfileView must be called with either an object pk or a slug." I also went on the shell and tried Howl.objects.filter(author="admin") But got ValueError: invalid literal for int() with base 10: 'admin' -
Add event on django admin dropdrown field
I am new to Django, I would like to add an onchange event on a dropdown field of django admin. i have model Subcategory which Contain Field Department and Category which are foreign key i would like to add onchange event on Department