Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SQL or django query to find the similar entries
I want to return the user a list of similar tasks. Two tasks A and B are considered similar if all the words in task A exist in task B or vice versa. I tried the query given below but couldn't get the required result. SELECT t1.task FROM todolistapp_todo t1 LEFT JOIN todolistapp_todo t2 ON t1.task in (t2.task) and t1.id != t2.id; I'm able to do this by the nested loop. But I want to do it by simple expression. similar = set() for task in tasks: for nested_task in tasks if (task.task in nested_task.task or nested_task.task in task.task) and task.id != nested_task.id: similar.add(task) -
pass pk to CreateView form in django
i'm new to django. I have a model that looks like this: models.py class Intervention(models.Model): subject = models.CharField(max_length=200) begin_date = models.DateField(default=datetime.datetime.today) end_date = models.DateField(default=datetime.datetime.today) description = models.TextField(blank=True) speaker = models.ForeignKey(CustomUser, on_delete=models.CASCADE) campus = models.ForeignKey(Campus, on_delete=models.CASCADE) class Meta: verbose_name = 'Intervention' verbose_name_plural = 'Interventions' def __str__(self): return self.subject class Evaluation(models.Model): interventions = models.ForeignKey(Intervention, on_delete=models.CASCADE) student_id = models.CharField(max_length=20) speaker_knowledge_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)]) speaker_teaching_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)]) speaker_answer_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)]) slide_content_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)]) slide_examples_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)]) comment = models.TextField(blank=True) The idea is when that the student enter the website on home page he have to choose the campus where he study then he is redirected to a page where he see only interventions of his campus then when he choose the intervention he get the detail of it : Home page screen Interventions page Intervetion detail page Everything is working so far. Now on "intervention detail page" when the user click on "give mark" he is redirected to a page to create mark (i use CreateView class-based) like below: create mark Now my question is how can i replace Modelchoicefield in the generated form by pk of the intervetion that student want to give a mark? Views.py class CreateEvaluationView(CreateView): form_class … -
How to disable or hide assign/redirect button if the ID already exist in other table on django
class Patient(models.Model): name = models.CharField(max_length=50) active_choices = [('Yes', 'Yes'), ('No', 'No')] active = models.CharField( max_length=6, choices=active_choices, default='Yes') def __str__(self): return self.name The other one is: class Ticket(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) is_active = models.IntegerField(default=1) def __str__(self): return self.patient.name In the Views.py @login_required def PatientView(request): form = PatientModelForm(request.POST or None) patients = Patient.objects.order_by('-id') ticket_list = Ticket.objects.filter(is_active=0) total = patient_list.count() if form.is_valid(): obj.save() messages.success(request, 'Patient was added successfully.') return redirect('/dashboard/patient') context = { 'form': form, 'patients ': patients , } return render(request, 'dashboard/patient.html', context) The other view for ticket: @login_required def TicketToGenerateView(request, pk): ticket = get_object_or_404(Patient, pk=pk) form = TicketModelForm(request.POST or None) if form.is_valid(): obj.save() messages.success(request, 'Patient assigned successfully.') return redirect('/dashboard/ticket') context = { 'form': form, 'ticket': ticket, } return render(request, 'dashboard/ticket.html', context) So I want to hide this bellow link button if patient.pk already exist in the Ticket model and is_active = 1 So it displays all rows with assign link button. <a href="{% url 'dashboard:ticket_to' patient.pk %}" name="doctor" class="btn btn-dark btn-sm" data-toggle="tooltip" title="Assign to a Doctor"> <span class=" fa fa-user-md "></span> </a> -
I want a feature to unregister model but in wagtail model admin
Suppose one model admin registered in wagtail model admin but i want to add/change in this registered modeladmin.So, how to add extra field in list_display in already registered modeladmin in wagtail? Please tell me idea about this problem or any method to unregister modeladmin in wagtail. -
How to setup Nginx server for angular and django
I'm trying to deploy a web application to my server. I have put the html files in one folder and I have a django server running on the same server. I am using nginx to set up reverse proxy for the backend but for some reason I'm not able to route to backend urls. Here is my nginx configuration: server { listen 80 default_server; listen [::]:80 default_server; server_name _; return 301 https://example.com$request_uri; } server { listen [::]:443 ssl ipv6only=on; listen 443 ssl; server_name example.com example.com; root /var/www/html/; index index.html; # Let's Encrypt parameters ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; location / { try_files $uri $uri/ = index.html; } location /api { proxy_pass http://unix:/run/gunicorn.sock; proxy_redirect off; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; } } In the first block..I'm setting fallbacks to index.html because it is an angular app. The angular app runs fine. But I'm not able to access the routes of the reverse proxy server, whenever I hit a route with /api/something it takes me back to the angular app i.e index.html -
Create API for geojson data in django
I know we can use django rest framework for creating API for normal data. But I'm confused can we use django rest framework for geojson data. I'm mean i want to build location based web app using django and I also want to manipulate the data from android app or ios app. So here I'm confused can i use django rest framework or somethings else. Here I'm using PostgreSQL and postgis for data storage. -
How to set small icon size for`tinymce` in mobile screens?
I added tinymce4-lite in my Django application. The size of icons looks the same in bigger screens and small screens. Big Screens: Small Screens: the size of icons are similar in either big and small screens. I want it to be smaller and more elegant in mobile size screens. This is the configuration in settings.py: TINYMCE_DEFAULT_CONFIG = { 'height': 360, 'menubar': False, 'statusbar': False, 'width': '100%', 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'modern', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak ''', 'toolbar1': ''' fullscreen preview bold italic underline | fontselect, fontsizeselect | forecolor backcolor | alignleft alignright | aligncenter alignjustify | bullist numlist table | | link image media | codesample | hr visualchars | ''', 'contextmenu': 'formats | link image', 'remove_linebreaks': False } Please help me with this. Thank you -
How to show BinaryField image preview in Django admin interface?
I've got web project with Django backend for which I decided to store images as BinaryField, it seemed to be more convenient for me in case of making backups and restoring them. At first I've created model: class ThermalSource(ClusterUnit): ... scheme_image = models.BinaryField(verbose_name='Scheme', blank=True, null=True, editable=True) ... Then created serializer to use in viewset (I know it is not related to admin interface, but maybe it will be useful): class Base64BinaryField(serializers.Field): def to_representation(self, value): from base64 import b64encode return b64encode(value) def to_internal_value(self, data): from base64 import b64decode return b64decode(data) class ThermalSourceSerializer(APAMModelSerializer): ... scheme_image_base64 = Base64BinaryField(source='scheme_image') ... Now I could get and set images converted to Base64 correctly via Django REST Framework. Admin class for ThermalSource looks so now: class ThermalSourceForm(forms.ModelForm): scheme_image = forms.FileField(required=False) def save(self, commit=True): if self.cleaned_data.get('scheme_image') is not None \ and hasattr(self.cleaned_data['scheme_image'], 'file'): data = self.cleaned_data['scheme_image'].file.read() self.instance.scheme_image = data return self.instance def save_m2m(self): # FIXME: this function is required by ModelAdmin, otherwise save process will fail pass class ThermalSourceAdmin(admin.ModelAdmin): form = ThermalSourceForm readonly_fields = ('id', ) list_display = ('id', ... 'scheme_image') But when I open Django admin interface, I could only download files to scheme image field, no preview is configured. Could anybody suggest me how could I … -
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