Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
browser is adding strong tag before and after the div tag automatic
I have a website sauravportfolio.pythonanywhere.com . It was running good earliar. But after some time a strong tag is adding before and after the div tag. before error it was looking like this after error it is looking like this The error is here which is marked by a red circle i can't able to find why this strong tag is here while this is not present in my code. Please help me to find this error. Why this is happening so. And how can i overcome on this situation. -
Why does INSTALLED_APPS in Django settings stops seeing directories if you rename settings.py file?
I work in Pycharm 2019.3.3. So if the settings.py file wasn't renamed, when you start typing a name of a directory inside INSTALLED_APPS, Pycharm indexes what you can choose from. But if you rename the file to something else (common.py eg), it doesn't. But the whole thing works and an app gets included anyway. How can I make it index properly? Same thing happens if you put the settings.py file inside a project/project/settings/ directory (instead of the default project/project). What actions should be taken to make it work as intended? -
Issue on Entity Relation
I need a helping hand in the area of Entity Relation. In this particular project, a student in a class (i.e J.S.S 1) should be able to attend examination for J.S.S 1 in a particular term and academic session. Note: In my country we have "Academic session, in academic session we have terms, in a term we have 1st, 2nd and 3rd term. Student should be a able to select field for class, subject ,academic session & term and print result for each term and session. Here is the admin model: from django.db import models from django.conf import settings class Course(models.Model): course=models.CharField(max_length=150,unique=True) def __str__(self): return self.course class Paper(models.Model): paper=models.CharField(max_length=150) def __str__(self): return self.paper class Questions(models.Model): qs_no=models.IntegerField() course=models.ForeignKey(Course,on_delete=models.CASCADE) paper=models.ForeignKey(Paper,on_delete=models.CASCADE) questions=models.TextField() answers=models.CharField(max_length=20) option_a=models.TextField() option_b=models.TextField() option_c=models.TextField() option_d=models.TextField() def __str__(self): return str(self.qs_no)+self.questions class Answer(models.Model): student=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) question=models.ForeignKey(Questions,on_delete=models.CASCADE) answer=models.CharField(max_length=20) date=models.DateTimeField(auto_now_add=True) def __str__(self): return self.answer Here is the account model: from django.db import models from admin_dash.models import Course from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser) class UserManager(BaseUserManager): def create_user(self, phone, roll, course, password, name=None): if isinstance(course, int): course = Course.objects.get(pk=course) user = self.model(phone=phone, roll=roll, course=course, name=name) user.set_password(password) user.save() return user def create_superuser(self, phone, roll, course, password, name=None): user = self.create_user(phone=phone, roll=roll, course=course, password=password, name=name) user.is_staff = True user.is_admin = … -
Django models inheritance
I want to create base model for my submodels, for example: Car(Base) and Truck, Sportcart etc. And I want to bind them all using base class with another class, cuz I don't want to bind all of them separately with another class. Example: I have a user and I want to add to him cars (I will do it separately for each class, yes). And I want to get all of them using my base Car class. -
After installing Django with poetry it says "No module named django" in active venv
I'm playing with poetry because I'm thinking about switching from pip. Following the basic usage examples, I'm doing the following: $ poetry new poetry-demo $ cd poetry-demo $ poetry add django $ django-admin #can't find it $ poetry shell #or poetry $(poetry env info --path)/bin/activate $ django-admin Traceback (most recent call last): File "/Users/cjones/Library/Caches/pypoetry/virtualenvs/poetry-demo-Jq168aNm-py3.8/bin/django-admin", line 5, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' Also tried in this order: $ poetry new poetry-demo $ cd poetry-demo $ poetry shell #or poetry $(poetry env info --path)/bin/activate $ poetry add django $ django-admin Traceback (most recent call last): File "/Users/cjones/Library/Caches/pypoetry/virtualenvs/poetry-demo-Jq168aNm-py3.8/bin/django-admin", line 5, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' Check the pyproject.toml: [tool.poetry] name = "poetry-demo" version = "0.1.0" description = "" authors = ["Your Name <you@example.com>"] [tool.poetry.dependencies] python = "^3.8" Django = "^3.2.6" [tool.poetry.dev-dependencies] pytest = "^5.2" [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api" Check poetry show: asgiref 3.4.1 ASGI specs, helper code, and adapters attrs 21.2.0 Classes Without Boilerplate django 3.2.6 A high-level Python Web framework that encourages rapid development and clean, pragmatic design. more-itertools 8.8.0 More routines for operating on iterables, beyond itertools packaging 21.0 Core utilities for Python packages pluggy 0.13.1 … -
Django rest with formset
Right now I have a working formset page, create one record in ModelA and 3 records for ModelB using foreignkey. Now I would like to create restApi for that, for now I have linked one model to another but my question is how to make ModelB add a few times for this model. serializers.py class DailyMontageCreateSerializer(serializers.ModelSerializer): class MonterDailyTempSerializer(serializers.ModelSerializer): class Meta: model = models.MonterDaily exclude = ['daily_montage', 'created', 'updated'] validators = [ UniqueTogetherValidator( queryset=models.MonterDaily.objects.all(), fields=['name', 'date'] ) ] daily_montage = MonterDailyTempSerializer() class Meta: model = models.DailyMontage exclude = ['created', 'updated'] validators = [ UniqueTogetherValidator( queryset=models.DailyMontage.objects.all(), fields=['team', 'date'] ) ] def create(self, validated_data): model_b_data = validated_data.pop('daily_montage') model_a_instance = models.DailyMontage.objects.create(**validated_data) models.MonterDaily.objects.create(daily_montage=model_a_instance, **model_b_data) return model_a_instance views.py class DailyMontageCreateAPIView(generics.CreateAPIView): queryset = models.MonterDaily.objects.all() serializer_class = serializers.DailyMontageCreateSerializer now if i will add like that is good { "daily_montage": { "status": null, "name": 1 }, "type": null, "date": null, "user": 1, } but i want to be like that { "daily_montage": { "status": null, "name": 1 }, "daily_montage": { "status": null, "name": 2 }, "daily_montage": { "status": null, "name": 3 }, "type": null, "date": null, "user": 1, } -
Return Specific User in Django
Still pretty new with Django and trying to work out how to display current user's profile when clicking 'view profile' through the nav-bar and the specific user when clicking 'view profile' on someone else's project page. Currently, when clicking on the nav-bar, it correctly returns the current user's profile, however, when clicking to see someone else's page on the project detail page, it still returns current user and not the desired user's profile page. I still want the url to show up like so: 'accounts/username/view_profile' and not 'accounts/pk/view_profile' I've tried to the 'get_context_data' method in my ViewProfileView but it returns an error about calling the url with slugs or object pk. models.py I think I have the slug properly set up but I'm not sure how to implement it or if that will even solve my problem here - I've tried adding the slug to the url-conf and passing it through the get_context_data in views.py but I could never get it to work properly, just error after error. ... class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) slug = models.SlugField(blank=True, db_index=True, unique=True) about = models.TextField(max_length=500, null=True, blank=True) profile_pic = models.ImageField(null=True, blank=True, upload_to="images/profile") facebook_url = models.CharField(max_length=255, null=True, blank=True) twitter_url = models.CharField(max_length=255, null=True, … -
An error occurred (403) when calling the HeadBucket operation: Forbidden
After a refactoring on an AdminModel class this error is happening in some instances. -
Django: how to filter queryset by the combination of related objects fields?
I have three related models that look like this: class Library(models.Model): name = models.CharField(max_length=200, blank=False) class Meta: verbose_name = 'library' verbose_name_plural = 'libraries' class Section(models.Model): name = models.CharField(max_length=200, blank=False) library = models.ForeignField(Library, related_name='sections', on_delete=models.CASCADE, null=False) class Meta: verbose_name = 'section' verbose_name_plural = 'sections' class Book(models.Model): title = models.CharField(max_length=200, blank=False) section = models.ForeignField(Section, related_name='books', on_delete=models.CASCADE, null=False) is_available = models.BooleanField(default=True) class Meta: verbose_name = 'book' verbose_name_plural = 'books' And say I need to filter all the libraries that have available books with title "The Lord of the Rings". If I create a request like this queryset = Library.objects.filter(sections__books__title="The Lord of the Rings", sections__books__is_available=True).distinct() it will include libraries that have my book and it's not available, because the filter condition doesn't apply to the same book. How do I specify that I need both filters to combine for related objects? -
Direct assignment to the forward side of a many-to-many set is prohibited. Using set makes another error
I am trying to make cart at my e-commerce page, full in django. But I have a problem. Code below after post request occurs an error - Direct assignment to the forward side of a many-to-many set is prohibited. Use order_items.set() instead.When i use set() then i get error object is not iterable. What should I do? def post(self, request, pk): if 'buy' in request.POST: item = get_object_or_404(Item, id=pk) orderItem, created = OrderItem.objects.get_or_create(order_item=item) order, created = Order.objects.get_or_create(order_user=request.user, order_items=orderItem) order.save() HttpResponse('Items added to the database') 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) -
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.