Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSRF verification failed behind Route 53
I have a dockerized Django app that utilizes Gunicorn and Nginx. When logging in on the admin page using localhost, no CSRF error emerges. When running the docker on Amazon EC2 with Route 53 as the proxy server (https redirects to http), I get the CSRF error on login. I note the following in my settings.py file (I added the SECURE_SSL_REDIRECT = False but it has had no effect): ALLOWED_HOSTS = ['localhost', '.website_name.ca'] SECURE_SSL_REDIRECT = False # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'The6ixDjango.apps.The6IxdjangoConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Given that I have Route 53 on the front-end, is it 'safe' to remove the csrf middleware reference in the MIDDLEWARE list? -
Django how to add many to many with bulk_create
this are my models: class MyShop(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile_shop') company_name = models.CharField(max_length=150) shop_commision = models.IntegerField(default=5) class OrderItem(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) shop = models.ForeignKey(MyShop, related_name='shop_order', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) size = models.CharField(max_length=5, null=True, blank=True, ) item_comission = models.IntegerField(default=5) class ShopInvoice(models.Model): shop = models.ForeignKey(MyShop, related_name='shop_invoice', on_delete=models.CASCADE) month = models.DateField() year = models.DateField() items = models.ManyToManyField(OrderItem, related_name='items') total = models.DecimalField(max_digits=10, decimal_places=2) this is my function:I use a cron job and this function to create an object for each user shop every month but items are not added to the object class Command(BaseCommand): help = 'Generate invoice monthly for shops' def handle(self, *args, **kwargs): month_inv = MyShop.objects.all() for invoice in month_inv: shop_invoice = invoice.shop_order.all().annotate(year=TruncYear('created'), month=TruncMonth('created')).values( 'month', 'year', 'shop_id' ).annotate(total=Sum(ExpressionWrapper( (F('item_comission') / 100.00) * (F('price') * F('quantity')), output_field=DecimalField())), ).order_by('month') ShopInvoice.objects.bulk_create([ ShopInvoice(**kv) for kv in shop_invoice if not ShopInvoice.objects.filter( shop_id=kv['shop_id'], month=kv['month'], year=kv['year'] ).values_list('shop_id', 'month', 'year').exists() ]) -
Django: Could not find the GDAL library (OSX)
After my old macbook died I am transferring across a Django Webapp I'd been building to my new machine. I am currently in the process of reinstalling the correct packages and extensions for the app. However I am currently getting the following error when I do python3 manage.py runserver: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal3.3.0", "gdal3.2.0", "gdal3.1.0", "gdal3.0.0", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. The database I created was through a server on Postgres.app which I believe comes packaged up with PostGIS, GDAL etc. I have tried following the geoDjango documentation and I added the following in the terminal: export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/14/bin When I run which psql it returns: /opt/homebrew/bin/psql Is this a conflict between a homebrew and Postgres.app installation or something? I can't figure it out. Full traceback of error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 115, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File … -
Instantiating dependencies (e.g. service clients) in Django
A Django API view calls another service. To call that service, the view needs a client. I'd like to initialize globally an instance of the client and pass that instance to the view. Also, for tests, I'd like to be able to easily mock the client. I can do some terrible hacks (hey, with Python everything is possible!) but I'd like to do it in Django-idiomatic way. I tried as_view(**initkwargs) and passing the instance of the client. The drawback is that in tests I need to modify class variable (and not instance variable, which seems more correct), and also I need to instantiate the client in urls.py which doesn't look like a right place to instantiate such clients (dependencies). I considered having a separate Application in INSTALLED_APPS, but it seems like an overuse of what an Application should do. In my case, the App would only run AppConfig.ready() and would initialize the client for later access by a view. A simple Dependency Injection would do, but I don't want to overcomplicate that, if Django supports equivalent functionality. Where should I initialize such dependencies in Django, and how to later mock them in tests? -
Why reply to the comment is not displaying? Python Django
Everything else seems to work but cannot see the reply to the comment. Please help MODELS: class Comment(models.Model): """ comments for Post model """ comment_post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comment_for_post', null=True, default='') comment_text = models.TextField(null=True) date_posted = models.DateTimeField(auto_now=True) def get_absolute_url(self): """ Reverse the Comment to the url once action has been taken with primary key to direct back to details page """ return reverse('posts:post_details', kwargs={'pk': self.pk}) def __str__(self): return self.comment_text class Reply(models.Model): """ add reply to commnets """ reply_comment = models.ForeignKey( Comment, on_delete=models.CASCADE, null=True, default='', related_name='comment_reply') reply_text = models.TextField() date_posted = models.DateTimeField(auto_now=True) def __str__(self): return self.reply_text VIEWS: @login_required def reply_to_comment(request, pk): comment = get_object_or_404(models.Comment, pk=pk) if request.method == 'POST': form = forms.ReplyCommentForm(request.POST) if form.is_valid(): reply = form.save(commit=False) reply.reply_comment = comment reply.save() return redirect('posts:post_details', pk=comment.pk) else: form = forms.ReplyCommentForm() return render(request, 'posts/reply_comment_form.html', context={'form': form}) URLS: urlpatterns = [ path('post_list/', views.PostListView.as_view(), name='post_list'), path('user/str:username/', views.UserPostListView.as_view(), name='user_posts'), path('create/', views.PostCreateView.as_view(), name='create'), path('details/int:pk/', views.PostDetailView.as_view(), name='post_details'), path('delete/int:pk/', views.PostDeleteView.as_view(), name='post_delete'), path('update/int:pk/', views.PostUpdateView.as_view(), name='post_update'), path('str:category/', views.CategoryPostListView.as_view(), name='category_posts'), path('posts/int:pk/comment', views.add_comment_to_post, name='post_comment_list'), path('delete_comment/int:pk/', views.CommentDeleteView.as_view(), name='delete_comment'), path('comment/int:pk/reply/', views.reply_to_comment, name='reply'), TEMPLATE: <div class='container'> {% for reply in comment.comment_reply.all %} <br> {% if object.author == user %} <div class=""> <ul> <li> <p >{{reply.reply_text}}</p> <p class='text-capitalize'>From {{user.username}} on {{comment.date_posted|date:'d-M-y'}}.</p> </li> </ul> </div> {%else %} <div class=""> … -
SystemCheckError: System check identified some issues: Django
from mptt.models import MPTTModel, TreeForeignKey from django.contrib.auth.models import User from django.db import models class CategoryTask(MPTTModel): """Модель категорий заданий""" title = models.CharField("Название", max_length=200, unique=True) parent = TreeForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True, related_name='children' ) slug = models.SlugField(max_length=200, unique=True) mastery_need = models.FloatField("Требуется мастерства", default=0) points_need = models.FloatField("Требуется балов", default=0) def __str__(self): return self.title class MPTTMeta: order_insertion_by = ['title'] class Meta: verbose_name = "Категория задания" verbose_name_plural = "Категории заданий" class DCTask(models.Model): category = models.ForeignKey(CategoryTask, verbose_name="Категория", on_delete=models.CASCADE) mastery_need = models.FloatField("Требуется мастерства", default=0) points_need = models.FloatField("Требуется балов", default=0) mastery = models.FloatField("Получит мастерства", default=0) points = models.FloatField("Получит балов", default=0) title = models.CharField("Название", max_length=200) description = models.TextField("Описание") slug = models.SlugField(max_length=200, unique=True) users = models.ManyToManyField(User, verbose_name="Взявшие", blank=True) def __str__(self): return self.title class Meta: verbose_name = "Задание" verbose_name_plural = "Задания" class AnswerDCTask(models.Model): user = models.ForeignKey(User, verbose_name="Пользователь", on_delete=models.CASCADE) task = models.ForeignKey(DCTask, verbose_name="Задание", on_delete=models.CASCADE) answer = models.TextField("Ответ") result = models.BooleanField("Сдано?", default=False) check = models.BooleanField("На проверке", default=False) verifiers_y = models.ManyToManyField( User, verbose_name="Проверяюще за", related_name="users_check_y", blank=True ) verifiers_n = models.ManyToManyField( User, verbose_name="Проверяюще против", related_name="users_check_n", blank=True ) count_check = models.IntegerField("Общее за", default=0) mentor = models.ForeignKey( User, verbose_name="Ментор", on_delete=models.CASCADE, blank=True, null=True, related_name="user_mentor" ) created = models.DateTimeField("Взято", auto_now_add=True) over = models.DateTimeField("Сдано", blank=True, null=True) def __str__(self): return "{} - {}".format(self.user, self.task) class Meta: verbose_name = "Взятое задание" verbose_name_plural … -
django - i want to redirect to the profile page after a user edits thier profile
when a user finish updating thier profile i want to redirect them back to the profile page but it keeps showing that Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['(?P<username>[^/]+)/$'] i have tried making my views redirect but it now. views.py def profile_update(request): Profile.objects.get_or_create(user=request.user) if request.method == "POST": u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Acount Updated Successfully!') return redirect('profile') else: u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, } return render(request, 'userauths/profile_update.html', context) urls.py main project dir from userauths.views import UserProfile urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('userauths.urls')), path('<username>/', UserProfile, name='profile'), ] -
django makemigrations nomodule found error
I am trying to add models, but whenever I run python manage.py makemigrations I get the following error ModuleNotFoundError: No module named 'django.contrib.staticfilesaccounts' accounts is an app in my project, the structure of the files is as follows file structure The models file is, from django.db import models # Create your models here. class Customer(models.Model): name=models.CharField(max_length=200, null=True) phone=models.CharField(max_length=10, null=True) email=models.EmailField(max_length=20, null=True) dateCreated=models.DateField(auto_now_add=True) def __str__(self): return self.name class Product(models.Model): name=models.CharField(max_length=30, null=True) category=models.CharField(max_length=20, null=True) price=models.IntegerField(null=True) def __str__(self): return self.name Im a Django beginner, could use some help. Much Thanks -
Django form-wizard form save
I would like to save the form and log in in a session wizard I used to do it using requests how would I use it like so>? Within the done function. class UserWizard(SessionWizardView): template_name = "registration/signup.html" form_list = [SignUpForm] def done(self, form_list, **kwargs): process_data(form_list) return redirect('home') """ def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'registration/signup.html', {'form': form}) """ -
Why i get Post.CommentPost.None
Can anyone explain me, why i get Post.CommentPost.None? I have connected CommentPost with Post, and when i try get something from my CommentPost i have Post.CommentPost.None Here something about my models and functions. class Posty(models.Model): title = models.CharField(max_length=250, blank=False, null=False, unique=True) sub_title = models.SlugField(max_length=250, blank=False, null=False, unique=True) content = models.TextField(max_length=250, blank=False, null=False) image = models.ImageField(default="avatar.png",upload_to="images", validators=[FileExtensionValidator(['png','jpg','jpeg'])]) author = models.ForeignKey(Profil, on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True) published = models.DateTimeField(auto_now_add=True) T_or_F = models.BooleanField(default=False) likes = models.ManyToManyField(Profil, related_name='liked') unlikes = models.ManyToManyField(Profil, related_name='unlikes') created_tags = models.ForeignKey('Tags', blank=True, null=True, related_name='tagi', on_delete=models.CASCADE) test_wyswietlenia = models.IntegerField(default=0, null=True, blank=True) class CommentPost(models.Model): user = models.ForeignKey(Profil, on_delete=models.CASCADE) post = models.ForeignKey(Posty, on_delete=models.CASCADE, related_name="comments") content1 = models.TextField(max_length=250, blank=False, null=False) date_posted = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) VIEWS tag = request.GET.get('tag') if tag == None: my_tag = Posty.objects.prefetch_related('comments') my_view = Posty.objects.prefetch_related('my_wyswietlenia') else: my_tag = Posty.objects.filter(created_tags__tag=tag) my_view = Posty.objects.prefetch_related('my_wyswietlenia') TEMPLATES {% for post in my_tag %} {% if post.comments.last.user == None %} <span class="forum_tag_author">Komentarz » <a href="{% url 'home:detail_post' post.pk %}">Brak komentarza</a></span><br/> <span class="forum_tag_author">Stworzony przez » <a href="{% url 'profile:profil_uzytkownika' post.pk %}">{{post.author}} </a> </span><hr/> {% else %} <span class="forum_tag_author">Komentarz » <a href="{% url 'home:detail_post' post.pk %}">{{post.comments.last.content1}}</a></span><br/> <span class="forum_tag_author">Odpowiadający » <a href="{% url 'profile:profil_uzytkownika' post.pk %}">Dodany przez: {{post.comments.last.user}} </a> </span><hr/> {% endif %} {% endfor %} And this … -
django two column foreign key reference to one column
I have this problem, I have two columns foreigner key and reference one columns, which works in mysql, but it did not work in Django models. it showed there are two same db_columns in one models and it is not allowed, how to fix it. I will appreciate it here is the code. how to avoid to use one db_column twice? -
Django prev step
Whenever I run the prev step in my wizard it always needs to check all the values in the verify form how would I just go back without checking. {% if wizard.steps.prev %} <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button> {% endif %} views.py from django.core.files.storage import FileSystemStorage import os from django.conf import settings class DoctorWizard(SessionWizardView): file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'doctor')) template_name = "registration/signup.html" form_list = [SignUpForm,verify] def done(self, form_list, **kwargs): process_data(form_list) return redirect('home') forms.py class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = Profile fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) class verify(forms.Form): verified = forms.ImageField(required=True) class Meta: model = Profile fields = ('verified',) -
Django (REST Framework) - How to add fields to queryset iteration
I need some advice for making a query in Django (DRF). I'm trying to make a queryset for Products, where every Product gets a field "images" with all the Images for that product (coupled using ProductImage model), but I can't figure out how to add the field. Below is my ProductViewSet class ProductViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer queryset = Product.objects.all() def get_queryset(self): queryset = Product.objects.all() product_list = [] # iterate over all products for product in queryset: # find Image ids for product image_ids = list(ProductImage.objects.filter(product=product.id).values_list('image', flat=True)) images = [] # iterate over images and add to images list for image_id in image_ids: image = list(File.objects.filter(id=image_id).all()) images.append(image) # add images field to product # product['images'] = images # "TypeError: 'Product' object does not support item assignment" product.images = images # Doesn't do anything. # add product to product list product_list.append(product) return product_list I've tried to do the following to add the field "images": product['images'] = images which gives the error "TypeError: 'Product' object does not support item assignment" product.images = images which doesn't do anything... Could anyone point me in the right direction? Any tips on how to make this query in a better way are also welcome! -
Closing django ORM connections in a multi-threaded environment
I have below code in standalone script which is using django orm (outside django) with multithreading. import threading MAX_THREADS = 30 semaphore = threading.Semaphore(value=MAX_THREADS) books = Books.objects.all() for book in books: book_id = book.id t = threading.Thread(target=process_book, args=[book_id]) t.start() threads.append(t) for t in threads: t.join() def process_book(book_id): semaphore.acquire() book = Books.objects.get(id=book_id) # Do some time taking stuff here book.save() semaphore.release() Once the number of threads reaches MAX_CLIENT_CONN setting of postgres (which is 100 by default), I start getting following error with further calls: operationalError at FATAL: remaining connection slots are reserved for non-replication superuser connections Researching this I got to solutions of using a database pooler like pgbouncer, However that only stalls the new connections until connections are available but again after django's query wat timeout I hit OperationalError at / query_wait_timeout server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. I understand that this is happening because the threads are not closing the db connections they are making but I am not sure how to even close the orm call connections? Is there something I could be doing differently in above code flow to reduce the number of connections? I … -
How to create an object upon confirmation of deletion in DeleteView in Django
In Django 3, I want to delete an object and upon the user confirming the deletion, create an unrelated object. The code I wrote below creates the unrelated object as soon as the user clicks "delete", but before the user has confirmed the deletion. I want the unrelated object to be created upon confirmation of deletion. class PromoteQuestionToMeta(DeleteView): model = QuestionList fields = [] template_name = 'search/questionlist_confirm_delete.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) questionlist_object = self.object MetaQuestionList.objects.create(question=questionlist_object.question, created_by=questionlist_object.created_by) return context def get_success_url(self): return reverse_lazy('home:home') -
Can't import views.py into urls.py
Just started working with Django. I created an app, mapped it on INSTALLED_APPS list and wrote a simple function in views.py. I tried to import views in urls.py but I'am getting an error: Cannot find reference 'views' in 'init.py' views.py code: from django.shortcuts import render def home_page(request, *args, **kwargs): return render(request, 'home.html') urls.py code from django.contrib import admin from django.urls import path from homepage import views #<---GETTING AN ERROR RIGHT HERE urlpatterns = [ path('admin/', admin.site.urls), ] -
Django about Form, form-group, and etc
1) I want to put the ID of the logged-in user in 'wrtier', what should I do? 2) b_note How can we extend rows in b_note? I've been looking at this and that for almost four hours, and I've only reached my current state, but I think I'm still lacking a lot. Help this pathetic beginner. forms.py class BoardForm(forms.ModelForm): b_title = forms.CharField(max_length=30, label="title", error_messages={ 'required': "Enter the title." }) b_writer = forms.CharField(max_length=10, label="writer", error_messages={ 'required': "Enter the writer." }) b_note = forms.CharField(max_length=None, widget=forms.Textarea, label="note", error_messages={ 'required': "Enter the note." }) def clean(self): clean_data = super().clean() b_title = clean_data.get('b_title') b_writer = clean_data.get('b_writer') b_note = clean_data.get('b_note') class Meta: model = Board fields = ['b_title', 'b_writer', 'b_note'] views.py def board_write(request): form = BoardForm() return render(request, 'board_write.html', { 'form':form }) @require_http_methods(["POST"]) def board_insert(request): if request.method == "POST": form = BoardForm(request.POST) if form.is_valid(): form.save() return redirect('/board') else: form = BoardForm() return render(request, 'board_write.html', {'form':form}) board_write.html <form method="POST" action="/board_insert" id="frmBoard"> {% csrf_token %} {% for field in form %} {% if user.is_authenticated %} ## I don't know from down here. ### <div class="form-group"> <input type="{{field.field.widget.input_type}}" class="form-control" id="{{field.id_for_label}}" placeholder="{{field.label}}" name="{{field.name}}"> </div> {% else %} <div class="form-group"> ????????????????????? </div> {% endif %} {% if field.errors %} <span style="color: … -
Page contents going down for a second (CSS)
My Morse Code translation app is working just fine, except that when I translate text to morse (Texto para Morse) for the first time, the styles glitch and go down for a second. There are some audio and blinking sync issues as well, but for now, I just wanna figure out what is causing that. All my code in is this repository. The only files that matter are "script.js" (does the morse blinking), "layout.html" (a not so organized yet layout), and "texto_para_morse.html" the page that is rendered in the Texto para Morse mode. Image of the page contents going to the bottom -
How to serve MEDIA uploads from summernote in prod hosting?
Good afternoon and Happy New Year! In the admin panel, when creating a post, the uploaded images are not displayed. Neither in the admin area nor in the published post. They are in the folder with the downloaded images, and through the Django admin panel, a link is visible (but it does not open, "Not Found The requested resource was not found on this server") and they are uploaded to the hosting (they appear in the django-summernote folder by dates). Tell me how to fix the situation? The statics loaded normally, everything is displayed OK. The only problem is with those files that the user uploads when the post is compiled. .htaccess at the slightest change from the standard one provided by the hoster - the site stops opening. From this and the working statics, I assume that Apache is configured normally, especially since the hoster's infrastructure does not contain a mention or a requirement to change it. Thanks! The settings.py settings are below: STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' X_FRAME_OPTIONS = 'SAMEORIGIN' SUMMERNOTE_THEME = 'bs4' MEDIA_ROOT = os.path.join(BASE_DIR, 'blog/media/') MEDIA_URL = '/media/' models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() … -
Django Admin - How to test @mark_safe condition
I'm trying to implement some code for example: @mark_safe def workers(self): workers_info = [] for name, role in self.workers: workers_info.append( f"<br> Name: {name}" f"<br> role: {role}" ) return '<br><br>'.join(workers_info) return '-' The problem is that my project runs together with sonarCloud and it is saying that I need to cover this part of the code with tests. How can I implement a test without needing to do something like: assert workers == a_giant_block_of_html -
DRF - Nested Serializer Writing Data
This is the model class Memo(BaseModel): memo_text = models.TextField(null=True, blank=True) tag = models.ForeignKey('Tag', on_delete=models.SET_NULL, null=True, blank=True) is_tag_new = models.BooleanField(default=False) class Meta: db_table = 'memo' class Link(BaseModel): url = models.URLField(blank=True, null=True) memo = models.ForeignKey('Memo', on_delete=models.CASCADE, related_name='url') class Meta: db_table = 'link' I have a serializer with nested serializer fields like this class LinkSerializer(serializers.ModelSerializer): class Meta: model = Link fields = ['url'] class MemoSerializer(serializers.ModelSerializer): images = serializers.SerializerMethodField() urls = LinkSerializer(many=True, read_only=True) memo_mark = BookmarkSerializer(read_only=True) tag_name = serializers.SerializerMethodField() tag_color = serializers.SerializerMethodField() def get_images(self, obj): image = obj.image_set.all() return ImageSerializer(instance=image, many=True, context=self.context).data class Meta: model = Memo fields = ['id', 'memo_text', 'is_tag_new', 'memo_mark', 'images', 'urls', 'tag_name', 'tag_color', 'tag', 'created_at', 'updated_at'] def create(self, validated_data): instance = Memo.objects.create(**validated_data) urls_data = validated_data.pop('urls') images_data = self.context['request'].FILES if images_data is not None: for images_data in images_data.getlist('image'): Image.objects.create(memo=instance, image=images_data) if urls_data is not None: for urls_data in urls_data: Link.objects.create(memo=instance, **urls_data) return instance my first problem is that urls is not showing up instead, it shows up like this { "id": 39, "memo_text": null, "is_tag_new": false, "images": [], "tag_name": "URL", "tag_color": "BL", "tag": 4, "created_at": "2022-01-04T04:17:56.221539", "updated_at": "2022-01-04T04:17:56.221539" } the second problem is writing datas to this nested serializer. uploading multiple image works fine, however saving multiple url isn't working. This … -
Transfering local files to docker container - docker COPY not updating with new files in directory
I'm hosting my media-files from the same server as I host my Django application in. From time to time I need to add some more files for being served from the application, such as images. I have set up so NGINX serves all my media files in a directory called /mediafiles inside my docker container, this is the same place where all images that a user upload will be located. What I want to do is to add some files into my repo, and copy these files over to /mediafiles in the container, and be able to reach them trough the application (when run locally) or NGINX (when run in my server). However, I'm running into some problems. I've tried with the following line in my Dockerfile: COPY ./reponame/mediafiles $APP_HOME/mediafiles Which works, but ONLY after I've run: docker system prune --volumes Which isn't something I can do on the server, because this is where all the users uploaded images will be located. I know that this isn't the optimal set-up as you should use an external file storage for user-media, but this is what I can spend on my project at this time and haven't found a good storage solution … -
How to access attributes of 'child' model in Django?
models.py class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, name="post_id") postauthor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='postuser') class PostImage(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, default=None,) image = models.ImageField(upload_to=user_directory_path) Before I write too much and describe everything I have tried so far, what would be the best way of showing all images for every post in a single view? Let's say I would use the images as thumbnails for the posts. Thank you. -
How to sum time based on a given time in django?
class Clock(models.Model): report_submitted_at = models.TimeField() delivery_time = models.TimeField(null=True, Blank=True) I am new to Django so I am curious how to achieve this. In my model report_submitted_at time I am entering. Based on the entered time i want to save the delivery time automatically. Delivery time is always '04:00:00'. So suppose i entered report_submitted_time '02:00:00'. The delivery time will be '06:00:00' for that row. I imported datetime. Manually i am able to add two times. But here how can i save the delivery time automatically. Any help would be really appreciated. Thank you !! -
Django how to prevent to show success messages if I go back to previous page without submitting forms?
Suppose if I go back to previous page without submitting forms or without doing any action then if I reload the page then I am seeing the success messages rendering on my html template. Why it's rendering because I didn't perform any actions? how to prevent to showing successes message if just go back to previous page without doing any actions? here is my code: views.py class EditPatient(UpdateView): model = Patient form_class = PatientUpdateFrom template_name = 'hospital/edit-patient.html' def form_valid(self, form): if form.is_valid(): messages.add_message(self.request, messages.INFO, 'Patient Sucessfully Updated') find_age = form.cleaned_data['date_of_birth'] find_age = age(find_age) form.instance.age = find_age form.save() return redirect('hospital:patient-details',self.object.slug) else: messages.add_message(self.request, messages.INFO, 'Somethings Wrong. Please try again') #htm page where I am doing actions: <form method="POST"> {% csrf_token %} {{form}} <button type="submit">Submit</button> </from> **#html redirect page ** {% if messages %} <div class="alert alert-danger" role="alert"> <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> </div> {% endif %}