Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Code optimization in a Django when populating field based by a foreign key
I'm searching for some advice on the optimization problem. In this case, I'll use a simple example, I've got these classes: class Genere(models.Model): genere_name = models.CharField(max_length=100) short = models.CharField(max_length=2) class Book(models.Model): name = models.CharField(max_length=100) genere_name = models.ForeignKey(Genere, on_delete=models.SET_NULL, null=True) book_system_id = models.CharField(max_length=100) My field book_system_id describe id number based on genre, for example (in a simplified way): id|name |genere_name|book_system_id 1|Dune |sci-fi |sf001 2|Invisible Man |novel |n001 3|Kindred |sci-fi |sf002 4|Neuromancer |sci-fi |sf003 5|IThings Fall Apart|novel |n002 Now, to populate the field book_system_id in views I use queryset to count elements based by genre, and I'm updating this object (genere_id I'm passing in URL to view function when I create new book object), bellow this is the code snippet: book.save() book.book_system_id = genere.short + str(Book.objects.filter(book_system_id=genere_id).count()) book.save() I'm knowing that this is probably the worst way to do this. That will be really slow when I have a big amount of objects stored in this table. I am wondering how to improvise to do this in the best way; I can add an extra field to store number current order, and when a new object is saved we can get the last number from DB. The second idea was that I can … -
Django Rest Framework - Write for Relational nested Serializers
I am quite new DRF so I am sorry beforehand for any mistake. For example, I have Post model which has Author as foreign key to NewUser model. When I list posts, instead of getting primary key of author, I wanted to get nested object with author details and that is why I created my serializer like this. class PostAuthorSerializer(serializers.ModelSerializer): class Meta: model = NewUser fields = ["id", "email", "user_name"] class PostSerializer(serializers.ModelSerializer): author = PostAuthorSerializer() class Meta: model = Post read_only_fields = ("slug",) fields = ( "id", "title", "author", "excerpt", "content", "status", "slug", ) lookup_field = "slug" However, now I don`t how to /POST a post back. I searched for 2 days but cannot find a proper guide for understand how to do. My main goal is to learn/understand rather than solve the issue so a little bit explanation also would be great! I was really motivated to learn DRF, but I think it lacks a detailed documentation and examples in internet or at least I could not find answer to my question. So, I want to learn 2 ways of posting: Representation is staying this way but I still /POST a post with showing "author":id Representation is staying this … -
Django global/thread objects
Often in Django I want to create and configure some object at startup, and have it available everywhere. For example a third-party API client. So when django starts I want to do this: from some.thirdparty import ThirdPartyClient from django.conf import settings ... my_thirdparty_client = ThirdPartyClient(configstring=settings.SOME_CONFIG_ITEM) And then in a view somewhere I want to do this: from somewhere import my_thirdparty_client def whatever(request): my_thirdparty_client.do_stuff() my_thirdparty_client.do_even_more_stuff() Obviously I understand that I can instantiate the client at the start of the view, but if initalizing the instance is expensive I don't want to do it on every request. What is the idiomatic Django way of creating these kinds of objects that I want to share between views? -
Exception has occurred: ImportError using Django on lines 13 and 23
When I try to rune the [ python manage.py runserver ] to run the server I get an "Exception has occurred: ImportError" and then it will states "Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? File "/Users/tarikzukic/Desktop/DJwebsite/manage.py", line 13, in main raise ImportError( File "/Users/tarikzukic/Desktop/DJwebsite/manage.py", line 22, in main()" Down bellow is the code snippet to be examined. #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DJwebsite.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() -
__str__ returned non-string (type datetime.date)
In Django I have 2 models: in inventory/models.py: class Transaction(models.Model): date = models.DateField() product = models.ForeignKey( Product, on_delete=models.PROTECT) type = models.ForeignKey(TransactionType, on_delete=models.PROTECT) quantity = models.IntegerField() location = models.ForeignKey(Location, on_delete=models.PROTECT) note = models.TextField(null=True, blank=True) def __str__(self) -> str: return f'{self.date}, {self.product.name}, {self.type.name}' And it's working normal. On the other hand. This model in sales/models.py: class Sale(models.Model): date = models.DateField() sale_id = models.IntegerField() sku = models.CharField(max_length=10) product = models.CharField(max_length=100) quantity = models.IntegerField() price = models.FloatField() channel = models.CharField(max_length=100) nooks_payout_schedule = models.ForeignKey( NooksPayoutSchedule, on_delete=models.RESTRICT, blank=True, null=True) def __str__(self) -> str: return f'{self.date}, {self.product}' give me error: __str__ returned non-string (type datetime.date) when trying to see it in admin dashboard. What Ive tried Ive tried to use str(self.date), but it's same error. I can't see the difference between those 2 models yet they are working differently. Do you know why? Full trace: Environment: Request Method: GET Request URL: http://localhost:8000/admin/sales/sale/160/change/ Django Version: 3.1.2 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'sales', 'inventory', 'graphene_django', 'corsheaders', 'django_pivot', 'drf_spectacular', 'django_extensions'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /home/tomo/anaconda3/envs/vdora/lib/python3.8/site-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 19 __str__ returned non-string (type datetime.date) 9 : {% for field in line %} 10 … -
Zero-length delimiter error using python psycopg2 to parse a gzip and insert it into a postgres database
I am attempting to load the contents of a gzip file I created into my postgres database using psycopg2. When I run the script, I get the following error: psycopg2.errors.SyntaxError: zero-length delimited identifier at or near """" (photo of traceback here) I understand that the error is most likely due to the single quotes around the empty string value of 'example', but I don't know the reason this would cause an issue. df = pandas.read_csv(cip_location, header=0, encoding='ISO-8859-1', dtype=str) number_loaded_rows += len(df.index) for index, row in df.iterrows(): row = row.squeeze() cip_code = row['CIPCode'] cip_code = cip_code[cip_code.find('"') + 1:cip_code.rfind('"')] if cip_code.startswith('0'): cip_code = cip_code[1:] cip_title = row['CIPTitle'] cip_def = row['CIPDefinition'] exam_string = row['Examples'] exam_string = exam_string.replace('Examples:', '').replace(' - ', '').replace(' -', '') examples = exam_string cip_codes[cip_code] = { 'code': cip_code, 'title': cip_title, 'definition': cip_def, 'examples': examples } with gzip.GzipFile(ending_location, 'r') as f: bytes = f.read() string = bytes.decode('utf-8') loaded_unis = jsonpickle.decode(string) print('Finished loading in ' + str(time.time() - start_load)) import psycopg2 cnx = psycopg2.connect('host=localhost dbname=postgres user=postgres password=password') count = 0 cursor = cnx.cursor() for d in cip_codes.values(): print('Inserted: %s' % count) print('Trying to insert (%s, "%s", "%s", "%s");' % (d['code'], d['title'], d['definition'], d['examples'])) cursor.execute('CALL InsertCIP(%s, "%s", "%s", "%s");' % (str(d['code']), d['title'].replace('"', "'"), … -
Django custom admin messages
I would like to know how to change the link that appears in the Django admin panel success message and redirect it somewhere else The underlined red part is where the link appears -
Best option for Django Logging accross multiple processes
What is the best option for Django logging if I have info.log and error.log which are being shared across multiple processes? One option would be Multiprocessing, another option would be SocketHandler. Here is the link: https://docs.python.org/3/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes -
Setting a field in django admin that is unchangeable
I'm currently developing a Django app that is used by multiple gas stations. I have a station model with every station having it's own object. Each station will have its own account and can only modify values for their own station. I am making a report to be submitted via Django admin, but I want to set the "station" field to their station name, where they can't view other station names nor change the selection to the other stations. In the admin.py, this is what I have (the report is called Shipment), the field in question is called station. class ShipmentAdmin(admin.ModelAdmin): #readonly_fields = ['station'] <- I thought this would work but it removes the value I set if user = manager def get_form(self, request, obj=None, **kwargs): form = super(ShipmentAdmin, self).get_form(request, obj, **kwargs) if str(request.user) == 'manager': form.base_fields['station'].initial = 'Texaco' else: form.base_fields['station'].initial = 'Exxon' Please let me know if you guys know how to fix this. Basically if the user is manager, set the station value to "Texaco", else set it to "Exxon", and don't allow that field to be changed. Thanks! -
Django grouping and filter, ordering
I am creating small project for our cinema web I have models class Movies(models.Model): name = models.CharField(max_length=100) ... class Projections(models.Model): movie = models.ForeignKey(Movies, on_delete=models.DELETE) startshow = models.DateTimeField() Each Movies have several Projections with different startshow. How can I get Movies grouped by name and ordered by first startshow with all projections for that movie ordered by startshow The list is looking like this: Trools: World Tour 2020-11-10 17:00 2020-11-11 17:00 2020-11-12 17:00 Frozen 2020-11-10 19:00 2020-11-11 19:00 2020-11-12 19:00 Tennet 2020-11-10 21:00 2020-11-11 21:00 2020-11-12 21:00 Please help -
django user defined fields and answer model
Similar to this: User defined fields model in django I am creating a COVID Prescreening system for a school project. Event creators will be able to create forms, which consist of basic questions such as temperature, contact with covid in the last 14 days, etc. as well as provide custom questions for the attendee to answer which I cannot predict. For example, the event creator could ask 2 questions: How are you feeling today? Have you been to a party in the last week? And every attendee for that event would have to fill out these 2 questions in addition to the standard questions. The model for this is: class Event(models.Model): ''' model for an event ''' creator = models.ForeignKey("Account", on_delete=models.CASCADE) title = models.CharField(max_length=200, help_text="Enter a title for this event") start_time = models.DateTimeField() uuid = models.UUIDField(primary_key=True, default=uuid.uuid4) custom_questions = models.ManyToManyField(CustomQuestion) def __str__(self): return f'{self.title} {self.uuid}' Each custom question is essentially a key/value model: class CustomQuestion(models.Model): question = models.CharField(max_length=200) response = models.CharField(max_length=200, blank=True) The user will fill out the COVID Form, which will create an object as such: class CovidScreenData(models.Model): custom_responses = models.ManyToManyField(CustomQuestion) temperature = models.DecimalField(max_digits=5, decimal_places=2, default=98.6) contact_with_covid = models.BooleanField(default=False) This data is embedded in the larger response, which ties … -
Problems trying to save data to a set of online forms
I am developing an application which saves the projects that the administrator assign to the developers, for that I have a project model and a task model, because a project can have multiple tasks, in order to save multiple tasks in a project what I am doing is using a inline formset, but I am having a problem and it is that the data is not saved correctly. This is my view. class ProjectCreateView(LoginRequiredMixin, CreateView): login_url = 'users:login' template_name = 'projects/add_project.html' form_class = ProjectForm success_url = reverse_lazy('projects:project') def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data['formset'] = ProjectFormSet(self.request.POST) else: data['formset'] = ProjectFormSet() return data def form_valid(self, form): context = self.get_context_data() formset = context['formset'] with transaction.atomic(): self.object = form.save() if formset.is_valid(): formset.instance = self.object formset.save() return super().form_valid(form) This is my inline formset: ProjectFormSet = inlineformset_factory( Project, Task, form=TaskForm, fields=['type_task', 'task'], extra=1, can_delete=True, ) This is my template,To use the inline formset I was investigating and they told me that the easiest way is with a jquery library to carry out this process: {% extends "base.html" %} {% load static %} {% block content %} <div class="container"> <div class="card"> <div class="card-content"> <h2>Agregar Proyecto</h2> <div class="col-md-4"> <form method="post"> {% csrf_token %} <div class="input-field … -
Loading Template in Admin Form for Custom Fields
I learned that I can add a custom button in my Admin form by adding it to fields = ["connect"] readonly_fields = ('connect',) def connect(self, obj): return format_html("<button></button>") connect.allow_tags=True connect.short_description = '' However, the html I want to add to the connect is getting out of control. I was wondering if there's a proper (Django-nic) way to move that to a template and load and return the content of the template in the connect function. I can think of reading the content of the template file (open('file.html', 'r')) to read the content, however, I am looking for a suggestion that aligns Django standards (if any). P.S. I also tried creating a view for getting the HTML content of the connect file, but that for some reason doesn't seem to work and feels unnatural to do. -
Can't correctly receive data in Django from Ajax
I wand to receive array data in Django view from jquery/Ajax request but in some reason I cannot correctly do it. This is the piece of js code: var arr = [1, 2]; $.ajax({ type: 'POST', url: '/go/', data: {arr: arr}, success: function (data) { console.log('Success!'); }, }); And this is from Django view: def go(request): if request.method == 'POST': arr = request.POST['arr'] It gives me KeyError: 'arr' If I do print(request.POST) in Django it prints it like this: <QueryDict: {'arr[]': ['1', '2']}>. Some square brackets appear after 'arr' key. Then if I do arr = request.POST['arr[]'] using the key with square brackets it assings arr value 2, so only the last value of the array. Can someone please explain to me why this is happening? -
can i do process with form django python
there is a input and select with options in form tag. i want to get input value and option that entered. and i will do somethings on backend with python that value and option than i will return a result to website. but i dont use to forms.py. how can i do? is it possible? <form action="" method="post"> {% csrf_token %} <input type="text" name="getinputValue"> <select name=""> <option value="1"></option> <option value="2"></option> <option value="3"></option> </select> <button type=""class=""></button> <p>{{result}}</p> </form> -
Why this django formset has stopped saving the content all of a sudden?
I had this view that rendered a form and a formset in the same template: class LearnerUpdateView(LearnerProfileMixin, UpdateView): model = User form_class = UserForm formset_class = LearnerFormSet template_name = "formset_edit_learner.html" success_url = reverse_lazy('pages:home') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) learner = User.objects.get(learner=self.request.user.learner) formset = LearnerFormSet(instance=learner) context["learner_formset"] = formset return context def get_object(self, queryset=None): user = self.request.user return user def post(self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) user = User.objects.get(learner=self.get_object().learner) formsets = LearnerFormSet(self.request.POST, request.FILES, instance=user) if form.is_valid(): for fs in formsets: if fs.is_valid(): # Messages test start messages.success(request, "Profile updated successfully!") # Messages test end fs.save() else: messages.error(request, "It didn't save!") return self.form_valid(form) return self.form_invalid(form) Then i wanted to make it prettier and i added the select2 multicheckbox widget and the django-bootstrap-datepicker-plus Nothing has changed elsewhere, yet when i submit the post it only saves the data relative to User and not to Learner (which relies on the formset) According to the messages, the formset data is not validated, I don't understand why since i didn't touch the substance at all but just the appearance. Being a beginner im probably missing something big, I thank in advance whoever can help me find out the problem. … -
Django dumpdata slow after delete all records in table
I cleared a table using RulesUsed.objects.all().delete() There were about 35,000 records in the table (out of a total database of 45,000 records in all tables). python manage.py dumpdata --exclude auth.permission --exclude contenttypes > db_input.json dumpdata went from about 17 seconds before delete to more than 19 minutes after. I have tried rebuilding the container and loading the data with json file from dumpdata -- so there is no data in the (now) empty table. dumpdata time on the new database is the same -- 19 minutes. python manage.py loaddata --ignorenonexistent /scripts/db_input.json I feel I have misunderstood something and there is some relation slowing things down. I tried clearing from command line with same result of 19 minutes; python manage.py shell from appname.models import RulesUsed RulesUsed.objects.all().delete() The table is a child of another, the model is; class RulesUsed(models.Model): hs_input = models.ForeignKey( hs_input, on_delete=models.CASCADE, related_name='rules_used' ) Rule_Type = models.CharField(max_length=50) Rule = models.CharField(max_length=50) Value = models.CharField(max_length=256) Rule_Comment = models.CharField(max_length=100) class Meta: ordering = ['hs_input','Rule_Type','Rule'] def __str__(self): return f'{self.hs_input} : {self.Rule_Type} : {self.Rule} : {self.Value}' def as_dict(self): return {'id': self.hs_input, 'Rule type' : self.Rule_Type, 'Rule' : self.Rule, 'Value' : self.Value, 'Rule comment' : self.Rule_Comment } The database is Postgres. Python 3.8. Django 2.2.5. Running … -
DRF data not validating nexted object while processed with file data (multipart/form-data)
===========JS========== const data = { "id": "d33e6dca-9152-4ded-96e3-51b2f24423d8", "logo": null, "name": "Company 1", "account": { "id": "d33e6dca-9152-4ded-96e3-51b2f24423d9", "name": "Account Name", "company": "d33e6dca-9152-4ded-96e3-51b2f24423d8" }, "modules": [ { "id": "d33e6dca-9152-4ded-96e3-51b2f24423d1", "name": "Module 1" }, { "id": "d33e6dca-9152-4ded-96e3-51b2f24423d2", "name": "Module 2" }, ], "addresses": [ { "id": "d33e6dca-9152-4ded-96e3-51b2f24423d4", "name": "Address 1", "company": "d33e6dca-9152-4ded-96e3-51b2f24423d8" }, { "id": "d33e6dca-9152-4ded-96e3-51b2f24423d5", "name": "Address 2", "company": "d33e6dca-9152-4ded-96e3-51b2f24423d8" }, ], } let formData = new FormData(); Object.keys(data).map(key=>{ formData.append(key, typeof data[key] === "object" && key!=="logo"? JSON.stringify(data[key]):data[key]) }) const config = { headers: {'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'} }; //axios.put(url, data).then(res => {console.log(".....Response!!! UPDATE")}).catch(err => {console.log(err.response.data)}) axios.put(url, formData, config).then(res => {console.log(".....Response!!! UPDATE")}).catch(err => {console.log(err.response.data)}) ===========Models========== class Address(BaseModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(_('name'), max_length=254, unique=True) company = models.ForeignKey("Company", on_delete=models.CASCADE, related_name="our_addresses") class Module(BaseModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=32) class Account(CompanyBaseModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=32) company = models.OneToOneField("Company", on_delete=models.CASCADE, related_name="account") class Company(BaseModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(_('name'), max_length=254, unique=True) logo = models.ImageField(_('Company Logo'), upload_to=logo_path, storage=PublicMediaStorage(), blank=True, null=True, default=None) addresses = models.ManyToManyField(Address, related_name="companies") modules = models.ManyToManyField(Module) ===========Serializers========== class AddressFormSerializer(serializers.ModelSerializer): id = serializers.UUIDField(read_only=False, required=False, allow_null=True) class Meta: model = Address fields = '__all__' read_only_fields = ['company', ] class ModuleFormSerializer(serializers.ModelSerializer): id = serializers.UUIDField(read_only=False) # required ONLY for … -
How can I use Pathlib for configuring the settings for the project in Django/Faker?
Right now I'm trying to put some fake data in my database using Faker just for the checking purposes. I've created separate file, but before starting to work with Faker itself and data manipulation, I need to configure the settings for the project in this separate file. Before DJANGO==3.1 all people have been using OS module and the following syntax. import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings') But now, when Django versions higher than 3.1 switched from OS module to PATHLIB module, how should I write this code using PATHLIB, not OS? Any help would be helpful! -
Can someone pleas tell me why my form is not valid
I'm stuck. I tried to get this forms.py to work but django never said that the form or things i write into the form at the webpage is valid I thought i made this in a nother app excactly the same way and it works there. class Recipe(models.Model): DIFFICULTY_EASY = 1 DIFFICULTY_MEDIUM = 2 DIFFICULTY_HARD = 3 DIFFICULTIES = ( (DIFFICULTY_EASY, u'einfach'), (DIFFICULTY_MEDIUM, u'normal'), (DIFFICULTY_HARD, u'schwer'), ) EVALUATION_V_SATISFIED = 5 EVALUATION_SATISFIED = 4 EVALUATION_NEUTRAL = 3 EVALUATION_DISSATISFIED = 2 EVALUATION_V_DISSATISFIED = 1 EVALUATION_DUNNO = 0 EVALUATIONS = ( (EVALUATION_V_SATISFIED, u'sehr zufrieden'), (EVALUATION_SATISFIED, u'zufrieden'), (EVALUATION_NEUTRAL, u'neutral'), (EVALUATION_DISSATISFIED, u'unzufrieden'), (EVALUATION_V_DISSATISFIED, u'sehr unzufrieden'), (EVALUATION_DUNNO, u'k. A.'), ) CATEGORY_KOCHEN = 1 CATEGORY_BACKEN = 2 CATEGORIES = ( (CATEGORY_KOCHEN, u'Kochen'), (CATEGORY_BACKEN, u'Backen'), ) author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=u'Autor',related_name="recipe", null=True, default=1) published = models.DateField(default=timezone.now, editable=False) #picture später hinzufügen mit MEDIA_ROOT title = models.CharField(max_length=250) img_url = models.TextField(null=True,blank=True) evaluation = models.SmallIntegerField(choices=EVALUATIONS, default=EVALUATION_NEUTRAL) category = models.SmallIntegerField(choices=CATEGORIES, default=CATEGORY_KOCHEN) subcategory = models.ManyToManyField(SubCategory,verbose_name=u'Unterkategorien') portions = models.PositiveIntegerField() duration_ges = models.PositiveIntegerField(null=True, blank=True) duration_working = models.PositiveIntegerField(null=True, blank=True) duration_cooking = models.PositiveIntegerField(null=True, blank=True) difficulty = models.SmallIntegerField(u'Schwierigkeit', choices=DIFFICULTIES, default=DIFFICULTY_MEDIUM) tags = TaggableManager() class Meta: verbose_name = u'Rezept' verbose_name_plural = u'Rezepte' ordering = ['-published'] def __str__(self): return self.title this is my forms.py class RecipeForm(forms.ModelForm): class Meta: model = Recipe … -
django simple history doesn't show in admin
I have followed the Django-simple-history documentation to display history from the admin page but somehow the history doesn't seem to appear from the admin page. I am using Django version 3.1.2 Here is my admin from django.contrib import admin from simple_history.admin import SimpleHistoryAdmin from .models import Company admin.site.register(Company, SimpleHistoryAdmin) -
display PIL image object in django template
i have edited the user profile photo with PIL library and trying to display the new image in my django template but somehow the image is not displaying ,here is my code in views.py : enterim = Image.open(get_user_model().objects.get(username=request.user).avatar) width, height = im.size newsize = (50, 50) image = im.resize(newsize) buffer = BytesIO() image.save(buffer, "PNG") img_str = buffer.getvalue() return render(request, '../templates/templates_v2/update_location.html', {'updatelocation_form': updatelocation_form,'user_info':user_info,'img_str':img_str}) and this is the img tag in html template: <img src='data:image/png;"+ {{img_str}} + "'/> Thanks in advance -
Django long model text field not loading from database but value exist in database
Django long model text field not loading from database but value exist in database. Databse used is Postgres. Since value is saved to database without issue I think problem is with Django loading afterwards. file_name in database: 2020-11-20-17-06-29_7e3410a8-4aa2-42d1-8225-3152757d433_v2ol-tHLIO_z7kyOPHfVAUHd13mcIE-7gD2OhFWowLc3RTfS1HKxxnPQ.mp3 In model.py class TestModel(models.Model): ... file_name = models.TextField(null=True) ... In view.py test_model = TestModel.objects.get(id=id) print(test_model.file_name) # file_name is None -
How to parse multipart form data by `MultipartParser`
I try to send list of values as a multipart form data by Swagger but I received comma separated array. attachments = "1,2,3,4" How I can send list of ids instead of comma separated array? class ProjectViewSet(UpdateModelMixin, CreateModelMixin): serializer_class = ProjectSerializer parser_classes = (MultiPartParser, ) permission_classes = (IsAuthenticated,) queryset = Project.objects.all() def create(self, request, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): project = serializer.create(serializer.validated_data, user=request.user) return Response(self.get_serializer(project).data) -
CSS from static folder in Django
my first question here. I'm still new to both Django and CSS. I'm trying to use CSS from Static folder in my Django project. It's all at a pretty basic stage. In the 'static' subfolder 'css' I have one main.css file with example code: body{ font-size: 20px; background-color: black; } h1{ color: #008000; } In my settings.py file I have: import os (...) DEBUG = True (...) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] And in my base.html template: {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Shopping List</title> <link rel="stylesheet" type="text/css" href="{% static '/css/main.css' %}"> </head> <body> <h1>TEST</h1> {% block content %} {% endblock %} </body> </html> I've tried moving the css file, changing the view/url, and adding/deleting bootstrap (which alone works). In the end my page just turns light blue-ish. Thanks in advance.