Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError at /post_create/ invalid literal for int() with base 10: 'manish'
This is my views : I want to create post with Author in different models def post_create(request): author, created = Author.objects.get_or_create(name=request.user.username) form = CreateForm(request.POST or None , request.FILES or None) if form.is_valid(): form.instance.author = author form.save() return redirect('post_list') context = { 'form': form } return render(request,'post/post_create.html',context) This is my models . I have created Author and Post here . from django.db import models from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey('Author',on_delete=models.SET_NULL,null=True) story= models.TextField() image= models.ImageField() slug = models.SlugField() def __str__(self): return self.title class Author(models.Model): name = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.name.username -
AngularJS + Django file upload
I am referring to the official Django documentation https://docs.djangoproject.com/en/2.2/topics/http/file-uploads/ on Handling uploaded files with a model, as well as 'ngFileUpload' and Django Rest Framework on Stack Overflow. However, I am still unable to upload a file. html: <div id="dropdown-lvl5" class="panel-collapse collapse" ng-submit="UploadFile"> <div class="panel-body" style="width:198px"> <input type="file" id="files" name="files[]" multiple size="10" class="inputfile_upload" file="file" files-model="file.file" ng-controller="fileUploadController" accept="application/pdf"/> <label for="files"> <span class="glyphicon glyphicon-open"></span>Select a file to upload</label> <div> <span ng-show="!files.length">No files selected</span> <ul> <li ng-repeat="file in files">{{file.file}}</li> </ul> </div> </div> </div> fileUploadController.js: app.controller('fileUploadController', function($scope, Upload, $timeout){ $scope.Submit = function(file){ $file.upload = Upload.upload({ url: '../../file', data: {file: file}, arrayKey: '', }); file.upload.then(function (response) { $timeout(function () { file.result = response.data; }); }, function (response) { if (response.status > 0) $scope.errorMsg = response.status + ': ' + response.data; } } }); fileUploadService.js: app.service('fileUploadService', ['$http', function ($http) { this.post = function(uploadUrl, data){ var fd = new FormData(); fd.append('file', file); for(var key in data) fd.append(key, data[key]); $http.post(uploadUrl,fd, { transformRequest: angular.identity, headers: { 'Content-Type': undefined } }) } } } } directive.js: app.directive('fileModel', ['$parse',function ($parse) { return{ scope: { file: '=' }, restrict: 'A', link: function(scope, element, attrs){ var model = $parse(attrs.fileModel) var modelSetter = model.assign; element.bind('change', function(){ var file = event.target.files[0]; scope.file = file ? file … -
How to derive an attribute from another in Django
Here is my first project in which I am experimenting with the Django documentation: a Person model. and two featured views (one to create a person and the other to view the list of created persons). So far a person has only two CharFields, first_name and last_name. What I'd like to do now is to implement a BooleanField adult, which returns True if the difference between today's date and the date of birth is greater than or equal to, say, 18 (or 16, it doesn't matter). Possibly I would also implement an attribute age based on the same principles. Obviously, it would be perfectly ok to derive adult from age. How can this be implemented in Django? Where should I write the piece of code that makes the math to derive adult/age? Inside models.py, forms.py, views.py or maybe inside the template? P.S. I know it looks weird to see the age attribute been declared as a DurationField, but as I was saying I am trying to experiment with different attribute fields. If the answer to my question requires it to be changed into, say, PositiveInteger, I don't mind changing it. My models.py looks like this from django.db import models # … -
modifying queryset in django admin page for auth_users and a custom related model
So, I have a model DailyTask that has a OneToOneField to the auth_users model, this is the DailyTask model fields : task_id task_date user ( OneToOneField ) Now each user has to submit a new Task report daily, already have an AdminModel that display all the submitted Tasks respectively to the logged in non superuser, here is the AdminModel : class DailyTaskAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return qs.filter(user=request.user) and I have created a proxy Model so I can create and register another AdminModel using the same Model : class MyDailyTask(DailyTask): class Meta: proxy = True then the second AdminModel : class DailyPresenceAdmin(DailyTaskAdmin): def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return qs.filter() admin.site.register(MyDailyTask, DailyPresenceAdmin) My only problem is, that in the DailyPresenceAdmin AdminModel, want to list all the users from auth_users that has not uploaded their Task of the day yet. so it will be something like, if auth_users.user has no TaskID with the date equals to today's date in the DailyTask Model yet, then I want to take the user and list it in the DailyPresenceAdmin AdminModel. -
Get data to Modal on button click, with buttons that have the same ID
Scenario - I have a page that has job listings, every individual job listing has a button called apply. A modal pops open when you click it, however that modal has no context as to which job the user wants to apply to, so I want to get the ID of the Job posting to the modal somehow. Problem - The buttons are being procedurally generated and have the same ID's. So using javascript to catch a onclick event cause for some reason it only gets the data-id of first button. {% for vacancy in vacancies %} <div class="card"> <div class="card-body"> <h5 class="card-title">Job Title - {{ vacancy.job_title }} </h5> <strong><p>Description </p></strong> <p class="card-text">{{ vacancy.job_description }}</p> </div> <button id="openmodal" data-id="{{ vacancy.id }}" type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal"> Apply </button> </div> {% endfor %} <div class="modal-body"> <form action="" class="customer-input" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="form-group col-lg-6"> <label for="fullName">Full Name</label><br> <input name="full-name" type="text" placeholder="Full Name" required="required"> </div> <div class="form-group col-lg-6"> <label for="email">Email</label><br> <input type="email" name="email" placeholder="Email" required="required"> </div> </div> <div class="row"> <div class="col-lg-6"> <div class="form-group"> <label>Job Role</label><br> <select class="job-role" name="job-role"> <option value="python-developer">Python Developer</option> <option value="fullstack-developer">Full Stack Developer</option> </select> </div> </div> <div class="col-lg-6"> <div class="form-group"> <label>Your Resume</label><br> <input type="file" name="resume" accept=".pdf, … -
how can I expire tokens after 1 minute?
I am trying to expire tokens after its creation with a max duration of 1 minute to meet security requirements. my function looks like this, but I don't think is doing it the right way, and I Would like to know what is the best way to expire the token after 1 minute? I am using the technique of diffing two times. the following function works under models.py def is_token_expired(self): if self.token == None: return False now = datetime.datetime.utcnow().replace(tzinfo=utc) timediff = now - self.created_at if timediff.seconds / 60 - 1 > 0: return True return False -
Easy Thumbnail with Django raising access denied error
I'm using S3Boto3Storage to save docs in my aws s3 and tried to use easy-thumbnails to generate thumbnail images, please find the code below Model class class ThumbnailTestModel(models.Model): sample1 = models.FileField( storage=S3Boto3Storage(), help_text="Field to store the sample document of Professional", null=True, blank=True, upload_to=s3_professional_sample_storage_path) sample1_file_name = models.CharField(blank=True,null=True,max_length=1000, default=True) View class class ThumbnailTestModelView(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): queryset = ThumbnailTestModel.objects.all() permission_classes = (AllowAny, ) serializer_class = ThumbnailSerializer and the serialize class ThumbnailSerializer(serializers.ModelSerializer): sample1 = serializers.FileField(read_only=True, required=False, allow_null=True) sample1_base64 = serializers.CharField(write_only=True, required=False, allow_null=True) sample1_thumbnail = serializers.SerializerMethodField(required=False, read_only=True, allow_null=True) class Meta: model = ThumbnailTestModel fields = ['id','sample1', 'sample1_file_name', 'sample1_base64', 'sample1_thumbnail'] def validate(self, validated_data): validated_data = super(ProductProfessionalSerializer, self).validate(validated_data) sample1_base64 = validated_data.pop('sample1_base64', None) if sample1_base64: validated_data['sample1'] = ContentFile( base64.b64decode(sample1_base64), name=validated_data["sample1_file_name"]) def get_sample1_thumbnail(self, instance): return AWS_URL + get_thumbnailer(instance.sample1)['avatar'].url Here's the response I get [{"id":5,"sample1":"https://wizcounsel-dev.s3.amazonaws.com/sample_document/None/add_team_2.png","sample1_file_name":"add_team_2.png","sample1_thumbnail":"https://wizcounsel-dev.s3.amazonaws.com/sample_document/None/add_team_2.png.150x100_q85_crop.png"}] However accessing the generated thumbnail url returns an access denied error, all objects in the same folder are in fact public, on inspecting the AWS folder doesn't seem to have the thumbnail file I'm super new to Django and hence the question might appear naive, Thanks -
Django - Allow only one filed to fill in the form
I am using below django model for forms class Post(models.Model): author = models.ForeignKey(CustomUser,on_delete=models.CASCADE,) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) post_url = models.URLField(max_length = 200, blank = True) picture = models.ImageField(upload_to='Image_folder', height_field=None, width_field=None, max_length=100, blank = True) slug = models.SlugField(unique=True, blank=True) I want to allow user to enter only one field either post_url or picture but not both. Can some give some an idea how to implement this? -
Django database post content as template
Hopefully, my title makes any sense. I'm building a personal blog with Django. I have some posts in my database and am trying to determine the best way to load images in my posts without specifying the entire path to my static directory. So, I pass my Post query into my template. In my template I have the following: <div class="post-content"> {{ post.post_content|safe }} </div> The post content loads but template tags such as static aren't loaded as expected. For example, my post_content might be: "A little text. And an image: <img src=\"{% static '/default-images/default-post-thumbnail.jpg' %}\" width='200'>" I'm using the django template tag static (which I did remember to load at the top of the template) in my img src but once the page is loaded the src for the image ends up looking like: src="{% static '/default-images/default-post-thumbnail.jpg' %}" Does anyone have recommendations for getting that static template tag to function as expected and fill in the img src with my STATIC_ROOT path? Let me know if you need further explanation or additional code and thanks in advance for any help! -
Django Nested Template Tags
I have a custom template tag that accesses a models function. However, I also need the custom template tag to be in a for loop, which requires nested template tags: {% for list in remind_lists %} <h3>{{ list.title }}</h3> {% for item in {% get_list_items user.username %} %} <p>{{ item.title }}</p> {% endfor %} {% endfor %} It gives me a TemplateSyntaxError and says the for is not formatted correctly. Is there anyway I can do this? custom tag: register = template.Library() @register.simple_tag def get_list_items(event_ins, authenticated_user): return event_ins.get_list_items(authenticated_user) -
Django "Rewrite the current ManyToManyModel" into the parent model
I would like to rewrite a ManyToManyModel: views.py qset = CustomUser.objects.all().order_by('?') game.team1.set = qset[:5] game.team2.set = qset[5:10] game.players.list = qset[:10] game.isReady = True game.isPrepared = False game.save() when I do this, I get the following output: (those array i am inserting) <QuerySet [<CustomUser: bot123>, <CustomUser: admin>, <CustomUser: murkgo>, <CustomUser: bot>, <CustomUser: xlaso1>]> <QuerySet [<CustomUser: bot1233>, <CustomUser: bot>, <CustomUser: xlaso1>]> (how does team1 and team2 look like after edit)===BFORE SAVE==> <QuerySet [<CustomUser: admin>, <CustomUser: lasododo>, <CustomUser: Wot>, <CustomUser: xlaso1>, <CustomUser: bot>]> <QuerySet [<CustomUser: xlaso1>, <CustomUser: bot>, <CustomUser: bot123>, <CustomUser: bot1233>, <CustomUser: murkgo>]> ===BFORE SAVE==> (how are team1 and team2 saved)=====> <QuerySet [<CustomUser: admin>, <CustomUser: lasododo>, <CustomUser: Wot>, <CustomUser: xlaso1>, <CustomUser: bot>]> <QuerySet [<CustomUser: xlaso1>, <CustomUser: bot>, <CustomUser: bot123>, <CustomUser: bot1233>, <CustomUser: murkgo>]> =====> i can see that values didnt change the ManyToManyModel. I have looked around the web and I noticed that some people were trying to override it somehow, but not acctualy change it. Is there any way, to acctualy make it saved like i want to ? -
Django - 'KeyError at /form/ "text" ' when using Pandas in a script
I'm building a simple web app tweeter sentiment analysis with Django and Pandas, so far the Django build worked as expected, but when I try to get a POST word from the HTML to run in the sentiment analysis script, I get an error message pointing to the script and to the dataframe column 'text'. My view.py: from django.shortcuts import render from . import script def form(request): searchword = request.POST.get('Searchword') submitbutton = request.POST.get('Submit') if searchword: searchword = script.main(searchword) context = {'searchword': searchword, 'submitbutton': submitbutton, } return render(request, 'blog/form.html', context) The POST works fine, I manage to collect the input and work with it, even with functions in the script, but if I reference a dataframe column, I have an error, the debugger points to: return self._engine.get_loc(key) The script.py: def create_ref(testDataSet): # Turns JSON into DataFrame df = pd.DataFrame(testDataSet) ref = pd.DataFrame() ref = df.copy() ref = ref.drop('label', axis=1) ref['original'] = ref['text'].copy() ref['text'] = clean_tweet(df['text']) ref['sentiment'] = '' ref['feel'] = '' for item in range(len(ref['text'])): ap = ref['text'][item] analysis = TextBlob(ap) ref['sentiment'][item] = analysis.sentiment.polarity if analysis.sentiment.polarity > 0: ref['feel'][item] = 'positive' elif analysis.sentiment.polarity == 0: ref['feel'][item] = 'neutral' else: ref['feel'][item] = 'negative' return ref def main(searchword='ostriches'): # Authenticating Twitter tokens twitter_api … -
dejango admin send back to homepage
i am new to django and i am makeing my first site i tried to get on my admin for my site but when i go to 127.0.0.1/admin it sends me back to the home page i have look over my code multiple times and i just cant find anything wrong about it here is my mysite urls """mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ # this is mysite not main from django.conf.urls import url,include from django.contrib import admin #url('^admin/', admin.site.urls), urlpatterns = [ url(r'^admin/', admin.site.urls), url('', include('main.urls')), url('tinymce/', include('tinymce.urls')), ] here is my main.urls """mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, … -
Django Passing Through List Items
I have a todo website that allows users to put a remind in a certain list, such as work, school, groceries, etc. However, I'm a bit lost on how to get the list and their items to display. Models.py: class RemindList(models.Model): parent_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=50) class Reminder(models.Model): remind_types = [('Regular', 'Regular'), ('Long Term', 'Long Term')] title = models.CharField(max_length=100) description = models.TextField() remind_time = models.DateTimeField(blank=True) parent_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) parent_list = models.ForeignKey(RemindList, on_delete=models.CASCADE, null=True) type_of_remind = models.CharField(max_length=12, choices=remind_types, default='Regular') complete = models.BooleanField(default=False) Views.py: @login_required(login_url='/login') def home(request): user = get_object_or_404(User, username=request.user.username) context = { 'events': ToDoItem.objects.filter(parent_user=user), 'reminders': Reminder.objects.filter(parent_user=user, type_of_remind='Regular'), 'long_term_reminders': Reminder.objects.filter(parent_user=user, type_of_remind='Long Term'), 'remind_list_items': RemindList.objects.filter(parent_user=user), } return render(request, 'main/home.html', context) I can pass through the list names, which I planned to just filter them like Reminder.objects.filter(parent_user=user, type_of_remind='Regular', parent_list=list_name). However, theres no way to filter through them by passing them in through python, and you can't filter them on the html side (correct me if I'm wrong). Is there another way to do this? -
How can I populate an HTML dropdown with data from a database using Django?
I'm attempting to create a dropdown selection on an HTML page containing options (specifically, the userID and name of a character for the user to select to load into a battle simulator) from my database, but it keeps coming up empty without any errors or any indication as to what is wrong. I'm trying to base my solution off of this. I know using a ModelForm through Django is an option, but if all I'm doing is populating HTML fields, I'm not sure if it would be my best option to take the time needed to familiarize with ModelForm. Below is what I presently have: views.py: from django.shortcuts import render from django.views.generic import TemplateView # Import TemplateView from django.http import HttpResponse from pathfinder.models import characterTable [...] class battleSimView(TemplateView): template_name = "battleSim.html" def post(request): item = characterTable.objects.all() # use filter() when you have sth to filter ;) return render_to_response (self.template_name, {'items':item}, context_instance = RequestContext(request),) [...] models.py: from django.db import models class characterTable(models.Model): userID = models.CharField(max_length = 32) playerName = models.CharField(max_length = 32) race = models.CharField(max_length = 32) playerClass = models.CharField(max_length = 32) strength = models.CharField(max_length = 2) dexterity = models.CharField(max_length = 2) constitution = models.CharField(max_length = 2) intelligence = models.CharField(max_length = … -
why does django.utils.translation.gettext always return translated string?
I'm using django internationalization. when I use simple strings, everything is fine and working as expected: translation.activate('en-us') translation.gettext('english string') # returns 'english string' translation.activate('fa-ir') translation.gettext('english string') # returns 'translated string' but when I use "named-string interpolation", it behaves strangely: class ConfirmationCodeForm(forms.Form): confirmation_code = forms.CharField( max_length=CODE_LENGTH, # translation for label works just fine, as expected. label=translation.gettext_lazy('Confirmation Code'), # translation for help_text behaves strangely. help_text=translation.gettext_lazy( 'Enter the %(number)s digit code that was sent to you.' ) % { 'number': CODE_LENGTH } ) form = ConfirmationCodeForm() field = form.fields['confirmation_code'] translation.activate('fa-ir') field.help_text # returns the translated string with no problem translation.activate('en-us') field.help_text # Again! returns the translated string instead of the English one That's really confusing. I don't know what I did wrong... If I remove translated string from .mo file, then it always returns the english string: #: forms.py:12 #, python-format msgid "Enter the %(number)s digit code that was sent to you." msgstr "" translation.activate('fa-ir') field.help_text # returns the english string as expected translation.activate('en-us') field.help_text # returns the english string as expected -
Django static files collectstatic works but static file not showing in browser
System check identified no issues (0 silenced). December 01, 2019 - 04:19:33 Django version 2.2.7, using settings 'list_pro.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [01/Dec/2019 04:19:40] "GET / HTTP/1.1" 200 2045 [01/Dec/2019 04:19:40] "GET /static/assets/bs/css/flatly.min.css HTTP/1.1" 404 1708 [01/Dec/2019 04:19:40] "GET /static/assets/styles.css HTTP/1.1" 404 1675 -
DRF: Serializing a Model with a ForeignKey Field
I am trying to use Django-rest-framework to post model data but am having trouble relating a row in one table to another via foreign key. so I have two models: class Sport(models.Model): sport_id = models.BigIntegerField(primary_key=True, unique=True) sport_name = models.CharField(max_length=30) sport_key = models.CharField(max_length=30) def __str__(self): return self.sport_key class League(models.Model): league_name = models.CharField(max_length=30) league_id = models.BigIntegerField(primary_key=True, unique=True) league_sport = models.ForeignKey( Sport, default=1, related_name="sport", on_delete=models.SET_DEFAULT) def __str__(self): return self.league_name and then two serializers: class SportSerializer(serializers.ModelSerializer): class Meta: model = Sport fields = ['sport_id', 'sport_name', 'sport_key'] class LeagueSerializer(serializers.ModelSerializer): class Meta: model = League fields = ['league_name', 'league_id','league_sport'] and my leagues view: class LeagueListCreateAPIView(ListCreateAPIView): queryset = League.objects.all() permissions_classes = (IsAdmin, ) authentication_classes = (TokenAuthentication, BasicAuthentication) serializer_class = LeagueSerializer lookup_field = 'league_id' However, when I try to post new league data which points to a sport via it's primary key I get an IntegrityError. The sport row is already created: { 'sport_id': 112, 'sport_name': 'Football', 'sport_key': 'american-football' } When I try to post the league data: {'league_name': 'NFL', 'league_id': 2, 'league_sport': 112} I get the following error: django.db.utils.IntegrityError: FOREIGN KEY constraint failed I also get the same error when trying to create a league entry from the browsable api and select the football object from the … -
pip3 install mysql-python is failing on Mac
There are a lot of similar question but all of them has different solution. And none of them work for me. I'm trying to install Mysql connector for Django project but it gives below error. First I have installed latest version of Django. Then install mysql with below code brew install mysql - Worked fine. Then this is the code which I'm trying install connector. pip3 mysql-python. Was using easy_install mysql-python before but both of them are not working. Python Version: 3.8.0 Django Version: 2.2.7 MySql Version: 8.0.18 pip3 mysql-python gives this error: Collecting mysql-python Using cached https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip ERROR: Command errored out with exit status 1: command: /Library/Frameworks/Python.framework/Versions/3.8/bin/python3.8 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/6n/d2t3k0sd4l1d78bgk_ll5psm0000gn/T/pip-install-4nmg9waj/mysql-python/setup.py'"'"'; __file__='"'"'/private/var/folders/6n/d2t3k0sd4l1d78bgk_ll5psm0000gn/T/pip-install-4nmg9waj/mysql-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/6n/d2t3k0sd4l1d78bgk_ll5psm0000gn/T/pip-install-4nmg9waj/mysql-python/pip-egg-info cwd: /private/var/folders/6n/d2t3k0sd4l1d78bgk_ll5psm0000gn/T/pip-install-4nmg9waj/mysql-python/ Complete output (7 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/6n/d2t3k0sd4l1d78bgk_ll5psm0000gn/T/pip-install-4nmg9waj/mysql-python/setup.py", line 13, in <module> from setup_posix import get_config File "/private/var/folders/6n/d2t3k0sd4l1d78bgk_ll5psm0000gn/T/pip-install-4nmg9waj/mysql-python/setup_posix.py", line 2, in <module> from ConfigParser import SafeConfigParser ModuleNotFoundError: No module named 'ConfigParser' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
Saving "array of CustomModes / quarryset" inside of a CustomModel works first time, but then throws 'NoneType' object has no attribute '_meta'
I would like to cut quaryset to half and save these 2 quarysets to use them later ( i know that this use of quaryset ( like its done in Game ) is not valid + its returned just once, and thats on initialisation ( for game in games inits, this quaryset. ). If I refresh the site, i get this error. I have been loking around, but I cant find a Model, that can store other models / quarysets that will last forever views.py def mm_index(request): games = Game.objects.all().order_by('-created_on') for game in games: if game.isPrepared: queryset = Game.players.order_by('?')[:10] Game.team1 = queryset[:5] Game.team2 = queryset[5:10] game.isReady = True game.isPrepared = False game.save() context = { "games": games, } return render(request, "mm_index.html", context) models.py ( Game ) from django.db import models from users.models import CustomUser class Game(models.Model): title = models.CharField(max_length=255) body = models.TextField() players = models.ManyToManyField(CustomUser) team1 = models.QuerySet() # models.ManyToManyField(CustomUser) <- doesnt work team2 = models.QuerySet() # models.ManyToManyField(CustomUser) <- doesnt work created_on = models.DateTimeField(auto_now_add=True) isReady = models.BooleanField(default=False) isPrepared = models.BooleanField(default=False) isFinished = models.BooleanField(default=False) mm_index.html <tr> {% for player in game.team1 %} <td>{{ player.lol_username }}</td> {% endfor %} </tr> <tr> {% for player in game.team2 %} <td>{{ player.lol_username }}</td> {% endfor … -
Django Display Choice Value
I'm trying to add a multiple choice field to my Django form. Choices in the form come from Request class where possible choices are defined: class Request(models.Model): RESUME = 'RS' NETWORKING = 'NT' INTERVIEW = 'IN' ADVICE = 'AD' JOB_SEARCH = 'JB' COVER_LETTER = 'CV' LINKEDIN = 'LI' PORTFOLIO = 'PR' REQUEST_TYPE_CHOICES = [ (RESUME, 'Resume'), (NETWORKING, 'Networking'), (INTERVIEW, 'Interview'), (ADVICE, 'Career Advice'), (JOB_SEARCH, 'Job Search'), (COVER_LETTER, 'Cover Letter'), (LINKEDIN, 'LinkedIn'), (PORTFOLIO, 'Portfolio'), ] request_type_name = models.CharField( max_length=2, choices=REQUEST_TYPE_CHOICES, ) def __str__(self): return f'{self.request_type_name})' and called in the form as possible choices: class StudentRegisterForm(UserCreationForm): email = models.EmailField() school = forms.CharField(max_length=25) requests = forms.ModelMultipleChoiceField(queryset=Request.objects.all(), widget=forms.CheckboxSelectMultiple, required=True ) class Meta(UserCreationForm.Meta): model = User fields = ["username", "email", "first_name", "last_name", "password1", "password2", "school", "requests"] However, when the form is displayed it shows abbreviations from REQUEST, not full names. Like this: How can I access the full names instead (Resume, Networking etc)? -
In Django, how do I query a MYSQL database for the logged in user? (i.e results for specific user without hardcoding the user id)
I have this so far, apologies I am new to programming - trying to learn Django and Python. View: def dashboard(request): return render(request, 'app/dashboard.html', {'my_custom_sql': my_custom_sql}) def my_custom_sql(self): return self.request.CustomUser.customuser_set.all() Template: Displaying User's First Name {% if user.is_authenticated %} The first name: {{my_custom_sql}} -
How to create multiple form update(edit) view in Django
I need to create function based or class based view which can edit/update multiple forms in one page. How to create this? -
django url concatenation. I don't want to concatenate
when I do something in 'profile' page, the url is concatenated to the next of 'profile'. but I want to link to just 'signout'. not 'profile/signout' this is my urls.py. how can I fix it? -
Django Browser Back or Next Button Doesn't Work
When I press the "like button" the browser's back or next button doesn't work. How can I solve this problem? detail.html <form action="{% url 'like_post' %}" method="post"> {% csrf_token %} {% if is_liked %} <button type="submit" name="post_id" value="{{post.id}}" class="btn btn-danger">Beğenme</button> {% else %} <button type="submit" name="post_id" value="{{post.id}}" class="btn btn-primary">Beğen</button> {% endif %} </form>