Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django/Python I relate an object (A) to two instances of another object (B) so that if I call B.A_set.all(), it works for either instance of B
I have written a modified ELO rating system for FIFA. I want to show an ELO leaderboard with players (I can produce this), show a game history, and also have the option to select a player and see their personal game history. My intended version of the classes is presented below. I can produce the leaderboard and game history if I set the player1 and player2 attribute of Game to a string and define the name manually but I want the game and players to be related. When I try to migrate this solution presented to mySQL this is the error message ERRORS: blog.Game.player1: (fields.E304) Reverse accessor for 'Game.player1' clashes with reverse accessor for 'Game.player2'. HINT: Add or change a related_name argument to the definition for 'Game.player1' or 'Game.player2'. blog.Game.player2: (fields.E304) Reverse accessor for 'Game.player2' clashes with reverse accessor for 'Game.player1'. HINT: Add or change a related_name argument to the definition for 'Game.player2' or 'Game.player1'. Models.py folder within django from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Player(models.Model): name = models.CharField(max_length=100) elo = models.IntegerField() date_added = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.name) + " = " + str(self.elo) + " - Joined " + str(date_add) class … -
Django widget not required by form despite setting
I have a form widget which is not required (no validation, no HTML attribute set to required) in a form despite me setting it explicitly in the form constructor (as suggested in this SO question): users/forms.py: from wagtail.admin.rich_text import get_rich_text_editor_widget class UpdateProfileForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UpdateProfileForm, self).__init__(*args, **kwargs) self.fields['bio'].required = True class Meta(): model = _user_profiles.__model__ fields = ( 'email', 'first_name', 'last_name', 'organisation', 'bio', 'city', 'country', 'photo_file' ) widgets = { 'bio': get_rich_text_editor_widget('submission') } If I set a breakpoint in users/views.py I can see that all the way until the end of the stack, the form field is correctly set to 'required'=True, just like the email field which the form correctly requires, and unlike city which it does not require: users/views.py: > /root/.pyenv/versions/3.7.2/lib/python3.7/site-packages/django/views/generic/base.py(151)get() 150 context = self.get_context_data(**kwargs) --> 151 return self.render_to_response(context) 152 ipdb> context['form'].fields['bio'].required True ipdb> context['form'].fields['email'].required True ipdb> context['form'].fields['city'].required False Any ideas why the field is not required? -
Passing ForeginKey to CreateView from url
I've been using examples from Django documentations, but so far it is not solving my problem: https://docs.djangoproject.com/en/1.9/topics/class-based-views/generic-editing/#models-and-request-user So basicly I have this model: models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Trip, on_delete=models.CASCADE) urls.py path('trip/<int:pk>/discussion/', PostCreate.as_view(), name='trip-detail-discussion'), views.py # 1st attempt class PostCreate(CreateView): model = Post template_name = 'tripplanner/postcreate.html' fields = ['title', 'content'] success_url = '/' def form_valid(self, form, **kwargs): context = super(PostCreate, self).get_context_data(**kwargs) context['pk'] = self.kwargs['pk'] form.instance.author = self.request.user form.instance.group = context.get('pk') # print(self.trip) print(form.instance.group) return super(PostCreate, self).form_valid(form) # 2nd attempt class PostCreate(CreateView): model = Post template_name = 'tripplanner/postcreate.html' fields = ['title', 'content'] success_url = '/' def dispatch(self, request, *args, **kwargs): self.trip = get_object_or_404(Trip, pk=kwargs['pk']) return super(PostCreate, self).dispatch(request, *args, **kwargs) def form_valid(self, form): form.instance.author = self.request.user form.instance.group = self.trip.id print(form.instance.group) return super(PostCreate, self).form_valid(form) Both attempts give me this error: Cannot assign "1": "Post.group" must be a "Trip" instance. Any ideas how to pass this to db? -
How to add external file paths to django when hosting the project in Heroku
The code includes some paths to some external files in the django project. eg- the path for stanfordpostager.jar, path for java jdk. The project is successfully running in the localhost but the push rejects when pushing the project to Heroku. Its a FileNotFoundError. The code:- cred = credentials.Certificate("../locationnewstest/news/newsapp.json") jar = '../locationnewstest/stanford-postagger-2018-10-16/stanford-postagger.jar' model = '../locationnewstest/stanford-postagger-2018-10-16/models/english-left3words-distsim.tagger' java_path = "C:/Program Files/Java/jdk1.8.0_101/bin/java.exe" os.environ['JAVAHOME'] = java_path nltk.internals.config_java('C:/Program Files/Java/jdk1.8.0_101/bin/java.exe')``` The output:- remote: FileNotFoundError: [Errno 2] No such file or directory: '../locationnewstest/news/newsapp.json' remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. -
How do I parameterise DRF API url?
I wrote an API with the following regex url format which doesn't conform to what I wanted. How do I go about this? any help is appreciated. Thanks in anticipation. What I want http://sample.com/app/check/?id=any_id_passed_into_the_url What I have: http://sample.com/app/check/id What I did # app/urls.py urlpatterns = [ url(r'^app/', include('modul.urls', namespace='modul')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # modul/urls.py from django.conf.urls import url from modul.views import OfferView urlpatterns = [ url(r'^check/(?P<id>[0-9]+)/$', OfferView.as_view(), name='id') ] -
Error during backward migration of DeleteModel in Django
I have two models with one-to-one relationship in Django 1.11 with PostgreSQL. These two models are defined in models.py as follows: class Book(models.Model): info = JSONField(default={}) class Author(models.Model): book = models.OneToOneField(Book, on_delete=models.CASCADE) The auto-created migration file regarding these models is like: class Migration(migrations.Migration): dependencies = [ ('manager', '0018_some_migration_dependency'), ] operations = [ migrations.CreateModel( name='Book', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('info', JSONField(default={})), ], ), migrations.AddField( model_name='author', name='book', field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='manager.Book'), ), ] These implementations have worked successfully. In addition to this migration, we also had some other additional migrations related to other tasks of our project. Due to our design changes we made today, we decided to move all of the Book info data into our cloud storage. In order to do that, I have implemented a custom migration code as follows: def push_info_to_cloud(apps, schema_editor): Author = apps.get_model('manager', 'Author') for author in Author.objects.all(): if author.book.info is not None and author.book.info != "": # push author.book.info to cloud storage author.book.info = {} author.book.save() def pull_info_from_cloud(apps, schema_editor): Author = apps.get_model('manager', 'Author') Book = apps.get_model('manager', 'Book') for author in Author.objects.all(): # pull author.book.info back from cloud storage book = Book.objects.create(info=info) author.book = book author.save() class Migration(migrations.Migration): dependencies = [ ('manager', '0024_some_migration_dependency'), ] operations = … -
Can I override the http status in a permission class?
I am trying to create a custom permission class inheriting from permissions.BasePermission. I know you can override the message property for a custom message but can the http status also be overridden? I'd like to return a 410 for an expired link. Not sure if I am trying to create an unintended behavior. -
how can i restrict user that have not pay not to exam section
class QuizTake(FormView): form_class = QuestionForm template_name = 'question.html' result_template_name = 'result.html' single_complete_template_name = 'single_complete.html' def dispatch(self, request, *args, **kwargs): self.quiz = get_object_or_404(Quiz, url=self.kwargs['quiz_name']) if self.quiz.draft and not request.user.has_perm('quiz.change_quiz'): raise PermissionDenied try: self.logged_in_user = self.request.user.is_authenticated() except TypeError: self.logged_in_user = self.request.user.is_authenticated if self.logged_in_user: self.sitting = Sitting.objects.user_sitting(request.user, self.quiz) else: self.sitting = self.anon_load_sitting() if self.sitting is False: return render(request, self.single_complete_template_name) return super(QuizTake, self).dispatch(request, *args, **kwargs) def get_form(self, *args, **kwargs): if self.logged_in_user: self.question = self.sitting.get_first_question() self.progress = self.sitting.progress() else: self.question = self.anon_next_question() self.progress = self.anon_sitting_progress() if self.question.__class__ is Essay_Question: form_class = EssayForm else: form_class = self.form_class return form_class(**self.get_form_kwargs()) def get_form_kwargs(self): kwargs = super(QuizTake, self).get_form_kwargs() return dict(kwargs, question=self.question) def form_valid(self, form): if self.logged_in_user: self.form_valid_user(form) if self.sitting.get_first_question() is False: return self.final_result_user() else: self.form_valid_anon(form) if not self.request.session[self.quiz.anon_q_list()]: return self.final_result_anon() self.request.POST = {} return super(QuizTake, self).get(self, self.request) the code above is my views please i want to give restriction for user who have not pay not to be able to access the exam section. @python_2_unicode_compatible class Quiz(models.Model): title = models.CharField( verbose_name=_("Title"), max_length=60, blank=False) description = models.TextField( verbose_name=_("Description"), blank=True, help_text=_("a description of the quiz")) url = models.SlugField( max_length=60, blank=False, help_text=_("a user friendly url"), verbose_name=_("user friendly url")) category = models.ForeignKey( Category, null=True, blank=True, verbose_name=_("Category"), on_delete=models.CASCADE) random_order = models.BooleanField( blank=False, default=False, verbose_name=_("Random … -
Can I create Python Enums for conversion rates?
I currently have two Django models defined for DataUnit (ex. kWh, $, day, month, etc.) and RateUnit (ex. $/day, $/kWh, etc.). This is proving helpful as I am able to assign units to a variety of values and ensure that calculations make sense (ex. X day * Y $/day = $Z) and also invalidate calculations that should not be made (ex. the DataUnit doesn't equal the RateUnit's denominator). However, I have a chunk of code that currently lives in Django and could be useful in a general context outside of Django, but relies on the RateUnit and DataUnit. Can I model something similar in straight Python? I believe I could model DataUnit using an enum and still store that enum value in a Django EnumField. However, I am not sure what to do with RateUnit. I would like to be able to compose a rate unit from two data units (one numerator and one denominator) in a way that can both live on its own in a Python module, but also be stored in a Django model in a field. class DataUnit(ValidationModel): """ Units of measure. Ex. kw, kwh, therms """ name = models.CharField(max_length=8, unique=True) class Meta: ordering = ["id"] … -
ImportError: module incorrectly imported
I am getting error when I run below given command docker-compose run app python manage.py test ImportError: 'tests' module incorrectly imported from '/app/core/tests'. Expected '/app/core'. Is this module globally installed? Tried to import that from shell but still not working >>> import app.core.tests Traceback (most recent call last): File "<console>", line 1, in <module> ModuleNotFoundError: No module named 'app.core' Versions: Django==2.1.3 djangorestframework==3.9.0 docker==3.7.2 docker-compose==1.24.0 docker-pycreds==0.4.0 dockerpty==0.4.1 docopt==0.6.2 Python 3.7.2 -
What is the correct http status code to return for an expiration?
If i send an email link for an invitation to my website where you fill out a form, what if I wanted to expire that invitation after, let's say, 10 days. What is the correct status code to return in this case? Maybe there isn't a standard? -
View data on PostgreSQL database in Ubuntu
I am running a Django based website on a Digital Ocean Ubuntu droplet, using PostgreSQL. The site is running and data is being stored in the database successfully. How do I view the data in the database? I was able to do this easily using PGadmin on my windows machine before I pushed it to production. How do I do this now that there is no GUI? Can I still use PGadmin somehow and "remote" into my droplet? Thanks! -
How to remove duplicate values from QuerySet?
I write users = User.objects.filter(is_active=True, article_creator__in=articles) And I get queryset <QuerySet [<User: A>, <User: A>, <User: A>, <User: B>, <User: C>, <User: B>]> How can to remove duplicate values. I need get this queryset <QuerySet [<User: A>, <User: B>, <User: C>]> -
Authentication error while trying to login to Django admin panel, cannot log out
I have two questions, the second is related to the first and could indeed be the cause. I am mid-development of a simple Django project, I used the (partially finished) login form to login using a non-super user. It redirected to the login page, but when I then proceded to localhost/admin, it came up with this error. You are authenticated as 3rdMayTest (this is the username), but are not authorized to access this page. Would you like to login to a different account? The problem being, I tried refreshing the page, clicking out of it, and restarting the server, but the error persists and I cannot figure out how to LOGOUT so I can continue. The related issue is in the SETTINGS.py (for the project) file, I added this, in the hope that on submitting login form data, it would login and re-direct to the home page, but instead it causes the above error, and redirects to the login page. LOGIN_REDIRECT_URL = 'socialmedia-home' socialmedia-home, is, as far as I know, the name I've given and this is in the socialmedia app/urls.py file #THIS IS THE SOCIAL MEDIA URLS ..not the root directory URLS from django.contrib import admin from django.urls import … -
how to insert multiple records at once by django admin
suppose I have 5 units of a product. now I want to create 5 individual rows in products table for these 5 units. all fields will get same value. can I do it by submitting the form once from django-admin? -
Why is my django Translation not working?
I have a form where most elements are translating as I would expect but a the language dropdown isn't. I have a file, languages.py of the following format: -- coding: utf-8 -- from django.utils.translation import ugettext_lazy as _ LANGUAGE_OPTIONS = ( ("Abkhaz", "аҧсуа (%s)" % _("Abkhaz")), ("Afar", "Afaraf (%s)" % _("Afar")), ("Afrikaans", "Afrikaans (%s)" % _("Afrikaans")), ("Akan", "Akan (%s)" % _("Akan")), ("Albanian", "Shqip (%s)" % _("Albanian")), .... ("Zhuang, Chuang", "Saɯ cueŋƅ, Saw cuengh (%s)" % _("Zhuang, Chuang")), ) The idea being the English version of the code is saved to the database but the user can see the language in it's original and their language. I import this into forms.py using from .languages import LANGUAGE_OPTIONS as language_choices I then have the following field within the form other_languages = forms.MultipleChoiceField( choices=language_choices, label = _("Which language(s)"), required = False ) "Which language(s)" is translated correctly, but the languages within the choices are not. What have I got wrong? -
Django authenticated user logged in as anonymous user
In my Django view, I authenticate and login a user. However, when I check to see if the user is authenticated in another view with request.user.is_anonymous, the user is anonymous. I have looked at all the other questions related to this, but haven't found anything to help. I am using jQuery/AJAX to post the data to the Django view, but I have checked and the correct data is being sent, so I don't think there is an issue with the frontend. @csrf_exempt def LoginView(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(request, username=username, password=password) if user is not None and user.is_active: login(request, user) return JsonResponse({'logged_in' : 'yes'}) return JsonResponse({'logged_in' : 'no'}) I get the JSON response logged_in : yes in the browser, so the user is authenticated, but is acting as an anonymous logged in user. -
How to improve admin load times with large table
I have a large table that currently has around 400k pages that is constantly growing. The admin page has gotten to the point that it just times out while trying to view it. I have added a paginator but that did not seem to help. Any suggestions would be appreciated. class MyAdmin(admin.ModelAdmin): ... paginator = LargeTablePaginator ... class LargeTablePaginator(Paginator): @property def count(self): query = self.object_list.query if not query.where: cursor = connection.cursor() cursor.execute('SELECT reltuples FROM pg_class WHERE relname = %s', [query.model._meta.db_table]) return int(cursor.fetchone()[0]) I have also tried updating the get_queryset method to only return data from the previous 24 hours but that also did not improve load times def get_queryset(self, request): return super(MyAdmin, self).get_queryset(request).filter(created_on__gte=datetime.datetime.today()) -
Doing a models.CASCADE in reverse
My models: class Bed(models.Model): id = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=200, default='', blank=True) class Admission(models.Model): id = models.AutoField(primary_key=True, unique=True) bed = models.ForeignKey(Bed, on_delete=models.CASCADE) So if the related bed entry is deleted, Admission gets deleted. However I want to delete Bed if an Admission entry gets deleted. Do I utilize signal for this, or is there a more apt way that I'm missing? I'm thinking of using django.db.models.signals.post_delete to do this. -
How to use URL namespaces with django-hosts
I'm using django-hosts in development and I now have multiple apps so i will need to use URL namespaces. With default django routing i would include either an app_name in the app url module(s) or add the namespace argument with the include statement in the root url configuration. But none of these seem to work with django-hosts. How can i implement namespaces with it? -
Django group permissions for specific model
I'm working on a website for my neighbor, and I was almost completely done. But he added one more feature that I can't seem to wrap my head around building. The feature in itself is pretty simple, and I already have it written. He just wanted a photo gallery with albums. Each vendor on his site would have their own album. But the problem I'm having is that he wants specific users from each vendor to be able to access the CRUD for these albums, and not anything else. If I try to do this in django admin, then the user gets access to other albums that aren't theirs. So I need to create some permissions. Can I use group permissions in django to do this, because the permissions in django are pretty general and not specific to their vendor name or any other models. I only want them to be able to access and add new items under their vendor name. Or do I need to use some other tool, and create another view? Models.py for reference: class Vendor(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=200, unique=True, null=True) website = models.CharField(max_length=256) city = models.CharField(max_length=100) state = models.CharField(max_length=3) vendor_email = models.CharField(max_length=100) … -
Testing viewsets with UploadedFile
I'm trying to test a particular viewset view which takes formData which contains a csv file. My test looks like this: @staticmethod def _create_file(rows: List[List[Any]], content_type: str = 'text/csv') -> UploadedFile: f = StringIO() csv.writer(f).writerows(rows) return UploadedFile(file=f.read(), name='test.csv', content_type=content_type) def test_upload_valid(self): """ Asserts that the upload view works correctly with valid information. """ response = self.client.post(reverse('core_api:upload-upload'), { 'file_type': self.file_type, 'file': self._create_file([self.header, self.acceptable_row]) }) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.content['process_status'], DemoConsumerDataParser.SUCCESS_STATUS) self.assertEqual(len(response.content['errors']), 0) However this fails here: 'file': self._create_file([self.header, self.acceptable_row]) With the following error: AttributeError: 'str' object has no attribute 'read' How can I modify the post so it correctly sends this file? I know the file is created correctly (I've used the creation method in other tests), but I can't get the post syntax right. -
How to run python code in html page using django
I am learning web development using django framework. I have little trouble in running python code in an html page. I need to iterate through a list of strings which basically contains the paths of images that I want to show in a carousel. I am getting this error "Invalid block tag on line 83: 'with.i', expected 'endblock'. Did you forget to register or load this tag?" in galleryPage.html file when I try to open that page. These are the few lines of code that I've written so far /View.py/ def galleryPage(request): from os import listdir from os.path import isfile, join ImageList = [] imagePath = "static/images/gallery/" for f in listdir(imagePath): temp = join(imagePath, f) if isfile(temp): temp = "../" + temp ImageList.append(temp) return render(request, "galleryPage.html", {"imageList": ImageList}) /galleryPage.html/ {% extends 'base.html' %} {% block title %} GALLERY {% endblock %} {% block slideshow %} * {box-sizing: border-box;} body {font-family: Verdana, sans-serif;} .mySlides {display: none;} img {vertical-align: middle;} /* Slideshow container */ .slideshow-container { max-width: 1000px; position: relative; margin: auto; } /* Caption text */ .text { color: #f2f2f2; font-size: 15px; padding: 8px 12px; position: absolute; bottom: 8px; width: 100%; text-align: center; } /* Number text (1/3 etc) */ .numbertext … -
Set form action using jquery
Is there a way to set form action to call a url with primary key parameter. I have the following jquery: $('#chatbox').on('show.bs.modal', function (event) { var button = $(event.relatedTarget) // Button that triggered the modal var recipient = button.data('whatever') // Extract info from data-* attributes $.ajax({ url: "{% url 'fetcher' %}", data: { 'search': recipient }, dataType: 'json', success: function (data) { list = data.list; id = data.id; $('#chatbox').find('.modal-body').text(id) $('#formid').get(0).setAttribute('action', "{% url 'usercreation:addmessage' %}"); } }); var modal = $(this) modal.find('.modal-title').text('Chat with ' + recipient) }) I need to include "id" from success response of ajax as the primary key passed to action form. Something like {% url 'usercreation:addmessage' id %} Is there any way? -
Django filter relation field set
I have two models, here is simplified example of it: class Application(TimestampedModel): ... forms = models.ManyToManyField(Form, related_name='applications', through='ApplicationForm', blank=True) class ApplicationForm(models.Model): application = models.ForeignKey(Application, on_delete=models.CASCADE) form = models.ForeignKey(Form, on_delete=models.CASCADE) created_at = models.DateTimeField() updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-created_at'] I want to filter forms field on Application model. I try to do this: queryset = Application.objects.get_active().filter(is_public=True, pk=self.kwargs['pk']) for application in queryset: forms = application.forms.filter(form_sections__form_fields__pk__in=application.public_form_fields.all()) application.forms.set(forms) But I get an error: AttributeError at /api/applications/public/79 Cannot set values on a ManyToManyField which specifies an intermediary model. Use applications.ApplicationForm's Manager instead. So my question is it possible, and if possible how can I do this?