Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JWTAuthentication not getting called
I am still new to django, trying to implement JWTAuthentication. Wrote a custom class and added it in the AUTHENTICATION_BACKENDS in settings.py. The authenticate method in this class has request as a parameter. My questions are: 1. How exactly does the flow work? 2. How does django know to pass request to the authenticate method? 3. Unrelated question, I am adding the jwt token using "request.session["Authorization"] = "Token " + jwt_token. Is this the correct way? -
How to deploy django project which uses redis for memcache to azure without using github?
I have done sample django project which i want to deploy it to Azure without using github. I also need suggestion how to use redis cache in django and deploy it to azure.Any suggestions please?? -
Filter Different log level messages to different log files
So, I am trying to create a logging system for my Django Project where I need to save all the different log level messages to different files. TLDR, I managed to get the Logs for particular level to appear in their respective files, but Debug.log contains all the log level messages Info.log contains all log level messages leaving debug warning.log contains WARN, ERROR & CRITICAL log level messages error.log contains ERROR & CRITICAL log level messages critical.log contains just CRITICAL log level messages So, I followed the official https://docs.djangoproject.com/en/2.2/topics/logging/ Got a clearer picture from this Django rest framework logging different levels on different files Then wrote the following code. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'debug_logs': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'logs/debug.log', 'formatter': 'verbose', }, 'error_logs': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': 'logs/error.log', 'formatter': 'verbose', }, 'warn_logs': { 'level': 'WARN', 'class': 'logging.FileHandler', 'filename': 'logs/warn.log', 'formatter': 'verbose', }, 'info_logs': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': 'logs/info.log', 'formatter': 'verbose', }, 'critical_logs': { 'level': 'CRITICAL', 'class': 'logging.FileHandler', 'filename': 'logs/critical.log', 'formatter': 'verbose', }, }, 'loggers': { '': { 'handlers': ['error_logs', 'warn_logs', … -
How to format timestamp in Django template
I'm trying to filter date from timestamp in Django template , (Input:)2019-03-23T18:51:05.253658 to (Output:)2019-03-23 .Anyone please help me on this? -
Create pop up message in django
I am doing some calculations in my views.py and I want to show the result. I have tried to use the following: return render(request, index.html{message:variable}) and return HttpResponse(message) I want to show the result as a Popup message. How can I implement this? -
i have a login page in that i have an image and username and password i want to change the image
Forms.py class ClientLoginPageForm(forms.ModelForm): def init(self, *args, **kwargs): self.user_id = kwargs.pop('user_id', None) super(ClientLoginPageForm, self).init(*args, **kwargs) def clean(self): error_messages = [] cleaned_data = super(ClientLoginPageForm, self).clean() idkey = self.user_id login_media = cleaned_data["login_media"] if login_media: ext = os.path.splitext(login_media.name)[1] if ext != '.jpg' and ext != '.png' and ext != '.mkv' and ext != '.avi' and ext != '.mp4': error_messages.append("Select a valid image.") else: if login_media is None: pass # error_messages.append("Image Must be Selected") if len(error_messages): raise forms.ValidationError(error_messages) return self.cleaned_data class Meta(): model = ClientDesignData fields = ('login_page_text','login_media') widgets = { 'login_page_text' : forms.Textarea( attrs = { 'maxlength' : "500" ,'type' : "text",'class' : 'form-control ptb10'}), 'login_media' : forms.ClearableFileInput(), } labels = { 'login_page_text' : 'Update Text', 'login_media' : 'Media', } -
Django Schedule Appointment Form Issue
I am creating a form where a user can click a time slot and reserve that time slot. There are 5 columns, one for each day of the week (mon, tues, wed, etc..) with 5 rows of times slots (3pm, 4pm, 5pm, 6pm, 7pm). Each time slot represents a radio input checkbox choice. The example below only has 2 columns. How could I seperate radio input buttons 1-6 and 7-12 into two different blocks. Forms.py class AppointmentForm(forms.Form): One = 1 Two = 2 Three = 3 Four = 4 Five = 5 Six = 6 SEVEN = 7 EIGHT = 8 NINE = 9 TEN = 10 ELEVEN = 11 TWELVE = 12 TYPE_CHOICES = ( (One, '3:00pm'), (Two, '3:45pm'), (Three, '4:30pm'), (Four, '5:15pm'), (Five, '6:00pm'), (Six, '6:45pm'), (SEVEN, '3:00pm'), (EIGHT, '3:45pm'), (NINE, '4:30pm'), (TEN, '5:15pm'), (ELEVEN, '6:00pm'), (TWELVE, '6:45pm') ) appointment_time = forms.ChoiceField( choices=TYPE_CHOICES, label="Appointment times", widget=forms.RadioSelect, required=True, ) AppointmentForm.html <form action="" method="post"> {% csrf_token %} {{ form|crispy }} <label for="id_id_appointment_time_0_1" class="form-check-label">1:00pm</label> <input class="btn btn-success-alt " type="submit" value="Submit"> </form> Attempting to create this This is where I am at -
post api with address field as foreign key should pass all attributes as city,area,
post API for passing foreign key attribute value with many fields of the address field in signup. # Employee model class Employee(models.Model): address = models.ForeignKey(Address, on_delete=models.CASCADE, null=True, blank=True) nationality = models.CharField(max_length=250, blank=True, null=True) profile_picture = models.ImageField(upload_to='pictures/', max_length=225, null=True, blank=True) # Address model class Address(models.Model): area = models.CharField(max_length=100) street = models.CharField(max_length=100) city = models.CharField(max_length=100) state = models.CharField(max_length=100) pincode = models.CharField(max_length=6) def __str__(self): return self.state @classmethod def create_employee(cls, email, password, first_name, last_name, mobile_number, dob, nationality, department, skill): user = User.objects.create(first_name=first_name, last_name=last_name, email=email, username=email) if not password: password = User.objects.make_random_password() user.set_password(password) user.save() dob_obj = datetime.datetime.strptime(dob, "%Y-%m-%d").date() for id in department: department_to_add = Department.objects.get(id=int(id)) emp = cls.objects.create(user=user, email=email, mobile_number=mobile_number, dob=dob_obj, nationality=nationality, return emp while signup for address field expected: address value passed with city, area,Pincode I want to pass address field value with it's attributes. -
How to add dynamic search filters with django-taggit and elasticsearch
I want to add dynamic search filters to my django-taggit tags using checkboxes next to my search form, so that a user can enter a query, select one or multiple checkboxes and get the result of any product that contains the selected value(s). How can I achieve this in both django and in my templates(html)? My Models.py looks like this: class Product(models.Model): title = models.CharField(max_length=255, default='') slug = models.SlugField(null=True, blank=True, unique=True, max_length=255, default='') description = models.TextField(default='') ptags = TaggableManager() image = models.ImageField(default='') timestamp = models.DateTimeField(auto_now=True) def _ptags(self): return [t.name for t in self.ptags.all()] def get_absolute_url(self): return reverse('product', kwargs={'slug': self.slug}) def __str__(self): return self.title and my search_form.html : <form class="search-form-container" action="/search/" method="get"> <div class="form-group"> <div class="icon-addon addon-lg"> <input type="text" placeholder="Search for good..." class="form-control" name="q" id="q" autocomplete="off"> <div id="selction-ajax"></div> </div> </div> <div class="col-md-3"> <!-- Tags section --> <div> <input class="facet" id="" type="checkbox" name="ptags" value="Solo" data-toggle="toggle" /> Solo </div> <div> <input class="btn btn-info btn-sm pull-right" type="submit" value="apply filter" onclick="return onFacetChangeApplied();" /> </div> </div> </form> Thanks in advance! -
How does django cache_page expire?
You set cache_page(60sec) for an endpoint, We assume the endpoint is requested every 5 sec Does the cache reset the timer for expiration every 5 sec , resulting in never expiring cache? Or does it expire after 60sec? -
Cannot Access Form Values With Python View in Django
I am trying to access the form values from a form that dynamically populates the number of input fields from a database query but I am not able to grab the values. def count_add(request): items = Item.objects.filter(username=request.user) if request.method == 'POST': form = CountAddForm(request.POST) for item in items: print(request.POST[item]) # if request.POST[item] != None: # print(item) # rating = form.save(commit=False) # rating.username = request.user # rating.item = item # rating.date = datetime.now() # rating.rating = request.POST[item] # rating.save # form = CountAddForm() return render(request, 'count_add.html', {'items': items}) <div class="container"> <div class="row"> <div class="col s12 opacity"> <h4 class="card-title center-align white-text">Rate Your Items Below</h4> <form method="POST" class="center-align white-text"> {% csrf_token %} <ul class="center-align white-text"> {% for item in items %} <li class="input-field col s12"> <select name="{{ item }}" class="browser-default"> <option value="" disabled selected>{{ item }}</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> </select> </li> {% endfor %} My desire is to get a value back from the input fields and save them in the database. I get None back when I do actually retrieve a value currently. -
In Django how to update multiple objects dynamically with values from dict
I have two models model1 and model2 and model1 have a field which is a foreign key pointing to model2. Also, I have a model1_model2_dict with keys as model1.id and value as model2.id. Now I am trying to bulk update the model1.model2_id field using the model1_model2_dict. I tried like this model1.objects.filter(model2_id=None).update(model2_id=model1_model2_dict.get(F('id'), None)) this statement resulted in the update count that I expected, but it actually did not update with model2_id instead it updated with None. Any help on how to make this work? -
Displaying ManyToManyField on Django Page
I'm trying to create a blog on Django, which on a blog post I can add one or more events and list them. For example: Blog Post A has Event1 and Event2 Blog Post B has Event 1 and Event 3 The main area I'm struggling with, is getting this code to actually show up on the page. I've tried a combination of things. The data shows up in the admin + database, but not on the front-end page On the Model I'm showing the below class Event(models.Model): eventname = models.CharField(max_length=150) location = models.CharField(max_length=150) eventdate = models.DateField(blank=False) eventlink = models.URLField(max_length=800) class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) title = models.CharField(max_length=120) slug = models.SlugField(unique=True) image = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field") height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) content = models.TextField() draft = models.BooleanField(default=False) publish = models.DateField(auto_now=False, auto_now_add=False) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) eventlist = models.ManyToManyField(Event) On the HTML I'm showing the below <h3> {{ post.listevents.eventname }} </h3> I expect the output to show the Event Name field on the page -
Django Rest Framework model serializer field level validation
I have a DRF ModelSerializer, and I'm trying to override the validation, to no avail. The reason to override the validation is that the corresponding model field is a postgresql HStoreField, so effectively a python dict. However, the incoming data is an array, and I build the corresponding dict during the create function. Serializer: class ReportSerializer(serializers.ModelSerializer): class Meta: model = Report fields = "__all__" def create(self, validated_data): codes = validated_data.pop("report") report = {code: translate_code(code) for code in codes} return Report(**validated_data, report=report) def validate_report(self, value): print("called") return type(value) == type([]) # I know this is hacky So the idea is to translate all of the codes to their respective translations, and save that as a key value pair. This is because I will always need the code and its translation together, and from a performance standpoint it makes more sense to do this once and save it in the db, rather than doing the translation on read. tl;dr: Model field expects dict, data is actually list, I'm trying to override the validation of this field on the serializer to accept this. Unfortunately, the validate_report function never seems to be called, and I'm not sure why. -
Why is the Django admin having trouble with underscores and hex characters in primary keys?
When I click certain links in the admin page of my application, I'm getting errors that look like this: "Object with ID "12345-2Q2019-SCAâA" doesn't exist. Perhaps it was deleted?" The primary key of the record (which is displayed on the link) is actually this: 12345-2Q2019-SCA_E2A Any record that contains an underscore, followed by a capital A-F, gives this error. It seems that Django is wanting to encode the underscore and the trailing letters to a hex character, and since the PK with the hex character isn't present in the database, Django can't find the record and won't redirect to my object's change form. I've tried casting this PK to a string the models by overriding the get_admin_url() method: # models.py def get_admin_url(self): content_type = ContentType.objects.get_for_model(self.__class__) return reverse("admin:%s_%s_change" % (content_type.app_label, content_type.model), args=(self.id,)) And in the admin file by manually creating the url using format_html: # admin.py def url_for_result(self, result): pk = Object.objects.get(id=result.id) html_string = format_html(u'<a href="/admin/project/object/{}/change/">{}', pk.id, pk.id) return html_string list_display = ('url_for_result',) Still, I'm unable to get the links with these 'hex' characters to link to their change form pages. My DB, server, and settings.py files all strictly define UTF8 encoding. Does Django encode/decode these hex characters somewhere, or is … -
Wagtail Page Reverse Error when trying to edit a page
I'm getting the following error: Reverse for 'wagtail_serve' not found. 'wagtail_serve' is not a valid view function or pattern name. This is a new install and I'm trying to edit the default landing page. I've never had this error before. Django==2.2.1 wagtail==2.5 wagtail-condensedinlinepanel==0.5.2 wagtailmenus==2.13 Any ideas on what could be causing this? Did I miss a setting somewhere? Any suggestions? -
How can user registration form for base django user model create ForeignKey user
I am new to django and am trying to set up a simple employee timesheet site that has multiple users. I set up two models one for the individual employee that has a ForeignKey of the base django user and a timesheet model that has a ForeignKey of the employee model. I'm not sure this is correct because when I use my registration form it just creates the base django user and not the "Employee" so when I want to create a new timesheet entry only the one employee is set up (set up with admin page). Can someone with more django experience tell me if there is a better way to do this (different model relationship, etc) from django.urls import reverse from django.core.validators import MinValueValidator, MaxValueValidator from django.utils import timezone import datetime from django.contrib.auth.models import User class Employee(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='employee') payRate = models.DecimalField(max_digits=4, decimal_places=2, default=15.00, verbose_name=("Pay")) vacTotal = models.DecimalField(max_digits=5, decimal_places=2, default=200.00, verbose_name=("Vacation")) # META CLASS class Meta: verbose_name = 'employee' verbose_name_plural = 'employees' # TO STRING METHOD def __str__(self): return f"{self.user}" class Tsheet(models.Model): # CHOICES WORK_CHOICES= ( ('W', 'Regular Work'), ('V', 'Vacation'), ('S', 'Sick',), ('C','Call In'), ) # DATABASE FIELDS name = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='name') workType … -
Image loading is too slow in Django imagekit
The below code snippet is how I use Django imagekit. I use many images on my website, but the initial loading is pretty slow because of image caching. So, if a page has images that have never been loaded, then it take about 5 seconds to be loadded, otherwise it gets loaded within a second. Just to make sure, there is no problem for image resizing as most of them are under 10kb and about a hundred images are loaded in a page. I feel like the image caching should happen when the image is uploaded so that I don't need to have image caching when I go to a page on my website. Is it possible to be done with Django imagekit? thumbnail.py from imagekit import ImageSpec, register from imagekit.processors import Thumbnail class ArticleHeadlineSmall(ImageSpec): processors = [Thumbnail(430)] format = 'JPEG' options = {'quality': 60} register.generator('thumbnail:article_headline_small', ArticleHeadlineSmall) ... HTML {% generateimage 'thumbnail:article_headline_small' source=article.headline_image -- class="card-img-top" alt=article.title %} -
Django manytomany relationship on recipe-meal
So I have this two models, which is Recipe and Meal. For example I want to get the Chicken Pasta meal for chicken and pasta ingredients. how do I do that? class Recipe(models.Model): mealId = models.ForeignKey('meal.Meal',on_delete=models.CASCADE,related_name='meal') ingredientId=models.ManyToManyField('ingredient.Ingredient') amountId=models.ManyToManyField('amount.Amount') class Meal(models.Model): mealName=models.CharField(max_length=100,verbose_name="Meal name") desc=RichTextField() img=models.ImageField(blank=True) categoryId=models.ManyToManyField('category.Category') -
How to fix NoReverseMatch 'user' is not a registered namespace
I'm setting up a website, and want to make a user login page. But I always get "NoReverseMatch at /users/login/ and 'user' is not a registered namespace" when I am on the login page. url.py from django.urls import path from django.contrib.auth.views import LoginView from . import views app_name ='users' urlpatterns = [ path('login/', LoginView.as_view(template_name='users/login.html'), name='login'), ] login.html {% extends "learning_logs/base.html" %} {% block content %} {% if form.errors %} <p.Your username and password didn't match. Please try again.</p> {% endif %} <form method="post" action="{% url 'user:login' %} {% csrf_token %} {{ form.as_p }} <botton name="sumbit">log in</button> <input type="hidden" name="next" value="{% url 'learning_logs:index' %} </form> {% endblock content %} and base.html that login extends from <p> <a href = "{% url 'learning_logs:index' %}">Learning Log </a> - <a href = "{% url 'learning_logs:topics' %}">Topics</a> - {% if user.is_authenticated %} Hello, {{ user.username }}. {% else %} <a href="{% url 'users:login' %}">log in</a> {% endif %} </p> {% block content %}{% endblock content %} -
How to make changes take effect to a deployed project
I am trying to make changes such as images, files, etc to take effect to a Django project that has already been deployed by AWS. I managed to somehow make the changes but the photos are broken. I rebooted the instance and it's still broken. I wanted to verify if the git commands I've used are appropriate to use for future Django projects? I am able to access the AWS server. There is only one master branch and I'm using GitBash. ~$/project_name$ source venv/bin/activate ----update the codes within Visual Studio so it will show up in GitHub---- ~$/project_name/repo_name$ git add --all ~$/project_name/repo_name$ git commit -m "message" ~$/project_name/repo_name$git pull origin master -------Nano screen shows up and I input the message and type in Ctrl-X and respond "no"----------- and thereafter, it'll show the changes. Are these steps appropriate? -
Calling the current user in a Django view and template
I have a view where a chat channel is created between two users. I want to notify the user when a message is sent (who it came from) but I'm having trouble accessing the current user (the user who is logged in and sending the message). In the view below I have a 'to_user' whose name is displayed properly, however, the 'current_user' is not displaying. Here is my views.py @login_required def create_channel(request, to_user_id): to_user = get_user_model().objects.get(pk=to_user_id) try: channel = Channel.objects.get(users=request.user, users__id=to_user_id) except Channel.DoesNotExist: channel = Channel.objects.create( channel_name='{from_user}-{to_user}'.format(from_user=request.user.username, to_user=to_user) ) channel.users.add(request.user) channel.users.add(to_user) client = get_client() service = client.chat.services(settings.TWILIO_CHAT_SID) twilio_channel = service.channels.create(channel.channel_name) channel.twilio_chat_id = twilio_channel.sid twilio_channel.members.create(identity=request.user.get_twilio_user_id()) twilio_channel.members.create(identity=to_user.get_twilio_user_id()) channel.save() #email the to_user when they receive a message to_user = to_user current_user = request.user to_user_email = to_user.email user_email = current_user.email html_message_to_user = render_to_string('send_message_to_user.html', {'user': current_user, 'to_user': to_user, 'channel': channel, } #send email to the to_user send_mail(current_user.first_name + ' has sent you a message', plain_message_to_user, 'x@x.com', [to_user_email], fail_silently=False, html_message=html_message_to_user) mail_admins('A message has been sent', 'A message has been sent to ' + to_user.first_name + ' from ' + current_user.first_name, fail_silently=False, ) return HttpResponseRedirect(reverse('chatapp:twilio', kwargs={'pk': channel.pk})) The email is sending properly however the 'current_user' first_name is not showing up. I have also tried to simply put … -
Error: requested URL /media/ was not found on this server
I'm using Django on pythonanywhere to create a webapp. I'm trying to access a file in my media folder by going to http://thedstrat94.pythonanywhere.com/media/6906qzxo55711_rM0he7x.png. I only get a 'Not Found' error My Url Patterns in urls.py looks right: urlpatterns = [ path('admin/', admin.site.urls), #url(r'^admin/', admin.site.urls), path('', views.index, name = "index"), path('about/',views.about,name = "about"), path('articles/',include("article.urls")), path('user/',include("user.urls")), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My settings.py file looks right: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' -
Get session information in generic view, to use in filtered queryset
So I am trying to list the team members of a current team in django. I want to use the session information to get the current team of the user, and then use that in a query to get all the team members. The problem is I don't really know how to write the get_current_users_team_id function within the generic view. I am not sure if the Team ID (which is a column I added to the user model) is directly accessible in the contrib.auth.models middleware, so I may have to use the user id to get the team id first. from django.contrib.auth.models import User class ListTeamView(generics.ListAPIView): serializer_class = UserSerializer authentication_classes = (TokenAuthentication,) def get_current_users_team_id(): current_user = self.request.team return current_user.team T = Team.objects.get_current_user.get(team_id=get_current_users_team_id()) queryset = T.user_set.all() -
django create modelform with dynamically create related fields and show updated form fields
I have the following two Model classes. class Question(models.Model): question_text = models.CharField(max_length = 100) pub_date = models.DateTimeField('date published') question_type = models.CharField(max_length = 100) def __str__(self): return self.question_text class Choice(models.Model): choice_text = models.CharField(max_length = 200) votes = models.IntegerField(default = 0) question = models.ForeignKey(Question, on_delete = models.CASCADE,related_name = 'q_choice') def __str__(self): return self.choice_text I am trying to create a modelform of Question. class QuestionForm(forms.ModelForm): class Meta: model = Question field = ['question_test','pub_date','question_type'] I want the following feature in the form, First should ask for question_text, pub_date and the question_type. If I choose question_type is equal to 'SELECT_ONE_CHOICE', then a add_choices+ button should appear and this button should enable us to enter n choices in a textfield box (one after another, by clicking add_choices+ n times). And these choices should also be reflected in the related_name attribute q_choice (create n q_choice and save() this question model). If I choose question_type is equal to 'SELECT_ALL_CHOICE' then similar sequence actions should happen and eventually QuestionForm should be saved. I can later display the Questions using radio or checkbox for choices depending on the question_type(this I know how to code) How can this be done using the modelform of Django? Basically how these intermediate interaction with …