Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Disconnect all recivers of particular sender and signal than reconnect them in django
Is there any way I disconnect all receiver of a model in specific signal (like post_save) than reconnect them? # some thing like this all_receiver = collect_receivers(signal=post_save, sender=MyModelClass) post_save.disconnect(all_receiver, sender=MyModelClass) # do some work post_save.connect(all_receiver, sender=MyModelClass) seems post_save.disconnect(sender=MyModelClass) just work fine with disconnecting signals but Django documentation is not clear about what will happened if I pass just sender. and I baffled about how can I reconnect, disconnected receiver? Note that because my app is 3rd-party I don't have access to receivers but, for one of my features I have to mute all receiver connected to my model in post_save than reconnect them. -
How to fetch list of dictionary json data and show it on html page as table data
I have two columns data.One is "GLI Code" column and another is "Country" column. I need to set the “GLI Code” data in “GLI Code” column. “Country” data in “Country” column. here is my data in list of dictionary format. views file: def tables_data(request): dbfs_source_file_path = 'dbfs:/mnt/adls/MPF/Alternate_Currency_Keys_Aug.csv' local_file_download_path = './mpf_dataset.csv' dbfs_api = DbfsApi(api_client) dbfs_path = DbfsPath(dbfs_source_file_path) dbfs_api.get_file(dbfs_path, local_file_download_path, overwrite = True) df = pd.read_csv(local_file_download_path).head(5) json_records = df.reset_index().to_json(orient ='records') data = [] data = json.loads(json_records) return render(request, "home/tables-data.html", {'data':data}) data ouput: [{'index': 0, 'GLI Code': '15013256_U', 'Country': 'Indonesia', }, {'index': 1, 'GLI Code': '20061265_U', 'Country': 'Philippines'}, {'index': 2, 'GLI Code': '20063869_U', 'Country': 'Indonesia'}] html file: <thead> <tr> {% for i in data %} <th>{{i}}</th> {% endfor %} </tr> </thead> <tbody> <tr> {% for g in data.GLICode %} <td>{{g}}</td> {% endfor %} </tr> <tr> {% for c in data.Country %} <td>{{c}}</td> {% endfor %} </tr> </tbody> Above html code not giving me the expected output like below screenshot data. I want to set the data as below screenshot format. -
How to restore deleted table from django migrations?
I've deleted both table and 0001_initial.py migration file from a model. I didn`t think I will need this model anymore, but now I do need it. The problem is that python manage.py makemigrations doesn't create a table with the name of deleted table and therefore my migrations are only displayed in migrations files. But they don`t affect database. How can I create or restore that table again or should I delete the whole database and restore everything afterwards? Thanks in advance! -
self.scope['user'] always returns AnonymousUser in websocket
I have researched similar questions but can't find an answer that works for me. I would like to get the username or user_id from a session when a user connects to a websocket. This is what I have in consumers.py: import json from channels.consumer import AsyncConsumer from time import sleep import random import redis from django.conf import settings from django.contrib.auth.models import User, AnonymousUser from channels.db import database_sync_to_async from asgiref.sync import async_to_sync from rest_framework.authtoken.models import Token from channels.middleware import BaseMiddleware redis_instance = redis.StrictRedis(host=settings.REDIS_HOST_LAYER, port=settings.REDIS_PORT_LAYER, db=0 ) class PracticeConsumer(AsyncConsumer): async def websocket_connect(self, event): print('session data', self.scope['user']) await self.send({"type": "websocket.accept", }) ... @database_sync_to_async def get_user(self, user_id): try: return User.objects.get(username=user_id).pk except User.DoesNotExist: return AnonymousUser() This is my asgi.py: """ ASGI config for restapi project. It exposes the ASGI callable as a module-level variable named application. For more information on this file, see https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'signup.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter(websocket_urlpatterns) ) ) }) and the user login function + token sent when user logs in: class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): authenticate_kwargs = { self.username_field: attrs[self.username_field], "password": attrs["password"], } try: authenticate_kwargs["request"] = self.context["request"] except KeyError: pass user = authenticate(**authenticate_kwargs) if not user: return { 'user': 'Username or password is incorrect', } … -
Why are the items not appearing in the table?
I'm creating a point of sale using Django, a part arrived here that the items are not showing up, since I already registered them... Could someone help me? A note: I'm Brazilian, my code is in the language, but I think there will be no problems. Here's the codes: This is the models part, which is inside the 'registration' app. I want this information to appear in another app called 'pages' inside, of course, the folder called 'templates'.. from django.db import models class ListaProdutos(models.Model): nome_produto = models.CharField(max_length=50, verbose_name='Produto') quantidade_produto = models.IntegerField(verbose_name='Qntd.') custo_venda = models.CharField(max_length=10, verbose_name='Custo/Venda') fornecedor = models.CharField(max_length=50, verbose_name='Fornecedor') data_adicao = models.DateTimeField(verbose_name='Data de Adição') def __str__(self): return "{} {} {} {} {}".format(self.nome_produto, self.quantidade_produto, self.custo_venda, self.fornecedor, self.data_adicao) class ListaDespesas(models.Model): nome_despesa = models.CharField(max_length=50, verbose_name='Despesas') quantidade_despesa = models.CharField(max_length=50, verbose_name='Qntd.') custo = models.IntegerField(verbose_name='Custo') tipo_gasto = models.CharField(max_length=50, verbose_name='Tipo de Gasto') data_atualizacao = models.DateTimeField(verbose_name='Data de Atualização') def __str__(self): return "{} {} {} {} {}".format(self.nome_despesa, self.quantidade_despesa, self.custo, self.tipo_gasto, self.data_atualizacao) Still in the 'registration' app, only in the urls part: from django.urls import path from .views import ProdutoCreate, DespesaCreate from .views import ProdutoUpdate, DespesaUpdate from .views import ProdutoDelete, DespesaDelete from .views import ProdutoList, DespesaList urlpatterns = [ path('cadastrar/produto', ProdutoCreate.as_view(), name='cadastrar-produto'), path('cadastrar/despesas', DespesaCreate.as_view(), name='cadastrar-despesa'), path('editar/produto/<int:pk>/', ProdutoUpdate.as_view(),name='editar-produto'), path('editar/despesa/<int:pk>', DespesaUpdate.as_view(),name='editar-despesa'), path('excluir/produto/<int:pk>/', … -
Django Rest Framework Field Validation Issue
My subscription view is located inside of UserViewSet. I'm wondering why I'm getting IntegrityError at /api/users/1/subscribe/ new row for relation "users_subscription" violates check constraint "prevent_self_subscription" DETAIL: Failing row contains (11, 1, 1). instead of proper json answer. Somehow SubscriptionSerializer field validation doesnt wish to work. Any thoughts? models.py class Subscription(models.Model): user = models.ForeignKey( User, related_name='subscriber', on_delete=models.CASCADE) author = models.ForeignKey( User, related_name='subscribing', on_delete=models.CASCADE) class Meta: constraints = [ models.UniqueConstraint( fields=('user', 'author'), name='unique_subscription' ), models.CheckConstraint( check=~models.Q(user=models.F('author')), name='prevent_self_subscription' ) ] serializers.py class SubscriptionSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField( read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = models.Subscription fields = ('author', 'user', ) validators = [ serializers.UniqueTogetherValidator( queryset=models.Subscription.objects.all(), fields=['author', 'user', ] ) ] def create(self, validated_data): return models.Subscription.objects.create( user=self.context.get('request').user, **validated_data) def validate_subscribing(self, value): if self.context.get('request').user == value: raise serializers.ValidationError( 'You cant subscribe to yourself!') return value views.py @action(['post'], detail=True) @permission_classes(permissions.IsAuthenticated) def subscribe(self, request, *args, **kwargs): author = get_object_or_404(models.User, id=kwargs['id']) data = request.data.copy() data.update({'author': author.id}) serializer = serializers.SubscriptionSerializer( data=data, context={'request': request}) if request.method == 'POST': serializer.is_valid(raise_exception=True) serializer.save() return Response( status=status.HTTP_201_CREATED, data=self.get_serializer(author).data) -
Resolving a ForeignKey field pointing to the model it belongs to
I have a model class in Django which has a ForeignKey referencing the model it actually belongs to: class Foo(models.Model): name = models.CharField(max_length=256, verbose_name="Name") #... some other fields bar = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True ) def __str__(self): return self.name I want to add a custom method in that class which resolves, on the fly, the name in a new field, e.g. bar_resolved when instantiating it in a QuerySet in a view: from .models import Foo foo = Foo.objects.all() # do stuff I've tried this: class Foo(models.Model): name = models.CharField(max_length=256, verbose_name="Name") #... some other fields bar = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True ) # preparing the resolved bar field which should contain the 'name' value corresponding to the id: bar_resolved = models.CharField( max_length=256, verbose_name="Bar name resolved", null=True ) def __str__(self): return self.name def resolve(self): if self.bar: self.bar_resolved = self.bar.name return super(Foo, self).resolve() Then in my view: from .models import Foo foo = Foo.objects.all() foo.resolve() but it raises: 'QuerySet' object has no attribute 'resolve' How could I achieve that? and do I need to hard code a 'resolved' field in my model for that? -
How should i insert html input data into a django database
i cant figure out how to fix this problem. Im trying to insert some data from a html form into a small simple django database sqllite if im right. i tried to follow tutorials and did allot of searching online but it seems like i've hit tutorial hell. my question is: How can i achieve putting data from the text input field on the html file into the django database. Hers what ive got sofar: the HTML: <h1>Create a Post </h1> <form action="" method="POST"> {% csrf_token %} artiest: <input type="text" name="artiest"/><br/> song: <br/> <textarea cols="35" rows="8" name="song"> </textarea><br/> <button type="submit" value="Post"/> </button> </form> the views.py def check(request): post=Post() post.artiest= request.POST.get('artiest') post.song= request.POST.get('song') post.save() return render(request, 'spotifylist/check.html') the models.py class Post(models.Model): artiest = models.CharField(max_length=100) song = models.CharField(max_length=100) naam = models.CharField(max_length=100) link = models.CharField(max_length=100) date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.artiest -
Duplicate instances not removed from queryset
I'm coming across a problem with the queryset returned in the get_tag_posts method within the Profile model. With the query as it is written, it won't remove duplicates even though .distinct() is being invoked. To provide a brief illustration of the problem: Question 1 - Tag A Question 2 - Tag A Question 3 - Tag A, Tag B As get_tag_posts is invoked it includes the following queryset: <QuerySet [<Tag: A>, <Tag: A>, <Tag: A>, <Tag: B>]> Yet I'm expecting the queryset to be returned as: <QuerySet [<Tag: A>, <Tag: B>]> From there each instance is annotated to calculate the number of times a given tag has been posted by a user. Why are duplicates of a single instance not being removed in this case? class Profile(Model): user = OneToOneField(settings.AUTH_USER_MODEL, on_delete=CASCADE) def get_tag_posts(self, order_by=None): if not order_by: order_by = "-question__date" elif order_by == "name": pass else: order_by = "-score" questions_with_tag = Subquery(self.questions.filter( tags__name=OuterRef("name")).only('id')) tags = Tag.objects.filter( question__profile=self ).distinct().order_by(order_by) return { 'records': tags.annotate(times_posted=Count(questions_with_tag)), 'title': f"{tags.count()} Tags" } class Tag(Model): name = CharField(unique=True, max_length=25) class Post(Model): body = TextField() date = DateTimeField(default=timezone.now) comment = ForeignKey('Comment', on_delete=CASCADE, null=True) profile = ForeignKey( 'authors.Profile', on_delete=SET_NULL, null=True, related_name='%(class)ss', related_query_name="%(class)s" ) vote = GenericRelation( 'Vote', related_query_name="%(class)s" ) … -
Django list_editable with custom method in list_display
I'm trying to do inline editing for list. I have the column language, which i use a custom method get_language to display how i want. from django.contrib import admin from .models import * class MovieAdminModel(admin.ModelAdmin): search_fields= ('title_en') list_display = ('get_language',) list_editable = ('get_language') def get_language(self, obj): if obj.language==1: return 'Persian With English Subtitle' else: return 'Persian' get_language.admin_order_field = "language" get_language.short_description = "language" When i use get_language in list_editable an error is returned because get_language is not in the Model, language is. If i use language in list_editable, says it isn't defined in list_display. How do i solve this? -
Django view - redirect to one page and open another in new tab
I have a Django view that looks like this: def edit_view(request, pk) # do something ... messages.success(request, "Success!") return redirect('index') The view should redirect to "index" (like in the code above), but it should also, at the same time, open another (second) page in new tab. How can this be achieved? -
Add second non null condition to Django FilterSet
How do you add a non-null constraint to a second field on a drf_filters.FilterSet? In the case below, I would like to impose a second constraint that the model field called "obsolete" is not None. class MyFilterSet(drf_filters.FilterSet): uploaded = drf_filters.IsoDateTimeFilter( field_name='uploaded_at', lookup_expr='gt', required=True ) -
Django EmailMessage return error in django_rq task
I am trying to make a simple mail sending service with django. Without the use of the queue everything works fine, but as soon as I add the use of django_rq an error occurs at the time of executing msg.send() class SendEmailSerializer(serializers.Serializer): email_to = serializers.ListField(write_only=True) subject = serializers.CharField(write_only=True) template_name = serializers.CharField(write_only=True) template_data = serializers.DictField(write_only=True) def create(self, validated_data): send_email_wrapper( emails_to=validated_data.get("email_to"), subject=validated_data.get("subject"), template_name=validated_data.get("template_name"), template_data=validated_data.get("template_data") ) return {} import os, django_rq from sizze_email.settings import BASE_DIR from django.conf import settings from django.template.loader import render_to_string from django.core.mail import get_connection, EmailMessage FROM_EMAIL = getattr(settings, 'EMAIL_FROM') def find_template(template_name): for root, dirs, files in os.walk(os.path.join(BASE_DIR, "templates")): if template_name in files: result = os.path.join(root, template_name) return result def send_emails(emails_to, subject, template_name, template_data): template = find_template(template_name=template_name) message = render_to_string(template, template_data) connection = get_connection() step = 100 for index in range(0, len(emails_to), step): msg = EmailMessage( subject=subject, body=message, from_email=FROM_EMAIL, bcc=emails_to[index:index+step], connection=connection ) msg.content_subtype = "html" msg.send() def send_email_wrapper(emails_to, subject, template_name, template_data): django_rq.enqueue(func=send_emails, emails_to=emails_to, subject=subject, template_name=template_name, template_data=template_data) I use amazon ses to send mail, django-rq performs other tasks, and if I remove sending mail from the task, then everything will work fine. What could be the problem? -
Filter with just an input field for an id
Django 4.1 In my admin site I often use raw_id_fields. But in this case it is strange that filter uses just lists of instances. I would prefer to have a filter with an input field for an id as the number of objects being filtered is immense. Is it possible to have such a filter? Maybe there is a ready made third party application? -
How to change URL for all already uploaded files in filefield after changing upload_to
What happened I changed the server for my Django application .. and I have filefield that was uploaded already and the field was like below: image = models.FileField(upload_to="uploads", verbose_name=_( "Team Strips"), help_text=_("A Strip to be used later by users")) But I the new server am forced to use a different path so I had to change it to be like image = models.FileField(upload_to="ldawri_django/uploads/uploads", verbose_name=_( "Team Strips"), help_text=_("A Strip to be used later by users")) Settings.py MEDIA_ROOT = '/home/wateopjw/l-dawri.com/ldawri_django/uploads/' MEDIA_URL = "ldawri_django/uploads/" The Problem After changing the server and upload_to parameter all images are not showing now inside the Admin panel .. but it is shown when I click open image in new tab. What I've tried Tried to re-upload one of the files and it worked like charm .. so that will force me to reupload all files .. that is kinda impossible because there are hundreds of images . What I need A function or method to help me simulate some kind of reuploading for all images so the link inside the admin site is fixed -
Python string function to make 10 character alphanumeric id
I am working with python. I need to generate string of 10 count, where I have two known value of unknown length, so after adding these two numbers the remaining place will be filled by zero between these two known strings. For example: "abcd" + "1234" should give output abcd001234. "xyz" + "12" should give output xyz0000012. Please help. Thanks -
Django: Fix order issue with list of objects
I have a function that gets queryset results from the database and does some manipulations. When I get the results of that list, somehow the order is changed. And exactly this is the function that makes the order change: schedules = list(set(schedule_list) - set(excluded_schedules)) So I will explain exactly: I want to display the availability of a professional for booking an appointment. This professional has a list of available slots. When the visitor loads the professional profile page, Django makes a query to get all time slots of the professional, and then gets all the existing appointments, then proceeds to remove the booked schedules from the total schedules, to display the rest (the available schedules). So far so good? So, the code is the following (edited for sensitive information): def get_home_schedules(date, professional): day = get_day_by_date(date) try: schedules = Schedule.objects.filter(professional=professional, day=day, stype="Home").order_by('timefrom') excluded_schedules = [] schedule_list = [] for s in schedules: new_appointments = s.appointments.filter(schedule=s, date=date, status='New') confirmed_appointments = s.appointments.filter(schedule=s, date=date, status='Confirmed') appointments = chain(new_appointments,confirmed_appointments) schedule_list.append(s) if appointments: for a in appointments: excluded_schedules.append(a.schedule) schedules = list(set(schedule_list) - set(excluded_schedules)) return schedules except: return None The schedule model is: class Schedule(models.Model): professional = models.ForeignKey(d, on_delete=models.CASCADE) timefrom = models.CharField(max_length=5, choices=HOURTIME, default="00:00") timeto = models.CharField(max_length=5, … -
How to check which message in Django
I am working on adding date functionality in my django applicaiton, and I'm checking if the date being added is not less than the current date if TaskList.objects.filter(date)< date.today(): messages.error(request,"Date not valid") Then in the jinja template I added condition in jinja to check which type of message and showing the error {% if messages %} {% for message in messages %} {% if message.level == DEFAULT_MESSAGE_LEVELS_ERROR %} <strong>{{message}}</strong> {% endif %} {% endif %} When running the application and adding the date I get the error arg, value = filter_expr TypeError: cannot unpack non-iterable type object Is this not the way to check for an error and show it in the template? -
Django property globally
I need to do calculations with other models, I have properties like that @property def SON_Gesamt_Summe_1(self): return self.SON_Sprache_1 + self.SON_Lernen_1 + self.SON_Erziehung_1 + self.SON_Sehen_1 + self.SON_Hören_und_Kommunikation_1 + self.SON_geistige_Entwicklung_1 + self.SON_körperliche_und_motorische_Entwicklung_1 @property def SON_Gesamt_Summe_2(self): return self.SON_Sprache_2 + self.SON_Lernen_2 + self.SON_Erziehung_2 + self.SON_Sehen_1 + self.SON_Hören_und_Kommunikation_2 + self.SON_geistige_Entwicklung_2 + self.SON_körperliche_und_motorische_Entwicklung_2 @property def SON_Gesamt_Summe_3(self): return self.SON_Sprache_3 + self.SON_Lernen_3 + self.SON_Erziehung_3 + self.SON_Sehen_3 + self.SON_Hören_und_Kommunikation_3 + self.SON_geistige_Entwicklung_3 + self.SON_körperliche_und_motorische_Entwicklung_3 @property def SON_Gesamt_Summe_4(self): return self.SON_Sprache_4 + self.SON_Lernen_4 + self.SON_Erziehung_4 + self.SON_Sehen_4 + self.SON_Hören_und_Kommunikation_4 + self.SON_geistige_Entwicklung_4 + self.SON_körperliche_und_motorische_Entwicklung_4 @property def SON_Gesamt_Gesamt(self): return self.SON_Gesamt_Summe_1 + self.SON_Gesamt_Summe_2 + self.SON_Gesamt_Summe_3 + self.SON_Gesamt_Summe_4 Gesamt mean sum, and those sums I need to calculate with other entries from other models. I dont know how to use the properties outside of one model, is there even a way ? -
How to insert multiple rows of data from dynamically generated rows into a database using Python Django
I have a Javascript function (addItem) that allows a user to add any number of dynamically generated rows of data and fill in the necessary fields required. See code below <div class="modal-body"> <table class="table order-list table-striped" id="myTable"> <thead> <tr> <th>Item</th> <th>Quantity</th> <th>Price</th> <th>Total</th> </tr> </thead> <tbody id="addItems"> </tbody> </table> <table> <tbody> <tr> <td colspan="5" style="text-align: left;"> <button onclick="addItem();" class="btn btn-sm btn-success" id="sspusd1" value="Add Row"><i class="fa fa-plus"></i>Add Row</button> </td> <td colspan="5" style="text-align: left;"> </td> </tr> </tbody> </table> </div> function addItem() { renumber++; var html = "<tr>"; html += "<td><select class='form-control'>{% for stock in stocks %}<option class='dropdown-item' value='{{stock.inventoryPart}}'>{{stock.inventoryPart}}</option>{% endfor %}</select></td>"; html += "<td><input type='number' class='form-control' onblur='lineTotal(this);' value='0' name='quantity[]'/></td>"; html += "<td><input type='text' class='form-control' onblur='lineTotal(this);' value='0' name='price[]'/></td>"; html += "<td><input type='text' id='lineTotal' class='form-control' value='0' disabled name='total[]' /></td>"; html += "</tr>"; document.getElementById("addItems").insertRow().innerHTML = html; }; However, One is able to insert any number of rows they want and insert the necessary data into the fields available. The problem is that I am unable to capture and store the dynamic information entered into these dynamic rows since Django is unaware of how many rows a user has created. The aim is to be able to store the data from the created dynamic rows inserted by … -
Django + React axios POST cant access Json properties
I created two abjects that need to be treated separated in the backend, and sent it to backend with: const order = { order_id: 1, customer: { name: "Jonas Illver" age: 18 } } const car = { model: 'XHL' brand: 'Toyota' } const postData = { order: order, car: car } const res = await axios.post("orders/shipping/create", JSON.stringify(postData)); console.log(res); And here I return the response: views.py @api_view(['POST']) @permission_classes([IsAuthenticated]) def shipping_create_order(request): if request.method == 'POST': return JsonResponse(request.POST) Here's what the console.log prints: res.data // {"order:"{"order_id": 1, "customer": {"name": "Jonas Illver", "age": 18}}, "car": **car object content**} The problem is that if I try to access those data in my django view, I always got a 500 error I tried accessing it via: order = request.POST['order'] # and also data = json.loads(request.POST) order = data['order'] # also order = request.POST.get('order') None os the above approaches worked, the only one that doesn't occurs an 500 error is the last one, using the POST.get, but as soon as I add the if not order: return HttpResponse("No order") line, it always return "No order" How can I access specific info from the request.POST? Am I doing something wrong with the axios request? -
ValueError at/message/new/phil_ghil Cannot assign"<SimpleLazyObject:<django.contrib.auth.models.AnonymousUser: Message.user" must be a "User"instance
Hi I am getting this error over and over again when I press the link which should leed to 'conversation' project.owner.user which starts a new conversation between 2 users. Thanks for your help! Here is my code: directs/models.py class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="from_user") reciepient = models.ForeignKey(User, on_delete=models.CASCADE, related_name="to_user") body = models.TextField(null=True) date = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) def sender_message(from_user, to_user, body): sender_message = Message( user=from_user, sender = from_user, reciepient = to_user, body = body, is_read = True ) sender_message.save() reciepient_message = Message( user=to_user, sender = from_user, reciepient = from_user, body = body, is_read = True ) reciepient_message.save() return sender_message def get_message(user): users = [] messages = Message.objects.filter(user=user).values('reciepient').annotate(last=Max('date')).order_by('-last') for message in messages: users.append({ 'user': User.objects.get(pk=message['reciepient']), 'last': message['last'], 'unread': Message.objects.filter(user=user, reciepient__pk=message['reciepient'], is_read=False).count() }) return users directs/views.py def inbox(request): user = request.user messages = Message.get_message(user=request.user) active_direct = None directs = None profile = get_object_or_404(Profile, user=user) if messages: message = messages[0] active_direct = message['user'].username directs = Message.objects.filter(user=request.user, reciepient=message['user']) directs.update(is_read=True) for message in messages: if message['user'].username == active_direct: message['unread'] = 0 context = { 'directs':directs, 'messages': messages, 'active_direct': active_direct, 'profile': profile, } return render(request, 'directs/direct.html', context) def NewConversation(request, username): from_user = request.user body = '' try: to_user = … -
Django Testing for File Size Limit
Our app has a limit on the size of the file that can be uploaded(<15MB). Is there a way i can create a dummy file of this size to test this? from django.core.files.uploadedfile import InMemoryUploadedFile import io f = io.StringIO("some initial text data") f.seek(1024 * 1024 * 1024) token_file=InMemoryUploadedFile(file=f , field_name=None, name="file.txt", content_type="text/plain", size=15729641, charset="utf8") print(token_file.size) response = self.client.post(HOME_URL, {'entity_level': 1, 'data_type': 1, 'team': GROUP_ID, 'upload_file': token_file}) # data=form_data, format='multipart') Inside clean method of the Form Class : def clean_upload_file(self): uploaded_files = self.files.getlist("upload_file") print(f"uploaded_files : {uploaded_files}") total_upload_size = sum([file.size for file in uploaded_files]) / (1024 * 1024) print(f"total_uploaded_size{total_upload_size}") if total_upload_size > MAX_UPLOADED_SIZE: raise forms.ValidationError(f"Total upload size is greater than {MAX_UPLOADED_SIZE} MB") Output: self.files.getlist('upload_file'): [<InMemoryUploadedFile: file.txt (text/plain)>] uploaded_files : [<InMemoryUploadedFile: file.txt (text/plain)>] total_uploaded_size0.0 FILE SIZE ALWAYS COMES AS ZERO WITH THIS APPROACH IS THERE A WAY TO MOCK THE FILE SIZE? -
Specify Factory db column names with FactoryBoy in a Django Test?
I've got a number of unmanaged models that I'm trying to develop some factories for so I can get some tests put together. The issue is that on a couple of them, they have db_column names and that is throwing an error for me in the factory. My models look like this: class Identity(models.Model): id = models.IntegerField(db_column="identityID", primary_key=True) person_id = models.IntegerField(db_column="personID") birth_date = models.DateField(db_column="birthdate") gender = models.CharField(db_column="gender", max_length=1) class Meta(object): # This is 'True' when testing so it's treated like a normal model managed = getattr(settings, "UNDER_TEST", False) db_table = "identity" class Person(models.Model): id = models.IntegerField(db_column="personID", primary_key=True) identity = models.ForeignKey( Identity, db_column="currentIdentityID", on_delete=models.PROTECT ) ticket_number = models.IntegerField(db_column="ticketNumber") class Meta(object): # This is 'True' when testing so it's treated like a normal model managed = getattr(settings, "UNDER_TEST", False) db_table = "person" class YearTerm(models.Model): active = models.BooleanField(default=False) name = models.CharField(max_length=50) created_by = models.ForeignKey( Person, on_delete=models.PROTECT ) class Meta: # This is 'True' when testing so it's treated like a normal model managed = getattr(settings, "UNDER_TEST", False) db_table = "[ALTS].[yearterm]" My factories look like this: class IdentityFactory(factory.django.DjangoModelFactory): class Meta: model = Identity @classmethod def _setup_next_sequence(cls): try: return Identity.objects.latest("id").id + 1 except Identity.DoesNotExist: return 1 id = factory.Sequence(lambda n: n) person_id = factory.Sequence(lambda n: … -
How to append a list in a dict from a JSONFeild in django
I want to use get_or_create() to search for an object. If it doesn't exist, it gets created. If it does exist, I want to update its metadata which is stored as a JSONFeild. obj, created = Customer.objects.get_or_create( first_name="John", last_name="Doe", defaults={ 'metadata':{ "customer_created": "2022_09_26", "adress_list": ["123 Street"], }, ) Which is correct? if not created: obj.metadata["address_list"].append(["123 Street"]) or if not created: addresses = obj.medata["address_list"] addresses.append(["123 Street"]) obj.metadata["address_list"] = addresses obj.save() Is there a better way to do this? I am not allowed to change the Customer class but I can change how I structure the metadata dict.