Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Manually rendered form fields do not save data
I really wanted to figure this out myself and I spent over 4 hours on the subject but I give up now. I have a form that is supposed to save data, and if I lay out the form with the {{ form }} tag everything works great. If I put in to form with individual tags like {{ form.client_email }}, the form data is not saved to the database. I need to render these fields manually for front end purposes but I just couldn't figure out how to do it. I appreciate your help a lot. Here is my code. views.py def client_list_view(request): if request.method == 'POST': form = ClientModelForm(request.POST) if form.is_valid(): client_title = form.cleaned_data["client_title"] client_email = form.cleaned_data["client_email"] client_turkishid_no = form.cleaned_data["client_turkishid_no"] client_tax_no = form.cleaned_data["client_tax_no"] client_tax_office = form.cleaned_data["client_tax_office"] client_contactperson = form.cleaned_data["client_contactperson"] client_phone_number = form.cleaned_data["client_phone_number"] Client.objects.create( client_title=client_title, client_email=client_email, client_turkishid_no=client_turkishid_no, client_tax_no=client_tax_no, client_tax_office=client_tax_office, client_contactperson=client_contactperson, client_phone_number=client_phone_number ).save() return redirect("books:client-list") else: form = ClientModelForm() client_list = Client.objects.all().order_by("client_title") context = {'client_list' : client_list, "form": ClientModelForm} return render(request, 'clients/client_list.html', context=context) Working template <div id="clientModal" class="modal bottom-sheet"> <div class="modal-content"> <form method="POST"> {% csrf_token %} {{form}} <button class="btn">Ekle</button> </form> </div> </div> Not Working Template <div id="clientModal" class="modal bottom-sheet"> <div class="modal-content"> <div class="row"> <div class="col s12"> <ul class="tabs"> <li class="tab … -
Django - getting the selected results return from data in template inside a for- loop
I having some issues in getting the selected to show on my res summary. I was able to get data from an api and load inside a Django template. On the Django template, this data is in a for loop, . it only works when I selected the first data inside that for loop which I am able to display on the res summary and insert into the database but for the rest of the data I cannot. -
Django + nginx security in production
I recently found a big security breach in a project I did with django. The application was deployed in production and worked properlly using Nginx, I also use python decouple to separate my sensitive information. Here is the permissions on the project files: -rw-r--r-- 1 rouizi rouizi 151 Oct 8 21:30 .env -rw-rw-r-- 1 rouizi rouizi 65 Jul 9 07:50 .env.example drwxrwxr-x 8 rouizi rouizi 4096 Sep 23 15:50 .git -rw-rw-r-- 1 rouizi rouizi 244 Jul 14 09:18 .gitignore drwxrwxr-x 5 rouizi rouizi 4096 Sep 22 16:17 core -rwxrwxr-x 1 rouizi rouizi 624 Jun 25 13:58 manage.py drwxrwxr-x 3 rouizi rouizi 4096 Oct 8 21:27 prof -rw-rw-r-- 1 rouizi rouizi 599 Jul 14 09:18 requirements.txt drwxrwxr-x 4 rouizi rouizi 4096 Jun 25 13:58 static drwxrwxr-x 5 rouizi rouizi 4096 Jun 25 14:02 staticfiles drwxrwxr-x 3 rouizi rouizi 4096 Oct 6 09:11 templates drwxrwxr-x 4 rouizi rouizi 4096 Jun 25 14:02 users drwxrwxr-x 6 rouizi rouizi 4096 Jun 25 13:59 venv let say my domain name is exemple.com. What I didn't know is if I try to access exemple.com/.env I can see the content of the .env file. This is really bad because this file contains the secret key and other … -
Delete db item in Django Python via Javascript button
I have written a small application in which want to build in a function which provides the possibility to delete database items (stored earlier) via a html button and Jinja (dynamic link building). Models.py Forms.py Views.py Etc. Have all been updated correctly. However the problem in building the link to delete a certain item gets triggered by the fact that i can't seem to succes in passing the db item (item.id) to the dynamic link because i have decided to put a javascript pop-up in between that asks for a confirmation before deleting the item. All attempts have failed until now. After endless searching for a solution i hope anyone can help me with this... First i generated a for loop that displays all the items in the db to which i have added a button "delete". This buttons triggers a javascript pop-up which works fine asking if the item must be deleted or the command should be cancelled. i don't seem to succeed in putting the dynamic link behind the last confirmation button. Python > Django > HTML > HTML Jinja > Javascript > HTML Jina For the moment the link has been build (lacking any better solution) as … -
Django not able to submit form using ModelForm
The form is always sending a Get request instead of a Post which has been explicitly added using method = "POST". So, not able to persist the data to db. I have just started with Django so, any help will be appreciated. Below are the code snippets: create_order.html <form method="POST" action="{% url 'home' %}"> {% csrf_token %} {{form}} <input class="btn btn-primary btn-sm" type="submit" name="Submit"> </form> urls.py urlpatterns = [ path('', views.dashboard, name='home'), path('products/', views.product, name='products'), path('customer/<str:cust_id>/', views.customer, name='customer'), path('create_order/', views.create_order, name='create_order'), ] views.py def create_order(request): form = OrderForm() if request.method == 'POST': print("In Post", request.method) form = OrderForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: print("In else", request.method) print(form.is_valid()) if form.is_valid(): form.save() return redirect('/') context = {'form' : form} return render(request, 'accounts/create_order.html', context) terminal output In else GET False -
Django merge querysets in one page
In django rest framework i am using pagination of 20 on a model. Now i want to make a queryset which takes 5 items which has the featured field as true. The other 15 should be items which has the featured field as false. Does anyone have an idea how to make this work? -
Django url without pk or slug (One to Many Relationship)
Please can anyone help me ou with this, I am totally lost.I am new and trying to learn django. I am trying to update my model formset using update views without using the model primary key on the url (eg: update-pet-health/<int:pet_id>/<pk>) I want it to be just update-pet-health/<int:pet_id> scenario: A pet in a vet clinic might have multiple health concerns. Model: class PetHealth(models.Model): pet_health_id = models.BigAutoField(primary_key=True, null=False) pet = models.ForeignKey('Pet', null=False, on_delete=models.PROTECT) symptom_type = models.CharField(null=True, blank=True) date_of_symptom = models.DateTimeField(null=False, auto_now_add=True) symptom_observed_by = models.CharField(null=True, blank=True) date_of_cure = models.DateTimeField(null=False, auto_now_add=True) cured_by = models.CharField(null=True, blank=True) give_medication = models.BooleanField('Propose Medication', null=False) date_medication_proposed = models.DateField('Date Medication Proposed', null=True, blank=True) Medication_given_by = models.CharField(null=True, blank=True) comments = models.TextField('Comments', null=True, blank=True) This is the form I used for...it is the same as the createview cbv Form: class PetHealthForm(forms.ModelForm): class Meta: model = PetHealth fields = [ 'symptom_type ', 'symptom_observed_by', 'cured_by ', 'give_medication', ] PetHealthFormset = modelformset_factory(PetHealth, form=PetHealthForm, extra=3) I'm trying to update the form using update view and here is my cbv for update View: @method_decorator(login_required, name='dispatch') class UpdatePetHealth(UpdateView): base = ... template_name = base + '/update_pet_observation.html' model = PetHealth form_class = PetHealthForm def get(self, request, *args, **kwargs): pet_id = self.kwargs.get('pet_id', None) formset = PetHealthFormset(queryset=PetHealth.objects.filter(pet_id=pet_id)) context = {'pethealthissues': … -
Django Foreign key relation views.py and template html
I have 3 tables related for listing a product with features, i want to list FeatureItem values with for loop in template html file. I ve tried to write a view class but i couldn't succeed. Any Suggestion which approach for views.py and template.html file would be best solution? Thanks. class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() slug = models.SlugField() category = models.ForeignKey(Category, on_delete=models.CASCADE) feature = models.ForeignKey(Feature, on_delete=models.CASCADE) class FeatureItem(models.Model): feature_title = models.CharField(max_length=100) feature_description = models.CharField(max_length=100) feature_id = models.ForeignKey(Feature, on_delete=models.CASCADE) class Feature(models.Model): title = models.CharField(max_length=100) description = models.TextField() -
How can I filter the queryset I use in my ModelChoiceField field?
I have looked at several answers on SO but I haven't found one that address my particular case. I have this ModelForm which I am using in Django admin panel. class AssignInventoryForm(ModelForm): class Meta: model = Driver fields = [] template = forms.ModelChoiceField(queryset=ItemTemplate.objects.all(), empty_label="(Select Template)") template.label = 'Template' def save(self, driver): driver = self.form_action(driver) return driver I would like to be able to filter ItemTemplate like so: ItemTemplate.objects.filter(id=driver.item.id) But obviously driver is not defined at that point of the code. -
How would you write an `is_pdf(path_to_file)` function in Python?
I have a Django project that creates PDFs using Java as a background task. Sometimes the process can take awhile, so the client uses polling like this: The first request starts the build process and returns None. Each subsequent request checks to see if the PDF has been built. If it has been, it returns the PDF. If it hasn't, it returns None again and the client schedules another request to check again in n seconds. The problem I have is that I don't know how to check if the PDF is finished building. The Java process creates the file in stages. If I just check if the PDF exists, then the PDF that gets returned is often invalid, because it is still being built. So, what I need is an is_pdf(path_to_file) function that returns True if the file is a valid PDF and False otherwise. I'd like to do this without a library if possible, but will use a library if necessary. I'm on Linux. -
Upload multiple images with Django Rest Framework
I am trying to upload multiple images from a Vue app to a Django Rest Framework api. Works fine for one image and thanks to this post I made it work for multiple images. But it feels like I missed something and I was wondering how I could improve this code. It feels like hacky code because: the serializer only returns one serialized object (and although it works the serialized object seems odd) I now need to create another serializer for simple get requests with one single image Should I split the images at view level a call a simple serializer with many=True? In create method or perform_create method? Tried a couple of things but without success Thanks for any help you may provide! models.py class Photo(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='photos') owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='photos') image = models.ImageField(upload_to=upload_path) view.py class PhotoViewSet(viewsets.ModelViewSet): serializer_class = PhotoSerializer permission_classes = (IsOwner,) parser_classes = (MultiPartParser, FormParser,) def perform_create(self, serializer): serializer.save(owner=self.request.user) def get_queryset(self): user = self.request.user project = self.request.query_params.get('project') if user.is_authenticated: return Photo.objects.filter(owner=user, project=project) raise PermissionDenied() serializers.py class PhotoSerializer(serializers.ModelSerializer): image = serializers.ListField( child=serializers.ImageField(allow_empty_file=False) ) class Meta: model = Photo fields = ['id', 'image', 'project'] def create(self, validated_data): images = validated_data.pop('image') for image in images: … -
Django 2.2 and Rest Framework 3.11 - partial updating model "owner" field (ForeignKey) with owner's username string instead of pk
Django 2.2 and Rest Framework 3.11 I have an Alarm model. Every alarm instance can optionally have an owner (the standard django User model). I want to be able to partially update (PATCH) an alarm by setting its owner just using his/her username (string) instead of the pk. Right now, I can update an alarm's owner only by using his/her pk. I tried various things, like: override the update() method in the AlarmSerializer class but whenever I use the owner's username string instead of the pk in the PATCH call, I get back: { "owner": [ "Incorrect type. Expected pk value, received str." ] } play with nested serializers and lookup_field but no luck so far. The api call (PATCH) should look like this: url: /api/alarms/{alarm_id}/ Payload: { "owner": "owner_username" } How can I do that? Thanks models.py from django.db import models from django.conf import settings class Alarm(models.Model): """ this class is meant to represent a network alarm (a.k.a. event or ticket) coming from some monitoring system (Zabbix, Nagios, etc.) """ customer = models.CharField(max_length=50) owner = models.ForeignKey( settings.AUTH_USER_MODEL, models.SET_NULL, blank=True, null=True, ) managed = models.BooleanField(default=False, blank=False, verbose_name="Managed ?") device_type = models.CharField(max_length=150) ... serializers.py from django.contrib.auth.models import User from rest_framework import … -
Django permission not working when variable in Axios request
I ran into a really strange error today while setting up restrictions on some of my Vue pages. I'm attempting to make this GET request: try { let actors = await $axios.$get(`/api/v1/users/${loggedInUser.id}/`); return { actors }; } catch (e) { return { actors: [] }; } }, I get back an empty actors [] object, but if I swap out ${loggedInUser.id} with just 1: try { let actors = await $axios.$get(`/api/v1/users/1/`); return { actors }; } catch (e) { return { actors: [] }; } }, I get back the actors: [] object I want. ({{loggedInUser.id}} returns 1 in the template). In Django I have the permission for this user's group set to myapp|user|Can View user Is there some reason that the variable in the Axios call is messing with the perms? I've tried already something like : const id = loggedInUser.id and await $axios.$get(`/api/v1/users/id/`) -
How can I solve my connection error in mysql
I've tried to connect my db. All db settings in settings.py is checked and they are correct. When I run the server, I face an error which is shown below. I searched at internet and I find solutions but all them is working for lower python version. I am using the newest python version. My error is that: System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/base/base.py", line 256, in cursor return self._cursor() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/base/base.py", line 233, in _cursor self.ensure_connection() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/base/base.py", line 197, in connect self.init_connection_state() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 231, in init_connection_state if self.features.is_sql_auto_is_null_enabled: File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res … -
Check if a string has a capital letter in Django?
If I have a string "Hello", how do I check if the string has at least one capital letter and one lowercase letter in Django? -
Django pagination request page given context
Is there a clever way to request a specific page from Django pagination if I know the content I want. e.g. article = Article.objects.get(pk=10) articles = Article.objects.all() paginator = Paginator(articles, 10) paginator.get_page_containing(article) Note. get_page_containing doesn't exist but illustrates what I'd like to do. -
Using primary keys in Django and connecting multiple CBVs in database
I am incredibly new to Django and I'm struggling to get something to work in my project even after extensive research (I've been trying this over and over for about 2 days straight now and I'm sure I'm not finding the right answer because I'm probably not looking for the right question). When I try and add a class based model (Artifacts) to another model in my database (Exhibit), it successfully adds the artifact data to the database but does not show up in the front end as I expect. The Exhibit view is already connected to another view (Case) and that all seems to work fine. model.py: class Artifact(models.Model): exh_ref = models.ForeignKey(Exhibit, on_delete=models.CASCADE, null=True) art_type = models.CharField(max_length=50) description = models.CharField(max_length=100) source = models.TextField(max_length=500) notes = models.TextField(max_length=1000) def get_absolute_url(self): return reverse('exhibit_detail', kwargs={'pk': self.pk}) def __str__(self): return self.art_type + " - " + self.description and class Exhibit(models.Model): case = models.ForeignKey(Case, on_delete=models.CASCADE) exh_ref = models.CharField(max_length=20) exh_pic = models.ImageField(upload_to='exhibit_pics', blank=True, null=True) exh_type = models.CharField(max_length=50) exh_make = models.CharField(max_length=50) exh_model = models.CharField(max_length=50) exh_PIN = models.IntegerField() exh_periph = models.TextField() exh_condtn = models.TextField() special_cat = models.BooleanField(default=False) def get_absolute_url(self): return reverse('case_list') def __str__(self): return self.exh_ref + " Make: " + self.exh_make + " Model: " + self.exh_model Views.py: … -
Why i can't save data in mutiple query?
I read several posts here on this subject, I tried to apply them but I still have this lack of backup in my database and i don't know why. my code : models.py class Noms (models.Model) : n_soza = models.CharField(max_length=20) nom = models.CharField(max_length=100) particule = models.CharField(max_length=20, null=True, blank=True) prenom = models.CharField(max_length=100) .... def __str__ (self): return self.n_soza class Conjoint (models.Model) : c_soza = models.ForeignKey(Noms, on_delete=models.CASCADE, null=True, blank=True) conjoint1 = models.CharField(max_length=100, null=True, blank=True) conjoint2 = models.CharField(max_length=100, null=True, blank=True) conjoint3 = models.CharField(max_length=100, null=True, blank=True) def __str__ (self): return str(self.c_soza) import_xls.py noms = Noms( n_soza=nom_list[0], nom=nom_list[2], particule= nom_list[3], prenom=nom_list[4], .... ) noms.save() conjoint = Conjoint( c_soza = Noms.objects.get(n_soza=nom_list[0]), conjoint1 = nom_list[8], conjoint2 = nom_list[9], conjoint3 = nom_list[10], ) conjoint.save() I have an excel that I acquire as a list and part of the list fields go to a specific location in my database. when I run my code, "Noms" fills up correctly but the "Conjoint" remains completely empty. I tried : conjoint = Conjoint.objects.create( conjoint1=nom_list[8], conjoint2=nom_list[9], conjoint3=nom_list[10] ) conjoint.c_soza = Noms.objects.get(n_soza=nom_list[0]) conjoint.save() but without "conjoint.save()" instancies are create but not for field "c_soza" (it's normal) and with "conjoint.save()" my queryset "Conjoint" is empty I don't know why one works (Noms) and not the … -
ModuleNotFoundError: No module named 'Django-Banking-App.settings' when migrating my Django app to Heroku
I have been trying for two days to deploy my django app to heroku but stuck with the modulenotfound error. Think it might have something to do with my static files but I am not sure. I would forever appreciate someone helping me out with this Here is the error: $ heroku run python manage.py migrate Running python manage.py migrate on ⬢ bb-bank... up, run.4227 (Free) Traceback (most recent call last): File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 82, in wrapped saved_locale = translation.get_language() File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/translation/__init__.py", line 254, in get_language return _trans.get_language() File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/translation/__init__.py", line 57, in __getattr__ if settings.USE_I18N: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'Django-Banking-App.settings' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, … -
Django: add row to formset within template
I have a template that renders a formset where the user can add rows. I added a "add" button for the user to add row. However, I am not very familiar with javascript but clicking the button does not render anything. here is what the javascript code look like: function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + prefix + '-\\d+)'); var replacement = prefix + '-' + ndx; if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); if (el.id) el.id = el.id.replace(id_regex, replacement); if (el.Id) el.Id = el.Id.replace(id_regex, replacement); if (el.Date) el.Date = el.Date.replace(id_regex, replacement); if (el.Quantity) el.Quantity = el.Quantity.replace(id_regex, replacement); if (el.NetAmount) el.NetAmount = el.NetAmount.replace(id_regex, replacement); } function cloneMore(selector, prefix) { var newElement = $(selector).clone(true); var total = $('#id_' + prefix + '-TOTAL_FORMS').val(); newElement.find(':input:not([type=button]):not([type=submit]):not([type=reset])').each(function() { var Id= $(this).attr('Id').replace('-' + (total-1) + '-', '-' + total + '-'); var Date= $(this).attr('Date').replace('-' + (total-1) + '-', '-' + total + '-'); var Quantity= $(this).attr('Quantity').replace('-' + (total-1) + '-', '-' + total + '-'); var NetAmount= $(this).attr('NetAmount').replace('-' + (total-1) + '-', '-' + total + '-'); var id = 'id_' + Id; $(this).attr({'Id': Id, 'id': id, 'Date': Date, 'Quantity': Quantity, 'NetAmount': NetAmount}).val('').removeAttr('checked'); }); newElement.find('label').each(function() { var forValue = $(this).attr('for'); if (forValue) { forValue … -
how to see attributes of User model when creating a model that has one to one relation?
I have a model for example Doctor model that has one to one relation to User model. When creating an instance of Doctor model, django says choose between existing users or create new user by clicking on plus button and create a new one. How to create user and a doctor at one time. I mean how can I show User form and Doctor form in a single page. (in the django administration panel) -
How do I get my handle function to run with the right arguments, (Django, bootstrap script)
Here is my code: class Command(BaseCommand): def handle(self, *args, **options): main_api_header = "https://pokeapi.co/api/v2/" specific_pokemon = f"{main_api_header}pokemon/" for name in pokemon_names: pokemon_stats = f"{specific_pokemon}{name}" response = requests.get(pokemon_stats).json() Pokemon.objects.create( [ Pokemon(name=f"{pokemon_stats}{['name']}"), Pokemon( front_normal_image=f"{pokemon_stats}{['sprites']}{['front_default']}"), Pokemon( front_shiny_image=f"{pokemon_stats}{['sprites']}{['front_shiny']}"), Pokemon( hp=f"{pokemon_stats}{['stats']}{[0]}{['base_stat']}"), Pokemon( attack=f"{pokemon_stats}{['stats']}{[1]}{['base_stat']}"), Pokemon( defense=f"{pokemon_stats}{['stats']}{[2]}{['base_stat']}"), Pokemon( speed=f"{pokemon_stats}{['stats']}{[5]}{['base_stat']}"), Pokemon( ability_One=f"{pokemon_stats}{['abilities']}{[0]}{['ability']}{['name']}"), Pokemon( ability_Two=f"{pokemon_stats}{['abilities']}{[1]}{['ability']}{['name']}"), Pokemon( type_One=f"{pokemon_stats}{['types']}{[0]}{['type']}{['name']}"), Pokemon( base_experience=f"{pokemon_stats}{['base_experience']}") ] ) With the above, I am getting the data I need, but if I run it like this, it says: TypeError: create() takes 1 positional argument but 2 were given (self, *args) gives me: TypeError: handle() got an unexpected keyword argument 'verbosity' (self) gives me: TypeError: handle() got an unexpected keyword argument 'verbosity' I think you get the idea, but I've been trying different arguments, and none of them work. Is it my syntax? Or is this not the way I can make this happen? -
Django: Best Practice for Storing Images (URLField vs ImageField)
There are cases in a project where I'd like to store images on a model. For example: Company Logos Profile Pictures Programming Languages Etc. Recently I've been using AWS S3 for file storage (primarily hosting on Heroku) via ImageField uploads. I feel like there's a better way to store files than what I've been doing. For some things (like for the examples above) I think it would make sense to actually just get an image url from a more publically available url than take up space in my own database. For the experts in the Django community who have built and deployed really professional projects, do you typically store files directly into the Django media folder via ImageField? or do you normally use a URLField and then pull a url from an API or an image link from the web (e.g., go on any Google image, right click and copy then paste image URL)? Hope this makes sense. Thanks in advance! -
Instead of form.save() update entry if already exists
So I'm building an auction site where users can bid on active listings. The lister can then choose to close the listing and all the bids that have been placed will appear and they can choose a winner. After a lot of tweaking, I've managed to get my placebid view set up and I'm quite happy with how it is working. The problem is if a user has already placed a bid, rather than a new bid is placed I want that existing bid to be located and then updated. What is currently happening is when I click to close the bid I am seeing several bids placed all by the same user which isn't very helpful. My functioning views.py looks like this: def placebid(request, id): listing_bid = get_object_or_404(Listing, id=id) highest_bid = Bid.objects.filter(bid_item_id=id).aggregate(Max('bid_input'))['bid_input__max'] or Decimal('0') currentHighest = Bid.objects.filter(bid_item_id=id).aggregate(Max('bid_input'))['bid_input__max'] listing = Listing.objects.get(pk=id) if request.method == "POST": bidform = BidForm(request.POST) if bidform.is_valid() and highest_bid == 0: bid_placed = bidform.cleaned_data['bid_input'] if bid_placed <= listing.start_price: messages.error(request, 'Make sure your bid is greater than the start price') return HttpResponseRedirect(reverse("listing", args=(id,))) else: newbid = bidform.save(commit=False) newbid.bidder = request.user newbid.bid_input = bidform.cleaned_data['bid_input'] newbid.bid_item = listing_bid newbid.time = timezone.now() newbid.save() messages.success(request, 'Bid placed succesfully') return HttpResponseRedirect(reverse("listing", args=(id,))) if … -
How can I change the name(s) of folders in my Django project without destroying its ability to find its own parts?
I'm reading through Two Scoops of Django and the authors note that best practices involve having a config folder and an apps folder. I've been building a Django project for the last few months here & there and want to get in the habit of complying with these practices, but when I change the name of my <project_name> folder (with the wsgi, settings, etc.), Django can't seem to find the contents of the folder anymore. How do I change this folder name and put the project apps into an app folder without breaking the connections they have?