Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python converting Django model.datetime from 24hr to AM/PM?
So I have this model field in Django that stores time in YYYY-MM-DD HH:MM:SS, here is how its created. station_0_checked_time = models.DateTimeField( null = True, default = datetime.datetime(1970, 1, 1, 0, 0) ) The data is stored properly as verified by the admin section of my Django site. Station 0 Checked Time: Date: 1970-01-01 Time: 22:00:10 However, when attempting to retrieve the data in a Django view with the following code I get the wrong output #SUBCARD is the name of the model object print(SUBCARD.station_0_checked_time) Expected: 1970-01-01 22:00:10 Actual: 1970-01-02 06:00:10+00:00 I don't really understand the conversion that is happening here. Thank you for the help. -
Form Validation not happening for Django model form
I have created the following model form and I want to apply validation on it but it is not working. Can anyone please tell me what mistake I am making? """class used for booking a time slot.""" class BookingForm(forms.ModelForm): class Meta: model = Booking fields = ['check_in_date', 'check_in_time', 'check_out_time', 'person', 'no_of_rooms'] """Function to check if username and password match or not.""" def clean(self): cleaned_data = super().clean() normal_book_date = cleaned_data.get("check_in_date") normal_check_in = cleaned_data.get("check_in_time") if (normal_book_date < now.date() or (normal_book_date == now.date() and normal_check_in < now.time())): #self._errors['check_in_date'] = self.error_class([ # 'You can only book for future.]) raise ValidationError( "You can only book for future." ) return cleaned_data -
Django: Custom PasswordResetForm issues
I have looked over other answers and questions and nothing I do seems to be working any suggestions on why this is not working. My custom class is not overiding and taking on a class or placeholder. I would like to try to get this set up to clean it up on my html to match my theme. My only thought might be the way I am using the url Path not being right how ever with my custom view reference it I dont know how to implement this properly. Form: from django.contrib.auth.forms import PasswordResetForm class UserPasswordResetForm(PasswordResetForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Override the email widget self.fields['email'].widget = forms.TextInput( attrs={'class': 'form-style', 'type': 'email', 'required': 'required', 'placeholder': 'Email'}) View: def password_reset_request(request): if request.method == "POST": password_reset_form = UserPasswordResetForm(request.POST) if password_reset_form.is_valid(): data = password_reset_form.cleaned_data['email'] associated_users = CustomUser.objects.filter(Q(email=data)) if associated_users.exists(): for user in associated_users: subject = "Password Reset Requested" email_template_name = "members/password_reset_email.txt" c = { "email":user.email, 'domain':'127.0.0.1:8000', 'site_name': 'Website', "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, 'token': default_token_generator.make_token(user), 'protocol': 'http', } email = render_to_string(email_template_name, c) try: send_mail(subject, email, 'admin@example.com', [user.email], fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect("/password_reset/done/") password_reset_form = PasswordResetForm() return render(request=request, template_name="members/password_reset.html", context={"password_reset_form": password_reset_form}) Template: {% extends 'members/base.html' %} {% block … -
Filter by multiple years in DRF
So I'm trying to do filter by year and so it could use multiple values like this filter?year=2000,2021 And with this I should get all objects with year 2000 or 2021 My filter.py from django_filters import( BaseInFilter, NumberFilter, FilterSet, CharFilter, ) from .models import Research class YearInFilter(BaseInFilter, NumberFilter): pass class ResarchFilter(FilterSet): year = YearInFilter(field_name='date', lookup_expr='year') category = CharFilter(field_name='category', lookup_expr='iexact') class Meta: model = Research fields = ['date', 'category'] It looks almost like example from django-filter. But when I'm trying to use it i've got an error Field 'None' expected a number but got [Decimal('2000'), Decimal('2021')]. So what's wrong here? Why here is Decimal? Why it's not number? And how make it work like expected? -
AttributeError: partially initialized module 'posts.views' has no attribute 'SearchMenuPage' (most likely due to a circular import)
I'm attempting to emulate the url routing of StackOverflow when it comes to requesting a URL with the path of search/. As shown, requesting that URL redirects to search?q=. Yet the following error is being raised when running the test to achieve the aforementioned result: AttributeError: partially initialized module 'posts.views' has no attribute 'SearchMenuPage' (most likely due to a circular import) Within the RedirectView, I set the url attribute to an f-string that interpolates reverse_lazy(). https://docs.djangoproject.com/en/4.1/ref/urlresolvers/#reverse-lazy What is the cause of this error and what would be the appropriate fix? class TestRedirectSearchView(TestCase): def setUp(self): self.request_url = reverse('posts:search_menu') self.response_url = f"{reverse('posts:search_results')}?q=" def test_search_page_response(self): response = self.client.get(self.request_url, follow=True) self.assertRedirects(response, self.response_url) posts_patterns = ([ path("", pv.QuestionListingPage.as_view(), name="main"), re_path(r"questions/?", pv.AllQuestionsPage.as_view(), name="main_paginated"), re_path(r"questions/ask/?", pv.AskQuestionPage.as_view(), name="ask"), re_path(r"questions/<question_id>/edit/?", pv.EditQuestionPage.as_view(), name="edit"), re_path("questions/<question_id>/edit/answers/<answer_id>/?", pv.EditPostedAnswerPage.as_view(), name="answer_edit"), re_path("questions/<question_id>/?", pv.PostedQuestionPage.as_view(), name="question"), re_path(r"questions/search/", pv.SearchMenuPage.as_view(), name="search_menu"), re_path(r"questions/search", pv.SearchResultsPage.as_view(), name="search_results"), path("questions/tagged/<tags>", pv.TaggedSearchResultsPage.as_view(), name="tagged") ], "posts") class SearchMenuPage(RedirectView): url = f"{reverse_lazy('posts:search_results')}?q=" class SearchResultsPage(PaginatedPage): def get(self, request): query, tab_index = request.GET.get('q'), request.GET.get('tab', 'newest') queryset, query_data = Question.searches.lookup(tab_index, query=query) if query_data['tags'] and not query_data['title'] and not query_data['user']: tags = "".join([ f"{tag}+" if i != len(query_data["tags"]) - 1 else f"{tag}" for i, tag in enumerate(query_data["tags"]) ]) return HttpResponseRedirect(reverse("posts:tagged", kwargs={'tags': tags})) else: context = super().get_context_data() search_value = "".join(list(reduce( lambda main_string, … -
Even guincorn is installed, Package 'gunicorn' is not installed, so not removed
I want to remove guincorn completely from my ubuntue server. However, when trying to run sudo apt-get purge --auto-remove gunicorn . it says Package 'gunicorn' is not installed, so not removed. Here is a screen shot which shows gunicorn is installed. How can I complete remove guincorn from my server? -
My django admin search list page view distorted
Is anyone know how to fix this css issue getting distorted see screenshot this is the screenshot of distorted -
How to count reviews for a product in django?
I am building an ecommerce website with django. In my models I have a Product and review model. How should i connect the two for the number of reviews and average rating attribute? This is my current models file class Product(models.Model): name = models.CharField(max_length=200, null=True, blank=True) brand = models.CharField(max_length=200, null=True, blank=True) image = models.ImageField(null=True, blank=True, default='placeholder.png') description = models.TextField(null=True, blank=True) rating = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) countInStock = models.IntegerField(null=True, blank=True, default=0) id = models.UUIDField(default=uuid.uuid4, max_length=36, unique=True, primary_key=True, editable=False) numReviews = [Count the number of reviews where product.id matches self.id] averageRating = [Sum up the ratings in reviews for this product and divide them by their count] def __str__(self): return str(self.name) class Review(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) rating = models.IntegerField(null=True, blank=True, default=0) comment = models.TextField(null=True, blank=True) createdAt = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, max_length=36, unique=True, primary_key=True, editable=False) def __str__(self): return f'{self.user} review for {self.product}' As you can see the numReviews and average rating columns are meant to connect both tables. I have been trying to figure out how to do it correctly with no success. Any help would be greatly appreciated -
Why is my function get_absolute_url is merging my domain into my website name?
I'm using the Django sitemap framework, and I have to use the function get_absolute_url to render the site URL in the sitemap. However, I'm facing a problem because my link is becoming: exampleio.io instead of example.io. My function in my model is it: def get_absolute_url(self): return reverse('packages', args=[self.name]) My function in the sitemap.py class ExampleSitemap(Sitemap): protocol = "https" changefreq = "weekly" priority = 0.7 limit = 500 def items(self): return Example.objects.all() I'm getting: <sitemap> <loc>http://exampleio.io/sitemap-examples.xml</loc> </sitemap> -
how to convert my html string into its own datatype?
I'm fairly new to JS and HTML, Working on a Django project now makes me crazy about it . I have passed a variable from context from Django toward html. I noticed the datatype of the data is converted to string by defualt. views.py: context = {'segment': 'index', "service_data": data } html_template = loader.get_template('index.html') return HttpResponse(html_template.render(context, request)) HTML pages <div class="card-body"><canvas id="myAreaChart" width="100%" height="40"></canvas></div> <script type="text/javascript"> const service_data = "{{ service_data }}" </script> In Javasript, I can see the datatype of service_data is string. I'd like to traverse it as a array, but it is converted to string. const data = Array.from(service_data); //this is converted to objet not arrary.. function prepareChartData(data) { var chartData = []; for (var i = 0; i < 10; i++) { let timestampe = data[i][0] let dat_list = data[i][1] chartData.push([timestampe, dat_list]); My service_data is a fairly large data from django backend, hence, I do not want to use split or something to convert it. The service_data snipet: Please ignore those &gt, etc, not sure why HTML added them, but image the data itself is a very nested dictnary. [(datetime.datetime(2022, 10, 4, 18, 35, 1, 247336, tzinfo=&lt;UTC&gt;), [[{&#x27;kubernetes_pod_name&#x27;: &#x27;kafka-rawbus-bravo-3&#x27;, &#x27;value&#x27;: 7.5456592756413645}, {&#x27;kubernetes_pod_name&#x27;: &#x27;kafka-rawbus-bravo-5&#x27;, &#x27;value&#x27;: 6.988051860579239}, {&#x27;kubernetes_pod_name&#x27;: … -
Simple JWT Method Not Allowed on Django App deployed on Gcloud App Engine
I am fairly new to django and gcloud and I am currently stuck at this issue where I am trying deploy my Django App on Gcloud App Engine. When accessing the api for getting token I got this error. Error when accessing API from App Engine from django.contrib import admin from django.urls import include, path from rest_framework_simplejwt import views as jwt_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('quitnow/', include('quitnow.urls')), path("admin/", admin.site.urls), path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), ] This is my urls.py. When I try to post my information to get token, the post requests doesn't return a response and hangs. I am stuck on this for days. Would really appreciate any help! -
The logic of if statement and (return redirect) in django
def set_default(request, id): Address.objects.filter(customer=request.user, default=True).update(default=False) Address.objects.filter(pk=id, customer=request.user).update(default=True) previous_url = request.META.get("HTTP_REFERER") if "delivery_address" in previous_url: return redirect("checkout:delivery_address") return redirect("account:addresses") This is a function that sets address to default and if the user came from checkout address page it sets default and return to same page.My question is about the logic of the if statment here.As far as I understand..If the condition is true return redirect("checkout:delivery_address") will be executed and it will exit the if condition then the last line will be executed return redirect("account:addresses") Why doesn't that happen and only the statment after if is executed when the condition is true? -
Best Python Framework suitable with Blockchain Database
As a side project, I have a web application idea, and I want to use Python at the backend. Firstly, I will use a conventional database. But after finishing the web application, I am planning to switch the database with a blockchain-based database like BigchainDB, or I will implement my blockchain. So my question is, which Python framework best suits this kind of database system? -
Update Django Formsets with data on many_to_many field
I feel like I've exhausted my google-fu on this subject. I've tried so many different ways, I can't remember what I've tried. I have a class "Recipe" which has 3 many_to_many fields. I've got an empty form using formsets for each many_to_many object for new. I'm now modifying the form to include "update", but I cannot seem to get the formsets to populate the data. I've tried "instance=", I've tried passing in a dictionary "model_to_dict", but I can't seem to figure this out. My current iteration looks like this: models.py: class Recipe(models.Model): def __str__(self): return self.name class Meta: unique_together = ('name', 'version') bs_file = models.FileField(storage=fs,null=True) name = models.CharField(max_length=75) dateCreated = models.DateField() dateUpdated = models.DateField(null=True, blank=True) version = models.IntegerField(null=True, blank=True) #type = models.CharField(max_length=30) #Cider, Mead, Wine, etc category = models.ForeignKey(BatchCategory,on_delete=models.CASCADE) brewer = models.CharField(max_length=30, null=True) batchSize = models.FloatField() #in Liters source = models.CharField(max_length=50, null=True) #Where did the recipe come from pairing = models.CharField(max_length=250, null=True) # Textfield listing various foods. TODO: Refactor notes = models.TextField() estOG = models.FloatField() estFG = models.FloatField() estABV = models.FloatField() fermentables = models.ManyToManyField(RecipeFermentable) adjuncts = models.ManyToManyField(RecipeAdjunct) yeasts = models.ManyToManyField(RecipeYeasts) You can see my 3 many_to_many fields at the bottom. views.py: def addRecipe(request,pk=None): if request.method == "GET": form = RecipeAddForm() … -
give a category using the action in django admin
can I use django actions to give a category to my articles? class Category(models.Model): name = models.CharField(max_length=155, db_index=True) class Woman(models.Model): title = models.CharField(max_length=255) content = models.TextField(blank=True) photo = models.ImageField(upload_to='img', blank=True) time_create = models.DateTimeField(auto_now_add=True) time_update = models.DateTimeField(auto_now=True) is_published = models.BooleanField(default=True) cat = models.ForeignKey(Category, on_delete=models.PROTECT,null=True) How can i create an action with the help of which it will be possible to give categories for several articles. I mean something like that https://docs.djangoproject.com/en/4.0/ref/contrib/admin/actions/ -
How to send emails from a contact form to recipient? Django
When I click the 'Send Message' button it gives me the message that it sent, but when I check my email the email is not there. Any help please? This is my first web application using Django. this is what it says in Git Bash after I send the message this is the index.html this is the views.py file this is the contact form, the contact form was made in index.html this is the settings.py file -
How to pass model instance pk to template from Django modelformset?
I have a model that I want to display in a template with a modelformset. I want to be able to delete instances of the model by pressing a button in the template, but I can't seem to pass the instance's pk. The "id" field only passes a huge boundfield that generates and error when I use it for the delete button. Is there any way to pass the instance's pk to the template? models.py class Activity(Model): user = ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE) activity = CharField(max_length=100, default='') number = IntegerField(default=1) def __str__(self): return self.activity Built in a formset: views.py activities = Activity.objects.filter(user=request.user) pre_formset = modelformset_factory(Activity, fields=('activity', 'number', 'id',)) formset = pre_formset(queryset=activities) template.html { formset.management_form }} {% for activity in formset %} {{ activity.id }} {{ activity.ORDER }} {{ activity.DELETE }} {% if not forloop.first %} <a class="btn" href="{% url 'activity_delete' activity.pk %}" onclick="return confirm('Are you sure you want to delete this activity?')">X</a> {% endif %} {% endfor %} -
json as table with django
I have modeled my database using models.py within my django project, one of the fields is a JSONField and I can save json data into that field without any problem. My doubt comes in how I can show that information as an html table. At the moment I have been using ListView to show that information in a template but I don't know how to transform it into a table. -
NGINX 403 (Forbidden) - Django React project
Hello i have problem with my Django React project .. i have 403 error on static files(js, css)..Error 403 NGINX Django -
Django Model Form field data not displaying
So I am trying to figure out why my dropdown menu will not display the list of collections for the user to pick from. IMAGE: [1]: https://i.stack.imgur.com/UIrq6.png Here is also the code for the 2 models here: class Collection(models.Model): title = models.CharField(max_length=255) def __str__(self) -> str: return self.title class Meta: ordering = ['title'] class listing(models.Model): image = models.ImageField(blank=True, null=True) name = models.CharField(max_length=255) description = models.TextField() unit_price = models.DecimalField(max_digits=6, decimal_places=2, validators=[MinValueValidator(1)]) inventory = models.IntegerField() last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT, blank=True, null=True) vendors = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=False) IF I CAN GET ANY HELP IT WOULD BE NICE. -
How to check the current isolation level setting in Django?
I'm trying to check the current isolation level setting in Django. For example, the default isolation level setting in Django is READ COMMITTED so if there is transaction.current_isolation_level(), I can print READ COMMITTED on console to check the current isolation level setting in Django as shown below: # "views.py" from django.http import HttpResponse from django.db import transaction @transaction.atomic def test(request): # Here print(transaction.current_isolation_level()) # READ COMMITTED return HttpResponse("Test") And if I set REPEATABLE READ for the isolation level setting in Django as shown below: DATABASES = { 'default':{ 'ENGINE':'django.db.backends.postgresql', 'NAME':'postgres', 'USER':'postgres', 'PASSWORD':'admin', 'HOST':'localhost', 'PORT':'5432', }, 'OPTIONS': { # Here 'isolation_level': psycopg2.extensions.ISOLATION_LEVEL_REPEATABLE_READ, }, } I can print REPEATABLE_READ on console to check the current isolation level setting in Django as shown below: # "views.py" from django.http import HttpResponse from django.db import transaction @transaction.atomic def test(request): # Here print(transaction.current_isolation_level()) # REPEATABLE READ return HttpResponse("Test") So, are there such functions or variables to get the current isolation level setting in Django? If no, how to check the current isolation level setting in Django? -
Authentication verification message is not displaying as a hyperlink in the mail but rather displaying as a text in the email. please, help me
views.py under my views I have all my views for user authentication which includes: signin, signup, signout and other function views. from django.core.mail import EmailMessage,send_mail from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth import authenticate,login,logout from my_site.settings import EMAIL_HOST_USER from django.core.mail import send_mail from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_encode,urlsafe_base64_decode from django.utils.encoding import force_bytes,force_str from .tokens import generate_token from .models import User # Create your views here. def all(request): return render(request,'authentication/all_signups.html') def signup(request): if request.method == "POST": username = request.POST.get("username") fname = request.POST.get("fname") lname = request.POST.get("lname") email = request.POST.get("email") password = request.POST.get("password") password2 = request.POST.get("password2") if User.objects.filter(username=username): messages.error(request, "Username already exist!") return redirect('home') if User.objects.filter(email=email): messages.error(request, "E-mail already exist!") return redirect('home') if len(username) > 15: messages.error(request, "Length of username too long!") return redirect('home') if password != password2: messages.error(request, "Passwords do not match!") return redirect('home') if not password.isalnum(): messages.error(request, "Password must be alphanumeric!") return redirect('home') user = User.objects.create_user(username=username,email=email,password=password) user.fname = fname user.is_active = False user.save() # Welcome E-mail subject = 'Welcome to ADi meals mobile!' message = f'Hello {fname.capitalize()}, welcome to ADi meals mobile!\n\nThank you for visiting our website.\n\nWe have also sent you a confirmation email, please confirm your email address to login into … -
Form returning not valid in django
In my django app I have a User model that has a Boolean field of is_manager. User model in models.py: class User(AbstractUser): name = models.CharField(max_length=15, null=True, blank=True) last_name = models.CharField(max_length=15, null=True, blank=True) title = models.CharField(max_length=50, null=True, blank=True) email = models.EmailField(unique=True) bio = models.TextField(null=True, blank=True) company = models.ForeignKey(Company, on_delete=models.DO_NOTHING, null=True) is_manager = models.BooleanField(default=False) can_assign = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] I've been trying to create an edit page in order for managers and users to be able to change some of their fields. Regular users should be able to change their bio and title, and the managers can change the can_assign Boolean. I have a form that deals with the logic of that in forms.py: class EditUserForm(ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') if self.user.is_manager: super().__init__(**kwargs) else: super().__init__(**kwargs) del self.fields['can_assign'] class Meta: model = User fields = ['title', 'can_assign', 'bio'] views.py: @login_required def editUser(request, pk): user = User.objects.get(id=pk) if request.user.is_manager or request.user == user: #POST if request.method == 'POST': form = EditUserForm(request.POST, instance=user, user=request.user) if form.is_valid(): form.save() redirect('user-page', pk) else: print('nope') #GET form = EditUserForm(user=request.user, instance=user) context = {'user': user, 'form': form} return render(request, 'users/user_edit.html', context) else: return HttpResponse('<h1>Access Denied</h1>') template: {% extends 'main.html' %} {% block content … -
CircleCI config for django
I have this circleci config version: 2.1 orbs: python: circleci/python@0.2.1 jobs: build: executor: python/default docker: - image: circleci/python:3.9 environment: DATABASE_URL: postgresql://circleci@localhost/circle_test - image: circleci/postgres:13.3 environment: PGHOST: localhost PGUSER: circleci POSTGRES_USER: circleci POSTGRES_DB: circle_test POSTGRES_HOST_AUTH_METHOD: trust steps: - checkout - python/load-cache - run: name: Installing dependencies command: | python3 -m venv venv . venv/bin/activate pip3 install -r requirements.txt - python/save-cache - run: name: Running tests command: | . venv/bin/activate python manage.py test When i commit django-test with TestCase, only choose test with SimpleTestCase, circleci comlete, but when i uncomment TestCase i have this errors RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead -
How Do I Override GET in Django Detailview?
I have a FORMVIEW that is redirecting to a DETAILVIEW and that is working perfectly. The issue I'm having is when I try to combine Pagination with DetailView. When I try to leverage the pagination, the GET is essentially redirecting me to the FORMVIEW. I get why it's doing this...I'm telling it to. What I'm trying to work out is how I can put in some logic in my overridden GET. I tried to do a self.GET_OBJECT.pk...to see if I could determine if I'm on the current page and not the FORMVIEW but that didn't work... Here's my DetailView.... def get_context_data(self, **kwargs): context = super(SuggestionByNameDetailView, self).get_context_data(**kwargs) attachments = SuggestionFiles.objects.filter(suggestion=self.object.pk).all() comment_form = SuggestionCommentForm() response_form = SuggestionCommentReplyForm() activities= self.get_related_activities() context['suggestion_comments'] = activities context['page_obj'] = activities context['attachments'] = attachments context['comment_form'] = comment_form context['response_form'] = response_form return context def get_related_activities(self): queryset = self.object.suggestion_comments.all() paginator = Paginator(queryset,5) #paginate_by page = self.request.GET.get('page') activities = paginator.get_page(page) return activities def get_object(self, queryset=None): return get_object_or_404(Suggestion, id=self.request.GET.get("dropdown")) def get(self, request, *args, **kwargs): dropdown=self.request.GET.get("dropdown") if dropdown is not None: if Suggestion.objects.filter(Q(id=self.request.GET.get("dropdown"))).distinct(): self.object = self.get_object() context = self.get_context_data(object=self.object) return self.render_to_response(context) else: raise Http404 else: messages.add_message(self.request, messages.INFO, 'Suggestion is required.') return HttpResponseRedirect(reverse('Suggestions:suggestion_by_name')) As mentioned I did try to do something like...if DROPDOWN is …