Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Tweet not creating in django twitter clone
I am just trying to build a simple twitter clone using django. To create a new tweet, a user has to choose an image and type some text. So i do just that, and when I click on the create tweet button, I get a form error that says "The image field is required". I don't understand why this happens. Here is a screenshot of that error: I don't even get ant error message. Here is my CreateTweet view function: class CreateTweetView(LoginRequiredMixin,CreateView): model = Tweet fields = ('image','tweet') template_name = 'twitter/create_tweet.html' def form_valid(self): new_tweet = form.save(commit=False) new_tweet.author = self.request.user new_tweet.save() return redirect('home') What is the problem here? EDIT: I have chosen an image, and upon form submission, I get this error In the media folder, I don't see the uploaded image -
How to pass data from ajax to django view?
I have the following script for ajax. this gets the public key and sends all other detail to Stripe server for payment but I need to send the dynamic value of price to item_line. fetch("/config/") .then((result) => { return result.json();}) .then((data) => { // Initialize Stripe.js var data1 = $('#priceId').html(); const stripe = Stripe(data.publicKey); // Event handler let submitBtn = document.querySelector("#submitBtn"); if (submitBtn !== null) { submitBtn.addEventListener("click", () => { var d = $('#priceId').html(); console.log(d) // this value need to send to my view... fetch("/create-checkout-session/") .then((result) => { return result.json(); }) .then((data) => { // Redirect to Stripe Checkout return stripe.redirectToCheckout({sessionId: data.sessionId}) }) .then((res) => { console.log(res); }); }); } }); how can I pass and how can I catch in a view file? my current view is: @csrf_exempt def create_checkout_session(request): if request.method == 'GET': domain_url = 'http://localhost:8000/' stripe.api_key = settings.STRIPE_SECRET_KEY try: checkout_session = stripe.checkout.Session.create( client_reference_id=request.user.id if request.user.is_authenticated else None, success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'cancel/', payment_method_types=['card'], mode='subscription', line_items=[ { 'price': settings.STRIPE_PRICE_ID, # here need dynamic selected value 'quantity': 1, } ] ) return JsonResponse({'sessionId': checkout_session['id']}) except Exception as e: return JsonResponse({'error': str(e)}) please help me. -
GeoDjango Get all records of a model that are within a given distance to any of the points of a given set of locations
I am trying to get the list of person(s) that are within a distance of 500m to a poi. I can achieve this goal in PostGIS as: SELECT DISTINCT public.dbconn_person.id, public.dbconn_person.name, public.dbconn_person.location, public.dbconn_poi.id, public.dbconn_poi.name, public.dbconn_poi.location FROM public.dbconn_person INNER JOIN public.dbconn_poi on st_dwithin(public.dbconn_person.location::geography, public.dbconn_poi.location::geography, 500); The point is that I am trying to use the same query in Django and I am facing some problems. models.py class Person(models.Model): name = models.CharField(max_length = 120) location = models.PointField() class Poi(models.Model): name = models.CharField(max_length = 120) location = models.PointField() view.py listpoi = Poi.objects.all() listperson = Person.objects.all() I expected that something like this would work, poi_filter = Person.objects.filter(location__dwithin=(Poi.objects.only('location'), 500)) As far as I have read, it seems that the location_dwithin function only accepts single points. Is this correct? Is there any way I can achieve my SQL result using Django? -
Debugger on Pycharm Macbook [closed]
Hello Fellow Developers. I am a junior in Django and Python. I wanted to set up the debugger in Pycharm but was not successful, As you know before running the server you have to enable the environment variables to be able to run the server because we are using shell file instead of .env file in my company's project. I cannot find any good source to follow so my last hope is StackOverflow. Any help is greatly appreciated 😊 -
Make executable file for django project to share with others
I have created a full running Django project and it's running fine locally. Now I have a requirement to share the project with others so that they can also use the web application running it on their local machine. I know Django is a web app and ideally should be deployed on a server instead of sharing the code but that's not a option for me now due to budget constraints. I was planning to share the entire folder with the team, but few of them are not from technical background so they are confused on how to activate the virtual environment and then run manage.py command. Questions: Is there a option to make the project executable i.e. one a click web app will open and users can start playing with it? If yes, how to implement it? I tried using pyinstaller, it did created the application but double clicking on it shows no result. Please help !! -
I installed uwsgi on ubuntu 20.04 but i keep getting errors when i run the command. How to i correct this error
sudo uwsgi --plugin=python3 --module=nebula.wsgi:application --env=DJANGO_SETTINGS_MODULE=nebula.settings.pro --master --pidfile=/tmp/project-master.pid --http=127.0.0.1:8000 --uid=1000 OUTPUT open("/usr/lib/uwsgi/plugins/python3_plugin.so"): No such file or directory [core/utils.c line 3724] !!! UNABLE to load uWSGI plugin: /usr/lib/uwsgi/plugins/python3_plugin.so: cannot open shared object file: No such file or directory !!! uwsgi: unrecognized option '--module=nebula.wsgi:application' getopt_long() error I also ran sudo uwsgi --module=nebula.wsgi:application --env=DJANGO_SETTINGS_MODULE=nebula.settings.pro --master --pidfile=/tmp/project-master.pid --http=127.0.0.1:8000 --uid=1000 Then i got this output: uwsgi: unrecognized option '--module=nebula.wsgi:application' getopt_long() error -
Django: Executing multiple commands with checkboxes
In my template I have two different tables. Table 1 shows every records with status "Yes". Table 2 shows records with status "No". Each row of table 1 has a button which changes the database status from "Yes"to "No". Meaning that if the user clicks the button, the record will move from table 1 to table 2. Table 2 has the same function, but then the other way around. I have now added a checkbox to do the same thing but then which multiple records. It all works, except in one scenario. When the first table is empty, I am unable to move items from table 2 to 1 with the checkbox function. The two tables <form action="{% url 'complete_multiple_tasks'%}" method="POST"> {% csrf_token %} <table class="trainers-table" id="myTable2"> <tr> <th> <button id = "deletion"class="btn_delete" type="submit" name="checkboxsubmit"> Uitvoeren</button></th> <th> Taak</th> <th> Check?</th> <th> Voltooien</th> </tr> {% for todo_nee in todo_nee%} <tr> <td> <input type="checkbox" name="instance" value={{todo_nee.id}} id="delete_selected"> </td> </form> <td> {{todo_nee.name}}</td> <td> <i id= "nocheck" class="fas fa-times-circle"></i></td> <td><form action="{% url 'todo_compleetmaken' todo_nee.id %}" method=POST> {% csrf_token %} <input type="hidden" name="returntopage" value="{{ request.path }}"> <button class="paginationformat2" type="submit">Uitvoeren</button> </form> </td> </tr> {%endfor%} </table> </div> <form action="{% url 'oncomplete_multiple_tasks'%}" method="POST"> {% csrf_token %} <table class="trainers-table" … -
Django GenericViews Context Data with Parameters
I have the following code views.py return HttpResponseRedirect(reverse('doc_aide:write_prescription', kwargs={'patient': patient.id})) And the Class in view.py fields = ("__all__") model = PrescriptionLine template_name = 'template.html' def __init__(self, *args, **kwargs): super(SinglePrescriptionCreateView, self).__init__(*args, **kwargs) print(kwargs) # this is {} def get_context_data(self, *args): context = super().get_context_data(*args) context['patient'] = Patient.objects.get(pk=1) # here needs to be the ID I need this Patient Id (where the 1 is), the print is {}, How please do I pass the patient ID into the class? -
Reverse for 'edit_post' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<slug>[^/]+)/edit_post$']
I am going through a Django tutorial and getting this error when trying to open post_detail view ( where i put the link of of edit_post ) for edit post in my blog app. I use Django==3.1.2. views.py def edit_post(request,id): context = {} user = request.user if not user.is_authenticated: return redirect('mains:posts') posts = get_object_or_404(Post,id=id) if request.POST: form = UpdatePost(request.POST or None, request.FILES or None ) if form.is_valid(): obj = form.save(commit=False) obj.save() context['success_message'] = "Updated" posts = obj form = UpdatePost( initial = { 'post_title' : posts.post_title, } ) context['form'] = form return render(request, 'mains/edit_post.html', context) forms.py class UpdatePost(forms.ModelForm): class Meta: model = Post fields = ['post_title'] def save(self,commit=True): post = self.instance post.post_title = self.cleaned_data['post_title'] if commit: posts.save() return posts urls.py path('<id>/edit_post', views.edit_post, name='edit_post'), models.py class Post(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') A template that causes the error in line 5 - post_detail_view.html. The error message highlights {% url 'edit_post' posts.id %} post_detail_view.html <br> <a>{{ post.post_title }}</a> <br> <a href="{% url 'mains:edit_post' post.id %}">Edit</a> The Problem When i open post_detail.html page in browser , i get this error :- Reverse for 'edit_post' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[^/]+)/edit_post$']. When i delete edit_post link from post_detail … -
cannot access a model field from filter queryset result
I have a model like this : class MeetingMember(models.Model): CHOICES = ( ("A", "Accepted"), ("R", "Rejected"), ) status = models.CharField(max_length=9,choices=CHOICES,default=None) meeting = models.ForeignKey(Meeting, on_delete=models.CASCADE, related_name="members2") user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name="memberships") and in my views.py i have this code: if get_user_model().objects.get(email=email): member = MeetingMember.objects.filter(meeting=meeting).filter(user__email=email) if len(member)==0: print(member.user) print('not joined yet') elif member.status=="A": print('accepted') else: print('rejected') else: print('not found') but i get this error: 'QuerySet' object has no attribute 'user' any suggestion on how to fix it? note :MeetingMember model is used in my another model filed like this: joined_members = models.ManyToManyField(get_user_model(), blank=True, through='MeetingMember') Many thanks! enter code here -
How to set default value for a model field based on enum in Django?
I'm using Django 2.2.5 and have multiple choice fields based on enums in my models. For an unknown reason I now get a migration error when using an enum for choice field during migration: django.db.utils.OperationalError: (1067, "Invalid default value for 'protocol'") model.py from django.db import models # See class above from .utils import NetworkProtocolList class Networks(models.Model): ipv4 = models.GenericIPAddressField(blank=False, null=False) protocol = models.CharField(choices=NetworkProtocolList.choices(), max_length=20,default=NetworkProtocolList.ETH) class Meta: managed = True db_table = 'networks' utils.py from enum import Enum class NetworkProtocolList(Enum): ETH = 'Ethernet' MPLS = 'MPLS' @classmethod def choices(cls): return [(key.name, key.value) for key in cls] I issued manage.py makemigrations and subsequent manage.py migrate generated the following error: django.db.utils.OperationalError: (1067, "Invalid default value for 'protocol'") xxxx_auto_xxxxxxxx_xxxx.py # Auto generated migration file import my_.utils from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('my_app', 'yyyy_auto_yyyyyyyy_yyyy'), ] operations = [ migrations.AddField( model_name='networks', name='protocol', # Field definition here, pay attention to the default value field=models.CharField(choices=[('ETH', 'Ethernet'), ('MPLS', 'MPLS')], default=my_app.utils.NetworkProtocolList('Ethernet'), max_length=20), ), ] Than I edited migration file to manually set the default to a string instead of calling enum class: xxxx_auto_xxxxxxxx_xxxx.py # Edited migration file import my_.utils from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('my_app', 'yyyy_auto_yyyyyyyy_yyyy'), ] operations = [ … -
How to filter data dynamically by supply values from form using django
I want to filter Blog Post objects or records based on the Post Category and a User that uploaded the Post record, it gives me an error when I try to do filter, this is the error. ValueError at /dashboard/filter-post/ The QuerySet value for an exact lookup must be limited to one result using slicing. Here is my models.py class Category(models.Model): cat_name = models.CharField(max_length=100, verbose_name='Category Name') cat_desc = models.TextField(blank=True, null=True) def __str__(self): return self.cat_name class Meta(): verbose_name_plural='Category' class Post(models.Model): pst_title = models.CharField(max_length=150) pst_image = models.ImageField(blank=True, null=True, upload_to='uploads/') user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ManyToManyField(Category) content = models.TextField() created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.pst_title @property def img_url(self): if self.pst_image: return self.pst_image.url on forms.py class FilterForm(forms.ModelForm): user = forms.ModelChoiceField( queryset=User.objects.all(), widget=forms.Select(attrs={'class': 'form-control'})) category = forms.ModelMultipleChoiceField( queryset=Category.objects.all(), widget=forms.SelectMultiple(attrs={'class': 'form-control js-example-disabled-results'})) catch_bot = forms.CharField(required=False, widget=forms.HiddenInput, validators=[validators.MaxLengthValidator(0)]) class Meta(): fields = ['user', 'category' ] model = Post on views.py def filter_post(request): post = FilterForm(request.GET) queryset = Post.objects.all() if post.is_valid(): user=post.cleaned_data.get('user') category=post.cleaned_data.get('category') if user and category: queryset = queryset.filter(user__username=user, category__cat_name=category) return render(request, 'backend/filter-post.html', {'query':queryset, 'post':post}) I am having challenges properly filtering this in my views any help? -
Image not uploading to aws s3 using django app
When a user registers on my website, a unique image is created internally(meaning, the user doesn't upload any image) and I want to upload that image to the s3 bucket in the name of the registered user. I have a single bucket in s3 that stores both static and media resources. The image that I create during the registration process is supposed to be uploaded to the media directory. views.py . . . img = qr.make_image() img.save('media/qrcodes/%s.png'%name) addnl.qr_gen = 'qrcodes/%s.png'%name # addnl is an instance of the form and qr_gen is a form field. addnl.save() ... models.py class UserModel(models.Model): ... qr_gen = models.ImageField(upload_to='qrcodes',default=None,null=True,blank=True) settings.py AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = config('AWS_S3_CUSTOM_DOMAIN') AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = config('AWS_LOCATION') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) TEMP = os.path.join(BASE_DIR, 'temp') STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'project.storage_backend.MediaStorage' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I've subclasses S3boto3Storage to store static and media files in separate directories and avoid overwriting. Hence, the DEFAULT_FILE_STORAGE = 'project.storage_backend.MediaStorage'. storage_backend.py from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = 'media' file_overwrite = False When a new user registers the account is created successfully, but the image … -
vuejs show real time log content on the page
Recently I get a requirement to show a log in frontend page via vuejs code. It's just to show a raw data of a log file. Now the file is served in Nginx and Django. And can be accessed via URL like http://myhost/media/file.log. But when I click the url in browser, the file is always downloaded instead of displayed in the page. Also the content is loaded all of the together. Can I implement the function just as bash command tail -f file.log in vuejs (Jenkins console has the same function)? It means display the file in the page with real time dynamic content. Many thanks. -
how does django cache queries indeed?
I like to know how django caching querySet work! for example how one can explain the following behaviour!? let say there is a model foo_model qs_1 = foo_model.objects.all() qs_2 = foo_model.objects.all() qs_x = foo_model.objects.filter(some_filed=some_value) when qs_1 is evaluated the qs_2 won't be evaluated, even though qs_1 is not qs_2 len(qs_1) len(qs_2 ) but qs_x will be evaluated! len(qs_x ) -
Django Celery scheduled task no output
I am working with Django and want a certain task to be runned twice a day (09:00 and 17:00). So I found Celery on the internet, and it looks good. I followed a few tutorials, and set it up. I've set a periodic task in the database, and it runs (for test) every minute. Or, it doesn't, it only says so: [2020-12-15 14:32:34,997: INFO/MainProcess] Scheduler: Sending due task ResumePentest (VulnManager.tasks.resumePentest) [2020-12-15 14:32:34,998: DEBUG/MainProcess] VulnManager.tasks.resumePentest sent. id->277c73a8-58bc-41ea-b2ba-4aa7af0c8b94 I don't think it actually runs, because I've tried some different "debugging" options: create file, print text, run my actual command. None of them seems to be working. My tasks.py file looks like this (for testing): from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def resumePentest(): f = open("/home/marvin/demofile2.txt", "a") f.write("Now the file has more content!") f.close() I run the celery worker with this command: celery -A VulnScanner beat -l DEBUG --scheduler django_celery_beat.schedulers:DatabaseScheduler Any hints? Not sure what I am doing wrong? If more info is needed, please let me know. Full output of celery worker: celery beat v5.0.4 (singularity) is starting. __ - ... __ - _ LocalTime -> 2020-12-15 14:44:26 Configuration -> . broker -> amqp://guest:**@localhost:5672// . loader -> celery.loaders.app.AppLoader … -
How to make my code insensitive to acronyms
I'm creating a website that shows available carparks in each college campus. How do I make the code insensitive to acronyms, e.g.g if the name of the campus is DCU Alpha? carparks.html <h2> {% if campus %} {{ campus }} {% else %} No such campus {% endif %} </h2> {% if campus %} {% if carparks %} <ul> {% for carpark in carparks %} <li>{{carpark.name}}: {{carpark.spaces}} spaces, {{carpark.disabled_spaces}} spaces for people with disabilities <br>Spaces available: {{ carpark.spaces_available }}<br><br> </li> {% endfor %} </ul> {% else %} <p>No carparks found</p> {% endif %} {% endif %} views.py def carparks(request): context = {} Base_URL = 'http://jfoster.pythonanywhere.com/carparks/' campus_name = request.GET['campus'] try: campus = Campus.objects.get(name__iexact=campus_name) except Campus.DoesNotExist: return render(request,"parkatdcu/carparks.html",context) carparks = Carpark.objects.filter(campus_id=campus) carpark_info = [] for carpark in carparks: URL = Base_URL + carpark.name r = requests.get(URL).json() if 'spaces_available' in r: spaces_available = r['spaces_available'] else: spaces_available = 'not available' carpark_info.append({ 'name': carpark.name, 'spaces': carpark.spaces, 'disabled_spaces': carpark.disabled_spaces, 'spaces_available': spaces_available } ) context['campus'] = campus_name.title() context['carparks'] = carpark_info return render(request,"parkatdcu/carparks.html",context) -
update the boolean field with hard condition - django rest framework
It's a little difficult. if some user like some post and then call the function allPost (in views.py) it should return is_liked=True in serializer.data. like this: { "id": 48, "body": "like me", "date": "2020-12-15T11:39:58.233912+06:00", "user": {}//objects "total_likes": 4, "liked_by": {}//object "total_comments": 0, "is_liked":true }, { "id": 47, "body": "hello", "date": "2020-12-15T10:53:56.047665+06:00", "user": {},//object "total_likes": 2, "liked_by": [ { "first_name": "", "last_name": "" }, { "first_name": "test3", "last_name": "three" } ], "total_comments": 0, "is_liked": false }, models.py: class Post(models.Model): id = models.AutoField(primary_key=True) body = models.TextField(max_length=10000) date = models.DateTimeField(auto_now_add=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) liked_by = models.ManyToManyField(User, blank=True, related_name='liked_by') is_liked = models.BooleanField(default=False) class Meta: ordering = ['-date'] serializers.py: class PostSerializer(serializers.ModelSerializer): user = UserSerializers() total_likes = serializers.SerializerMethodField() liked_by = SimpleUserSerializer(many=True, read_only=True) total_comments = serializers.SerializerMethodField() class Meta: model = Post fields = ('id','body','date','user','total_likes','liked_by','total_comments','is_liked') def get_total_likes(self, instance): return instance.liked_by.count() def get_total_comments(self, instance): return instance.comment_set.count() urls.py: path('myapi/likepost/<str:pk>/', views.likePost, name='likePost'), views.py: @api_view(['GET']) @permission_classes((IsAuthenticated,)) def allPost(request): user = request.user.id allpost = Post.objects.all() serializer = PostSerializer(allpost, many=True) liked = Post.objects.filter(liked_by__id=user).values_list('id', flat=True) #--> i think, code should be written here return Response(serializer.data) @api_view(['POST']) @permission_classes((IsAuthenticated,)) def likePost(request, pk): user = request.user.id post = Post.objects.get(id=pk) previous_user = post.liked_by.all().values_list('id', flat=True) liked_by = [user] for i in previous_user: liked_by.append(i) data = {'liked_by':liked_by} serializer = … -
AttributeError: 'ShiftChangeFilter' object has no attribute 'values_list'
Hello Everyone I am getting Attribute Error. I have one Django based webpage where I am using Django filter to search user result and trying to implement functionality for download filtered result only in order to achieve this I am trying to pass Filter class, in my existing download views. (Earlier my download view is responsible to download all model-based data). My code is from .models import * import django_filters class ShiftChangeFilter(django_filters.FilterSet): id = django_filters.NumberFilter(label="DSID") class Meta: model = ShiftChange fields = ['ConnectID', 'EmailID','id','SerialNumber','Project_name',''] My view responsible to download xls file: from django.utils import timezone now_aware = timezone.now() import xlwt,openpyxl def exportgenesys_data(request): allgenesys = ShiftChange.objects.all() genesys_filter = ShiftChangeFilter(request.GET,queryset=allgenesys ) print('download:',genesys_filter.qs) response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="Genesys_ShiftTiming.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('GenesysShiftChange Data') # this will make a sheet named Users Data # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['id', 'ConnectID', 'Shift_timing', 'EmailID', 'Vendor_Company', 'Project_name', 'SerialNumber', 'Reason', 'last_updated_time'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # at 0 row 0 column # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = genesys_filter.values_list('id', 'ConnectID', 'Shift_timing', 'EmailID', 'Vendor_Company', 'Project_name', 'SerialNumber', 'Reason', 'last_updated_time') for row in rows: row_num += 1 for col_num … -
Field 'id' expected a number but got a dict
I'm getting a error when run seed_responses command. Complete error std error: $ ./manage.py seed_responses --number 15 Traceback (most recent call last): File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1774, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'dict' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "./manage.py", line 22, in <module> main() File "./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/src/secret/api/core/management/commands/seed_responses.py", line 36, in handle seeder.execute() File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django_seed/seeder.py", line 157, in execute entity = self.entities[klass].execute(using, inserted_entities) File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django_seed/seeder.py", line 101, in execute obj = manager.create(**faker_data) File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 447, in create obj.save(force_insert=True, using=self.db) File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/db/models/base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/db/models/base.py", line 790, in save_base updated = self._save_table( File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/db/models/base.py", line 895, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/db/models/base.py", line 933, in _do_insert return manager._insert( File "/usr/src/secret/api/.venv/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File … -
Django downloading image using ImageField
I am trying to create a Django app that allows user to upload and download images from /images/ folder (similar to a static folder in my app). My upload part of the app uses ImageField to store the image filepath into MySQL database: models.py class ImagefieldModel(models.Model): title = models.CharField(max_length = 200) img = models.ImageField(upload_to = "images/") class Meta: db_table = "imageupload" forms.py class ImagefieldForm(forms.Form): name = forms.CharField() image_field = forms.ImageField() fileupload.html {% extends "main/header.html" %} {% block content %} <head> <title>Django File Upload</title> </head> <body> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> </body> {% endblock %} views.py def imgupload(request): context = {} if request.method == "POST": form = ImagefieldForm(request.POST, request.FILES) if form.is_valid(): name = form.cleaned_data.get("name") img = form.cleaned_data.get("image_field") obj = ImagefieldModel.objects.create( title = name, img = img ) obj.save() print(obj) messages.info(request, f"image uploaded successfully!") return redirect("main:basehome") else: form = ImagefieldForm() context['form'] = form return render( request, "main/fileupload.html", context) For the download part of my app, I want the app to list down all images from the /image/ folder and users can choose an image to download into their download folder. How do I do that in Django while using ImageField? -
Files uploaded through a "multipart/form-data" form aren't stored anywhere
I've been struggling with this for some time and it makes me think that what I want to achieve is done differently in Django. I have a model (Album) with the following definition: class Album(models.Model): building_id = models.ForeignKey(Building, on_delete=models.CASCADE) name = models.TextField() I have another model (Photo): class Photo(models.Model): album_id = models.ForeignKey(Album, on_delete=models.CASCADE, related_name="photos") path = models.ImageField(upload_to="photos") You can probably see where this is going: I want to be able to upload many photos at once when creating a photo album. To access my Album data through Django admin, I register it: @admin.register(models.Album) class AlbumAdmin(admin.ModelAdmin): form = forms.AlbumForm And the associated form, which apparently must inherit from ModelForm: class AlbumForm(forms.ModelForm): class Meta: model = Album fields = ["building_id", "name", "photos"] building_id = forms.ModelChoiceField(queryset=Building.objects.all()) name = forms.CharField() photos = forms.FileField(widget=forms.ClearableFileInput(attrs={"multiple": True})) After this setup, going to http://localhost:8000/admin/api/album/add offers me a form (with enctype="multipart/form-data") where I can upload my files. Pressing the submit button succesfully create the new album, but the uploaded photos are nowhere to be found (my ${MEDIA_ROOT}/photos is still empty), and obviously no Photo model is created. What would be the best "Django way" of doing it, and how could I achieve any of the following: Whenever a new … -
Django queryset count by attribute
Is there a simple, or built-in mechanism in Django to perform a queryset where from the queryset output I will be able to do some statistics based on an specific attribute ? Here is my example: models.py class Transaction(models.Model): transactionType = models.CharField(max_length=2) value = models.DecimalField(max_digits=7, decimal_places=2) transactionDate = models.DateField() owner = models.ForeignKey(User, related_name="transactions", on_delete=models.CASCADE) def __str__(self): return self.transactionDate serializers.py class TransactionSerializer(serializers.ModelSerializer): owner = UserFilteredSerializer(many=False) class Meta(): model = Transaction fields = ( 'pk', 'transactionType', 'value', 'transactionDate', 'owner' ) views.py class TransactionList(generics.ListCreateAPIView): parser_classes = (MultiPartParser, FormParser) serializer_class = TransactionSerializer name = 'transaction-list' def get_queryset(self): queryset = Transaction.objects.all() transactionType = self.request.query_params.get('transactionType', '') return queryset.filter(transactionStatus=transactionStatus).order_by('-transactionDate') My View returns output as below: [ { "pk": 261, "transactionType": "ch", "transactionDate": "2020-11-01" "value": "30.00", "owner": { "username": "john", "first_name": "John", "last_name": "Smith", } }, { "pk": 262, "transactionType": "ch", "transactionDate": "2020-11-01" "value": "40.00", "owner": { "username": "andrew", "first_name": "Andrew", "last_name": "Kowalsky", } }, { "pk": 263, "transactionType": "ch", "transactionDate": "2020-11-01" "value": "50.00", "owner": { "username": "john", "first_name": "John", "last_name": "Smith", } }, ] But I would like to get number of transactions for each individual user. Is it a simple way to get this in django like this ? return queryset.filter(transactionStatus=transactionStatus).count(by username) -
Optimising infrastructure for Django application that utilizes Pandas
My company has built a backend Django application that utilizes pandas data frames. Before I jump in as a DevOps Engineer, the application was hosted on Digital Ocean on a machine with 8GB of RAM and 4vCPUs. According to some metrics, the application is utilizing less than 10% CPU and around 37% of RAM I was tasked with migrating the application to GKE, which I am currently monitoring how it is doing. I am using the normal E2 VMs as nodes and I have allocated the container 1GB of RAM and I have left the CPU to be of the default value. According to the metrics, CPU usage is really low and the RAM usage is high but it never drops even when there are no requests to the application, A developer also complained that the application hosted on GKE is quite slow compared to the application hosted on Digital Ocean. My question is; how can I better engineer the infrastructure while keeping costs in mind? Should I add more CPUs and RAM? Should I use other VM types for Nodes? Any tips or suggestions are highly welcomed! Thank you. -
Custom Queryset constructor loses value of argument
Django. I want to prevent my future self from overwriting a certain property of the Cable class in the database. I wrote a custom Django QuerySet that accepts a field name in the constructor and which will prevent updates on that field. However, in the constructor, the argument field_name is well received (as evidenced by the correct output from print), but then the Exception is also raised, meaning that the variable was instantly changed to None. What devilry? Note I also tried putting *args in the constructor signature. class PreventChangeQuerySet(models.QuerySet): def __init__(self, field_name, **kwargs): self._field_name = field_name print(f"Field name: {self._field_name}") if self._field_name is None: print(self._field_name) raise Exception("A field name must be set") self._field_name = field_name super().__init__(**kwargs) def update(self, *args, **kwargs): if kwargs.get(self._field_name): raise Exception("This field may not be updated") super().update(*args, **kwargs) class Cable(models.Model): __original_short_name = None # For keeping track of changes objects = PreventChangeQuerySet(field_name="short_name").as_manager() output: ./manage.py shell_plus Field name: short_name Traceback ... TypeError: __init__() missing 1 required positional argument: 'field_name'