Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to catch django forms error in javascript?
I have a django form to create something. Some of my form fields are required. Django forms return "this field is required" but I want to scroll page to empty field or start of form field. <div clas="some_class"> {{ django form field}} </div> I want to scroll page to this div container. <script> document.getElementsByClassName('my_button').onclick = function() { document.getElementById('create-address').scrollIntoView(); }; </script> How can I get fdjango form errors instead of button click ? Thanks. -
Cascade delete in Django + collecting deleted data
I have Django 2.2 models: class A(models.Model): pass class B(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) class C(models.Model): b = models.ForeignKey(B, on_delete=models.CASCADE) url = models.URLField(...) def do_something(set_of_urls): ... What I want is to do_something with all url values for which C instance being deleted, but I need to do it at once. In other words, when a.delete() cascades, deleting all of its B children, which in turn delete all of their C children, I want to call do_something({c.url for c in C.objects.filter(b__a_id=a.pk)}) However, I also want to be able to do b.delete(), which would then do do_something({c.url for c in C.objects.filter(b_id=b.pk)}) And same for c.delete() (which would just do do_something({c.url})). Further, relationship manager deletes should behave in a similar way: A.objects.filter(...).delete() would ideally call do_something for each deleted instance of A (so, not all URLs at once, but one call per each delete object). If grouping is problematic to implement, I could do with do_something for URLs of all affected instances of C. But I must avoid calling do_something for each affected C-child separately. B.objects.filter(...).delete() would call do_something for all URLs belonging to children of those deleted instances (filter will always ensure that all deleted instances of B belong to the same … -
Why Django base URL can't be reached?
I am having trouble accessing the base url for my django app once it is deployed. Can't reach base url: www.example.com This just runs until it times out. Can reach: www.example.com/home/ Here are my allowed hosts in settings.py: ALLOWED_HOSTS = ['example.com', 'example' 'https://example.com/', '127.0.0.1'] Here are my url patterns in myapp/urls.py: from .views import index urlpatterns = [ path('', index, name='index'), path('home/', index, name="index"), ] I have tried adjusting the url patterns but have had no success. Thanks for your help. -
Forgot Password Django - password_reset (custom user model)
looking for help. I am beginner Python/Django developer. I have the following view: class UserForgotPasswordView(auth_views.PasswordResetView): with open(str(settings.BASE_DIR) + "/frontend/static/frontend/languages/emails/EN/email_footer__main.json", "r") as temp_file_email_footer_main: email_footer_main_data = json.load(temp_file_email_footer_main) with open(str(settings.BASE_DIR) + "/frontend/static/frontend/languages/emails/EN/email_user_forgotPassword.json", "r") as temp_file_email_forgot_password: email_forgot_password_data = json.load(temp_file_email_forgot_password) extra_email_context = { 'email_footer_static_json_text': email_footer_main_data, 'email_static_json_text': email_forgot_password_data, 'static_json_text': static_textLanguage, 'static_json_textGlobal': static_textGlobal} html_email_template_name = '../frontend/templates/frontend/templates.emails/template.email_user_forgotPassword.html' from_email = 'numeratio <support@numeratio.com>' title = 'numeratio password reset' subject_template_name = 'registration/password_reset_subject.txt' template_name = '../frontend/templates/frontend/templates.user/template.page_forgotPassword.html' success_url = reverse_lazy('password_reset_done') def get(self, request, *args, **kwargs): context = super().get_context_data(**kwargs) try: if not self.request.user.is_authenticated: context = { 'email_subject': self.email_forgot_password_data['emailSubject'], 'static_json_text': static_textLanguage, 'static_json_textGlobal': static_textGlobal} return self.render_to_response(context) except: if self.request.user.is_authenticated: return HttpResponseRedirect(reverse('page_home')) What I am trying to get is that if the user is authenticated(logged) if he tries to go the the forgot-password link he is redirected home. The template render fine if the user is not logged/anonymous However, I am getting the following error for authenticated users trying to access the page The view users.views.UserForgotPasswordView didn't return an HttpResponse object. It returned None instead. I need help with the redirect. Any and all help is welcome. -
Possible ways to serve the gatsby static files (with image optimization) to later use it as a Django template?
Other than running gatsby and Django on two different servers and pointing it to the same domain is there any other to serve the gatsby static files as a Django template? -
How to find average rating of a gig from another reviews model?
I have two Django Models 'Gigs' and 'Reviews' I want to get an average of the ratings belonging to that Gigs field. I also want the avg_rating on the movie field to update every time a review is added. Im new to Django and I've tried alot but I don't really know what the error is. Below is my code files Models.py class Gigs(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey(Categories , on_delete=models.CASCADE) price = models.DecimalField(max_digits=6, decimal_places=2) details = models.TextField() seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE) @property def average_rating(self): if self._average_rating is not None: return self._average_rating return self.reviews.aggregate(Avg('rating'))['rating_avg'] class Reviews(models.Model): rating = models.SmallIntegerField( default=0,validators=[MaxValueValidator(5),MinValueValidator(1)]) comment = models.CharField(max_length=500) item = models.ForeignKey(Gigs , on_delete=models.CASCADE, related_name='reviews') buyer = models.ForeignKey(User ,default=None, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) Views.py class GigsListAll(GenericAPIView, ListModelMixin ): def get_queryset(self): return Gigs.objects.all().annotate(_average_rating=Avg('reviews__rating')) serializer_class = GigsSerializer permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.list(request, *args, **kwargs) Serializers.py class GigsSerializer (serializers.ModelSerializer): average_rating = serializers.FloatField() class Meta: model = Gigs fields = ['id','title','category','price','details','seller','images', 'average_rating'] But when I tried to go to my this Api it gives me an error "Got KeyError when attempting to get a value for field average_rating on serializer GigsSerializer.\nThe serializer field might be named incorrectly and not match any attribute or … -
Cannot find reference 'services' in '__init__.py' Pycharm
For some odd reason, Pycharm is not recognizing modules in my Django project. I looked online and there are a bunch of solutions that I tried: deleting .idea invalidating cache and restarting making the /beagle folder the source root None of those work. here is where I import the module: beagle/apps/memberships/models.py from django.db import models from beagle.services import plaid_api, stripe_api -
Default value if null or if value doesn't exist in the table Django
I have a product model like this below: class Brand(models.Model): name = models.CharField(primary_key=True, max_length=100) def __str__(self): return self.name class Product(models.Model): ... brand = models.ForeignKey(Brand, on_delete=models.PROTECT, default='Mercedes') ... When I am posting a product without the brand field it works and sets the product with brand default value, but when I add a brand field like this brand: "", or send a value which doesn't exist inside Brand table like this: brand: "abc123", it shows me informations: This field may not be null. and Invalid pk \"abc123\" - object does not exist.. I still want to set the default value in this situations, so if the value is null or does not exist I want to use the default='Mercedes'. How can I do this? -
how to validate token in jwt authentication in django rest framework
how to validate the JWT token in simle jwt authentication. i nned to verify when the user sends request if the token access token is expired so it will redirect him to refresh the token. serializers.py class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): # The default result (access/refresh tokens) data = super(CustomTokenObtainPairSerializer, self).validate(attrs) # Custom data you want to include data.update({'email': self.user.email}) data.update({'id': self.user.id}) data.update({'status':"success"}) # and everything else you want to send in the response return data views.py class CustomTokenObtainPairView(TokenObtainPairView): # Replace the serializer with your custom serializer_class = CustomTokenObtainPairSerializer urls.py from rest_framework_simplejwt.views import TokenRefreshView, TokenVerifyView urlpatterns = [ path('token/', views.CustomTokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('token/verify/', TokenVerifyView.as_view(), name='token_verify'), ] urlpatterns = format_suffix_patterns(urlpatterns) -
Django Mail Test Fails in GitHub Actions
I am trying to figure out why my mail test fails when run in GitHub Actions but succeeds when I run it locally. According to the Django documentation, the test runner uses an in-memory backend for email so it shouldn't rely on an SMTP connection. https://docs.djangoproject.com/en/3.2/topics/email/#in-memory-backend views.py class ContactApiView(View): def post(self, request): name = request.POST.get('name') email = request.POST.get('email') message = request.POST.get('message') if not name or not email or not message: return HttpResponseBadRequest('ERROR: All fields are required') body = 'Name: {}\nE-mail: {}\n\nMessage: {}.format(name, email, message) email = EmailMessage( 'Contact Form Submission', body, settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], None, reply_to=[email] ) email.send() return HttpResponse(status=200) tests.py (Works locally, Fails in GitHub Actions) class ContactApiViewTestCase(TestCase): def setUp(self): self.client = Client() self.viewname = 'contact_api' def test_happy_path(self): request_body = { 'name': 'John Doe', 'email': 'test@example.com', 'message': 'Hello world' } response = self.client.post(path=reverse(self.viewname), data=request_body) self.assertEquals(response.status_code, http.HTTPStatus.OK) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Contact Form Submission') GitHub Actions Error ====================================================================== FAIL: test_happy_path (app.tests.ContactApiViewTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/runner/work/repo/project/app/tests.py", line 137, in test_happy_path self.assertEqual(len(mail.outbox), 1) AssertionError: 0 != 1 GitHub Actions django.yml name: Django CI on: push: branches: [ main ] pull_request: branches: [ main ] jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: python-version: [3.9] steps: - uses: actions/checkout@v2 - name: … -
Update view not displaying data
I have a function-based view that does not load the data that was inputted. The view does not throw any error at all. It just presents the form as a blank one. urls.py path('edit/<slug>/', editPost, name='edit'), views.py @login_required def editPost(request, slug): if request.method == 'POST': post = get_object_or_404(Post, slug=slug) form = PostForm(request.POST or None, request.FILES or None, instance=post) if form.is_valid(): post.author = request.user.username post.updated = True form.save() return redirect('dashboard') else: form = PostForm(request.POST, request.FILES, instance=post) return render(request, 'edit_post.html', {'form': form}) template <form class="dropdown-item" action="{% url 'edit' slug=post.slug %}" method="post">{% csrf_token %} <input class="btn btn-sm" type="submit" value="Edit"> -
How create a model instance from a form with AJAX fields in Django?
I'm having troubles to create a model instance using a template that use AJAX to have a chained dropdown (I had followed this to do that functionality). When I want to save the form, my CreateView returns "form is invalid" and I don't know where is the problem. The commented blocks inside views.py are the methods that I investigated to solve the problem but couldn't figured out how. I suspect that my form does not load correctly my post data and could not retrieve the proper objects to save the instance for my model. Here is what I have until now: models.py: import uuid from django.db import models from django.forms import ModelForm, Textarea, RadioSelect, Select # Create your models here. class Cliente(models.Model): nombre = models.CharField("Nombre", max_length=50) descripcion = models.CharField("Descripción", max_length=120) def __str__(self): return '%s' % (self.nombre) class Servicio(models.Model): nombre = models.CharField("Nombre", max_length=50) descripcion = models.CharField("Descripción", max_length=120) clientes = models.ManyToManyField(Cliente, verbose_name="Clientes") def __str__(self): return '%s' % (self.nombre) class Etiqueta(models.Model): nombre = models.CharField(max_length=50) descripcion = models.CharField(max_length=120) servicios = models.ManyToManyField(Servicio, verbose_name="Servicios") def __str__(self): return '%s' % (self.nombre) # This is the model that I could not create new instances for my model class Lote(models.Model): lote_id = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False) creacion = models.DateTimeField(auto_now=False, auto_now_add=True) … -
Django, noReverseMatch
Hello I am struggling making cart to my e-commerce web app. I get error NoReverseMatch because of: <a class= "navbar__link" href="{% url 'cart-page' item.id %}">Cart</a> views.py: @login_required def add_to_cart(request, item_id, *args, **kwargs): item = Item.objects.get_object_or_404(Item, pk=item_id) order_item= OrderItem.objects.get_object_or_create( order_item = item, quantity=1) order = Order.objects.get_object_or_create(order_user=request.user, order_items=order_item) order.save() messages.success(request, "Cart updated!") return redirect('cart-page') models.py class OrderItem(models.Model): order_item = models.ForeignKey(Item, on_delete=CASCADE, null=True) quantity = models.IntegerField(default=1) class Order(models.Model): order_user = models.ForeignKey(User, on_delete=CASCADE) order_items = models.ManyToManyField(OrderItem) ordered = models.BooleanField(default=False) total = models.DecimalField(default=0.00, decimal_places=2, max_digits=11) class Item(models.Model): title = models.CharField(max_length=150) price = MoneyField( decimal_places=2, default=0, default_currency='USD', max_digits=11, ) image = models.ImageField(upload_to='pictures', default='static/images/man.png') description = models.TextField(default="Item") -
passing context into register form
I have a registration page, how can I pass the context to the header to display information in the header from the database view class RegisterFormView(FormView): form_class = UserCreationForm success_url = '/login/' template_name = 'essense/registration.html' def form_valid(self, form): form.save() return super(RegisterFormView, self).form_valid(form) def form_invalid(self, form): return super(RegisterFormView, self).form_invalid(form) -
django time convert from string format to standard
Here the time format is not same in terminal and postman,I do not know why this is so, is there any way to change the time value? x = VideoDetails.objects.filter(video__coursemodulevideos__module_id).aggregate(Sum('duration')) print('x', x) print('x',x['duration__sum']) result = { "ho":x['duration__sum'] } In terminal the output is x {'duration__sum': datetime.timedelta(seconds=130)} x 0:02:10 but in postman "hour": { "duration__sum": "P0DT00H02M10S" } Give me a solution to solve this problem. -
ModuleNotFoundError: No module named 'book' django
first I create a new app book and create a model class book then I messed up with that. I delete that app and create another app and run python3 manage.py runserver then I get this error enter image description here. I don't add anything in the new app. What can I do now? Is there anything more I want to specify? -
Making different views from similar (but slightly different) information?
I know there is a better way to do this, but I can't quite figure it out. I am making a web application that has a series of the same pages, based on what department and station you select. This is info that I am using later in a separate script to determine where to send a file. But right now I am using different views for each page. For example I have one view in my views.py that looks like this: views.py def FOO_station_0(request): Site_Data.station = 0 Site_Data.dept = "FOO" ctx = {} ctx['station'] = Site_Data.station if request.method == 'POST': form = my_form(request.POST) if form.is_valid(): try: Ext_Data.parsed_data = form.cleaned_data['full_scan'] saveScan() except IndexError: ctx['error_message'] = error_message return HttpResponseRedirect('/error/input') return HttpResponseRedirect(f'/confirm') else: form = my_form() ctx['form'] = form return render(request, f'scan/FOO/FOO_station.html', ctx) And another that looks like this: def BAR_station_2(request): Site_Data.station = 2 Site_Data.dept = "BAR" ctx = {} ctx['station'] = Site_Data.station if request.method == 'POST': form = my_form(request.POST) if form.is_valid(): try: Ext_Data.parsed_data = form.cleaned_data['full_scan'] saveScan() except IndexError: ctx['error_message'] = error_message return HttpResponseRedirect('/error/input') return HttpResponseRedirect(f'/confirm') else: form = my_form() ctx['form'] = form return render(request, f'scan/BAR/BAR_station.html', ctx) As you can see, they are both returning the same HTML file, this is because … -
How do II get object with the the largest value of a certain field in my Django model objects?
I'm am trying to create a view where the user will get the object with the largest value of a certain field in my Django model objects. This is my model: class LongTermCoinHistory(models.Model): coin = models.ForeignKey(Coin,on_delete=models.CASCADE) timestamp = models.BigIntegerField(default=0) price = models.FloatField() I want to get the object instance from my database that has the largest timestamp value. How do I go about doing this? -
How do I reference a model via User model in Django?
So I have two models -- UserInfo model, which references Django's built-in User model, and Article model, written by each user, as below. class UserInfo(models.Model): objects = models.Manager() this_user = models.OneToOneField(User, on_delete=models.CASCADE, related_name = 'userinfo', null=True, default=None) real_name = models.CharField(max_length=20, blank=False) class Article(models.Model): objects = models.Manager() author = models.ForeignKey(UserInfo, on_delete=models.CASCADE, related_name = 'article', null=True, default=None) body = models.CharField(max_length=20, blank=False) And here's part of my views.py. def create_ans_us(request): current_article = Article.objects.get(id=1) ... context = { 'current_article' : current_article, } return render(request, 'main/main.html', context) And in Django template tag, I'm trying to render the real_name field in UserInfo like below. <html> ... {{current_article.user_id.real_name}} </html> Now obviously, I want to render the real_name field to the template. How do I make this possible? Thanks in advance. :) -
ModuleNotFoundError: No module named 'expenseswebsite.userpreferences'
Good day dear Community! Got a following error at the PyCharm Terminal: File "C:\NewDjangoProjects\django-income-expense-website\expenseswebsite\expenses\views.py", line 9, in <module>from expenseswebsite.userpreferences.models import UserPreference ModuleNotFoundError: No module named 'expenseswebsite.userpreferences' here below my expenses\views.py file: from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .models import Category, Expense from django.contrib import messages from django.contrib.auth.models import User from django.core.paginator import Paginator import json from django.http import JsonResponse from expenseswebsite.userpreferences.models import UserPreference here below my UserPreference\models.py file: from django.db import models from django.contrib.auth.models import User class UserPreference(models.Model): user = models.OneToOneField(to=User, on_delete=models.CASCADE) currency = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return str(user)+'s preferences' Hierarchy: django-income-expense-website \ \__expenseswebsite \ \ \ \ \_authentication(migr, models, views etc..) \ \ \ \__expenses (migr, models, views etc..) \ \ \____expenseswebsite(migr, models, views etc..) \ \______templates \_________userpreferences(migr, models, views etc..) All migrations are migrated/applied successfully and there is no any red underlined text inside PyCharm Editor window, so what is wrong with that import? Thanks for any help in adavnce! -
How to change admin panel in django
I want change html, css, javascript of django admin panel because default admin panel is very ugly. How to change html, css and javascript of django admin panel. Is it possible? -
django filter in Subquery raise 'Expression contains mixed types. You must set output_field' error
I am using django orm Subquery. But when I add a specific filter parameter, FieldError: Expression contains mixed types. You must set output_field error was raised. Can I know what this error is and how to fix it? Below is the code where the error occurs, and the error occurs when is_active=True and eventcardad__isnull=False in lines 6 and 7 are added! and I'm using PostgreSQL RDBMS! personalized_event_ads_qs = CustomerPersonalization.objects.filter( customer__id__in=Customer.objects.filter(accept_marketing=True).filter(email='abc1@naver.com') ).annotate( element_ids=Subquery( Element.objects.fil is_active=True, eventcardad__isnull=False, campaign__in=campaign_qs, ).filter( majors__in=OuterRef('majors'), ).filter( Q(cities__in=OuterRef('cities')) | Q(districts__in=OuterRef('districts')) ).values( 'is_active' ).annotate( element_ids=ArrayAgg('eventcardad', distinct=True) ).values( 'element_ids' ) ) ).values( 'element_ids' ).annotate( customers=ArrayAgg('customer', distinct=True) ) -
How can I authenticate a Post Request with Token Authentication?
Right now I can successfully authenticate patch, get and delete so only the user that has access to the object can do it. But I have a simple problem: -How can I authenticate POST request? For example: User should be able to only create an ArticleImage linked to Article if both of their authors are the same, so User 2 cannot add an object to Article if User 1 is the owner. And also we want to make sure that User 2 can't do POST request in the name of User 1. Model.py class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') caption = models.CharField(max_length=250) class ArticleImage(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) image = models.FileField(upload_to='images',null=True,blank=True, validators=[validate_file_extension]) article = models.ForeignKey(Article, on_delete=models.CASCADE,null=True,blank=True, related_name='articleimages') author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articleimages') View.py class ArticleImageViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = ArticleImage.objects.all() serializer_class = ArticleImageSerializer filter_backends = [ArticleFilterBackend] Filter.py class ArticleFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): return queryset.filter(article__author=request.user) -
django run websocket client in background
So when I run the WebSocket client I can no longer reach the Django app like I can't connect to 127.0.0.1:8000, here is the WebSocket file: import websocket, json, pprint from datetime import datetime socket = "wss://stream.binance.com:9443/ws/manausdt@kline_1m" def on_message(ws, msg): message = json.loads(msg) messageData = message['k'] if messageData['x']: # get_data(messageData) timestamp = float(messageData['t']) symbol = messageData['s'] interval = messageData['i'] closeprice = float(messageData['c']) openprice = float(messageData['o']) highprice = float(messageData['h']) lowprice = float(messageData['l']) datetime_ob = datetime.fromtimestamp(timestamp / 1000) data = {'timestamp': timestamp, 'symbol': symbol, 'interval': interval, 'closeprice': closeprice, 'openprice': openprice, 'highprice': highprice, 'lowprice': lowprice, 'datetime_ob': datetime_ob} print(data) def on_open(ws): print('Connected!') def on_error(wsapp, err): print("Got a an error: ", err) def runwss(): stream = websocket.WebSocketApp(socket, on_error=on_error, on_open=on_open, on_message=on_message) stream.run_forever() runwss() And I inited it in apps file: from django.apps import AppConfig class ServiceGetDataConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'service_get_data' def ready(self): import service_get_data.wss And as I said I can't reach 127.0.0.1:8000 anymore so what shall I do in this case? -
django ContentFile vs InMemoryUploadedFile
i have this code that use to compress the image,itc work, i have read many comments but i am not sure which is safer and better, ContentFile or InMemoryUploadedFile, this is my code: def save(self, *args, **kwargs): img = Image.open(self.image) img = img.convert('RGB') output = BytesIO() img = img.resize((400x400)) img.save(output, format='JPEG', quality=90) output.seek(0) #content_file = ContentFile(output.read()) #file = File(content_file) self.image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.image.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) super(Image, self).save(*args, **kwargs) with InMemoryUploadedFile, if the size is greater than 2.5mb, the TemporaryFileUploadHandler will be used or the connection will drop