Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.IntegrityError: null value in column of relation violates not-null constraint
I'm trying to add several existing facility objects to a lead object whenever i create a new lead object using a json field serializer. When i print out the "assigned_facilities_id" it returns: "none" but it is in the json data I'm sending to the serializer. Does anyone know why this is happening? This is the error I'm getting when i try to create a lead: django.db.utils.IntegrityError: null value in column "assigned_facilities_id" of relation "users_leadfacilityassign" violates not-null constraint DETAIL: Failing row contains (78, null, null, 159). File "/app/users/api/views.py", line 53, in perform_create serializer.save(agent=self.request.user) File "/usr/local/lib/python3.9/site-packages/rest_framework/serializers.py", line 205, in save self.instance = self.create(validated_data) File "/app/users/api/serializers.py", line 252, in create instance.leadfacility.create(assigned_facilities_id=assigned_facilities.get('facility_id'), datetime=assigned_facilities.get('datetime')) class LeadUpdateSerializer(serializers.ModelSerializer): is_owner = serializers.SerializerMethodField() assigned_facilities = serializers.JSONField(required=False, allow_null=True, write_only=True) class Meta: model = Lead fields = ( "id", "first_name", "last_name", "is_owner", "assigned_facilities", ) read_only_fields = ("id", "is_owner") def get_is_owner(self, obj): user = self.context["request"].user return obj.agent == user def create(self, validated_data): assigned_facilities = validated_data.pop("assigned_facilities") instance = Lead.objects.create(**validated_data) for item in assigned_facilities: instance.leadfacility.create(assigned_facilities_id=assigned_facilities.get('facility_id'), datetime=assigned_facilities.get('datetime')) return instance json { "assigned_facilities": [{ "facility_id": "1", "datetime": "2018-12-19 09:26:03.478039" }, { "facility_id": "1", "datetime": "2019-12-19 08:26:03.478039" } ] } models.py class Facility(models.Model): name = models.CharField(max_length=150, null=True, blank=False) def __str__(self): return self.name class Lead(models.Model): first_name = models.CharField(max_length=40, … -
Custom Headers are missing in the request received in Django
I'm working on a ReactJS/Django project where I need to send few custom headers to Django from React. Issue: Custom headers are missing when the request comes into Django Custom Headers Added are - Token and User-Type React code below. export async function post(url, requestBody = {}, auth_req=true) { const token = window.sessionStorage.getItem("Token"); const user_type = window.sessionStorage.getItem("User-Type"); console.log("Header Data : ",token, user_type); try{ const requestOptions = { method: 'POST', headers: { "Content-Type": 'application/json', "Token" : auth_req ? token : null, "User-Type" : auth_req ? user_type : null }, body: requestBody ? JSON.stringify(requestBody) : "{}" }; console.log("POST URL is : ", url) console.log("Request is : ", requestOptions) const response = await fetch(url, requestOptions); let json_response = await response.json() console.log("Response is : ",json_response) return json_response }catch(e){ console.log("Service Failed: ", e) return { status: false, messages: ["Service Failed. Please try after sometime."] } } } Console Output: - As per the console logs, all the information are sent out correctly But when it comes to Django, its all empty. In Django, I verify the custom header info in my middleware and below is the code def __call__(self, request): headers = request.headers token = headers.get('Token') user_type = headers.get('User-Type') print(headers) print("** Token : {} | … -
Django migration column does not exist ProgrammingError error when running tests
I run into an error when testing a django application with pytest, more specifically when running tests if I have done a migration that removes a field used in an earlier migration. Doing so outside of tests gives no error. To reproduce: models.py from django.db import models class TestModel(models.Model): # We started with this field, but now longer need it # original_text = models.CharField(max_length=255) # We added this field and then moved over to it new_text = models.CharField(max_length=511) migrations/0001_initial.py from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='TestModel', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('original_text', models.CharField(max_length=255)), ], ), ] migrations/0002_testmodel_new_text.py from django.db import migrations, models def move_text_to_other_field_and_append_new(apps, schema_editor): TestModel = apps.get_model("sample", "TestModel") for test_model in TestModel.objects.all(): test_model.new_text = test_model.original_text + " new" test_model.save() class Migration(migrations.Migration): dependencies = [ ('sample', '0001_initial'), ] operations = [ migrations.AddField( model_name='testmodel', name='new_text', field=models.CharField(default='', max_length=511), preserve_default=False, ), migrations.RunPython(move_text_to_other_field_and_append_new, migrations.RunPython.noop) ] migrations/0003_remove_testmodel_original_text.py from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('sample', '0002_testmodel_new_text'), ] operations = [ migrations.RemoveField( model_name='testmodel', name='original_text', ), ] tests.py from django.test import TestCase class TestModelTestCase(TestCase): def test_example(self): self.assertEqual(1, 1) This is a minimal setup to reproduce the error. Now when running pipenv run … -
The comprehensive of Python and its future? [closed]
Python is a programming language that can be used in many areas such as AI, creating a Web Server, and writing tools that run in many industries (DevOps, Hacking, etc.). So is Python comprehensive and what does its future look like? I have used Python to create products for problems in different fields (AI, Web Server, script tool). So is it possible to use Python for everything? -
Django app dissapears from Django Admin site when I add apps.py file
I'm working with Django 3.2 and trying to configure correctly the AppsConfig subclass of apps.py in order to avoid duplicate apps names when initzialing the project. The context is the following. I have in my INSTALLED_APPS two apps whose names are equal although their paths not: INSTALLED_APPS = [ ... 'first_app.myapp', 'second_app.myapp' ] To avoid the error shown below (and according to the documentation), I need to create an apps.py file subclassing AppConfig in at least one of the apps called myapp. I've decided to create that file in the second one, second_app.myapp. django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: myapp The app.py in second_app.myapp module looks like as follows: from django.apps import AppConfig class MySecondAppConfig(AppConfig): name = "second_app.myapp" label = "my_second_app" And in the __init__.py I've added: default_app_config = 'second_app.myapp.apps.MySecondAppConfig' My admin.py looks like: from django.contrib import admin from .models import MyModel class MySecondAppAdminModel(admin.ModelAdmin): list_display = ('attr_1', 'attr_2') admin.site.register(MyModel, MySecondAppAdminModel) When I start the project all works OK and I can use that model information, views called from second_app.myapp also work OK. The problem comes when I access to the admin site (http://localhost:8000/admin), where only appears the first_app.myapp admin form instead of both. Can you help me? Thanks in advance. -
How to include information from a request in linkify in Tables2 in Django - using to populate a many-to-many relationship
I have a many to many relationship and am setting up a way to add a new relationship from a detail view of model1. I have set it up so I have a url mapped to create the relationship given pk(model1)/url/pk(model2). This is just a function that adds the many to many relationship, and redirects back to the detailview of model1. I have this working in a function based aproach, but would like to be able to display the list of available ModelB records using Tables2, but am strugling to figure out how to add the pk(model1) to linkify in the table as the table is based on model2 and this is not part of the definition of model2. Maybe there is a whole different way of aproaching this problem which is a better aproach? (lots of documentation and tutorials about setting up and dealing with a many-to-many relationship, but couldn't find any examples of doing this part other than in the shell) Here is what I have: models.py class Dmsesite(models.Model): ... class Job(models.Model): dmsesite = models.ManyToManyField(Dmsesite) ... urls.py path('<int:pk>/add_job/', views.DmsesiteAddJob, name='dmsesite_add_job'), path('<int:dmsesite_pk>/add_job_to_site/<int:job_pk>', views.DmsesiteAddJobToSite, name='dmsesite_add_job_to_site'), views.py class DmseSiteAddJobListView(PermissionRequiredMixin, SingleTableMixin, FilterView): permission_required = 'dmsesites.view_dmsesite' redirect_field_name = 'dashboard' table_class = DmsesiteJobTable filterset_class … -
FATAL: password authentication failed for user 'xxx' error when migrating to a postgresql db in RDS
I am trying to migrate to a PostgreSQL db in RDS from Django. The db was set up successfully but when I run python3 manage.py migrate I keep getting the error 'FATAL: password authentication failed for user'. The user name that it mentions is not the master username from RDS which is the same as my USER in settings. I have a .env file with the USER, ENGINE, PASSWORD etc that is being read correctly apart from the fact that it is not referencing the USER. It is referencing the username I use to log onto the computer which I also used when I set up a superuser in the venv. I have tried logging out from superuser which did nothing. I also tried deactivating the venv which seemed to solve the authentication issue though obviously none of the modules within the venv uploaded so I got errors from that. I tried changing the password in RDS but it is still trying to connect using the wrong user. I also tried making a new venv but still got the same error. The NAME in settings is set to postgres. Has anyone else had this issue? Any advice much appreciated. -
Django sessions cookie and login_required
I have a Django app where I don’t want to use database and session engine is signed cookies. I create a request.session[‘user’]=ssouser when a user is successfully logged in via SSO. However when I use login_required decorator user is not detected as logged in. Do I have to create my own way to check it from cookie and how can I do it ? Thanks -
Django how do you AutoComplete a ForeignKey Input field using Crispy Forms
Looking for any assistance as i just can't seem to get this. I have a 'category' field that has approx 4000 categories in it, sourced from my table "Category". When a user inputs their details they choose from the category field. This works fine as a drop down list but takes ages to scroll. I'd rather have the field as text entry so when they start typing, for example 'plum', then every category with 'plum' somewhere in it appears in the list so they can choose. They must also choose from list and not enter rubbish. Can anyone assist? Here's how it works just now with the drop down list, is there any way to change this (category1) to an autocomplete field? I've looked at django autocomplete_light but got nowhere. Models.py: class Category(models.Model): details = models.CharField(max_length=250, blank=True, null=True) def __str__(self): return self.details class Search(models.Model): name = models.CharField(max_length=200) email = models.CharField(max_length=200) category1 = models.ForeignKey('Category', blank=True, null=True, on_delete=models.CASCADE, related_name='category') Forms.py: class NewSearch(forms.ModelForm): class Meta: model = Search fields = ['name', 'email', 'category1'] def __init__(self, *args, **kwargs): super(NewSearch, self).__init__(*args, **kwargs) self.fields['category1'] = forms.ModelChoiceField(queryset=Category.objects.all().order_by('details')) self.helper = FormHelper() self.helper.form_show_labels = False Views.py: @csrf_exempt def search(request): my_form = NewSearch() if request.method == 'POST': my_form = NewSearch(request.POST) … -
How to initialise date time object from date time (string) in NetSuite (User Event - server side script)
Here, I have string date_time as "2022-10-27T01:35:48.354z" , the same and time i need to initialise as date time object with same and time as in given string. I have tried new Date() in javascript, format.parse, format.format in suitescript, moment library file too, but still could not get solution. Please help me on this. I will be thankful. -
how can I throw all the categories into the header
In my header there is a slide bar where you can immediately go to the selected category of the book. The question is, how can I throw all the categories into the header without throwing the variable with all the categories into all the views. Header, available on all pages of the site. For example, ruby has helpers where I can define a variable once, as it will be available in all controllers, and from this in all views. Сan i run {% for i in sometags %} or no ? I expect minimum duplication of code. I tried to do it through template tags. -
Is there a way to pass a string which contain muliple delimiter in Django?
Info: I want to make a queryset where i have pass a string. A string contain multiple delimiter , like a separator. I just want to know it is possible to pass a string with muliple delimiter and filter out the video which are match with the strings? def videosfilter(request): ''' videos filter ''' videos = Video.objects.filter(title__icontains='python programming,django framework') return videos -
Django Chat App - Capturing value from URL
I tried to create a simple Django Chat App. There is no login system. Whenever a user(e.g. John) tries to create a message, it stores under 'messageroom' I tried to pass the username 'John' value in the URL but somehow it is not creating a message as expected. Here is my code Urls.py : urlpatterns = [ path('admin/', admin.site.urls), path('',views.home,name='home'), path('checkview',views.checkview,name='checkview'), path('messageroom/<str:room_name>/<str:username>',views.messageroom,name='messageroom'), ] Models.py class Room(models.Model): roomname = models.CharField(max_length=1000) class Message(models.Model): messagetext = models.CharField(max_length=10000) username = models.CharField(max_length=1000) datetime = models.DateTimeField(default=datetime.now,blank=True) messageroom = models.CharField(max_length=1000) Views.py def home(request): return render(request,'home.html',{}) def checkview(request): room_name=request.POST.get('room_name') username = request.POST.get('username') Roomexists = Room.objects.filter(roomname=room_name) if Roomexists.exists(): return redirect('messageroom/'+room_name+'/'+username) else: newroom = Room(roomname=room_name) newroom.save() return redirect('messageroom/'+room_name+'/'+username) def messageroom(request,room_name,username): if request.method == "POST": messagetext = request.POST.get('message') newmessage = Message(messagetext=messagetext,messageroom=room_name,username=username) newmessage.save() listmessages = Message.objects.filter(messageroom=room_name) return render(request, 'room.html', {'listmessages':listmessages,'room_name':room_name,'username':username}) Room.html <form id="post-form2" method="POST" action="messageroom"> {% csrf_token %} <input type="text" name="message" id="message" width="100px" /> <input type="submit" value="Send"> </form> I want to create messages under the user which should be there on the URL. -
How to use DFR filters SearchFilter in django function based view?
I have a django view function. This function is using to list data. I want to add DRF SearchFilter in this function. SearchFilter works with ListAPIView succesfully but I couldn't make it works with function view. I tried the code below. I give search_fields list as view paramater but it returns back my queryset. Thanks for your help. def masterListView(request): master_queryset = Master.objects.all() search_filter = filters.SearchFilter() mastersearch_queryset = search_filter.filter_queryset(request, master_queryset) master_ser = MasterSerailizer(mastersearch_queryset, many=True) ... Note: filter_queryset takes, request, queryset and view parameters. I didn't notice what is function expected as view. In SearcFilter class definition there is a comment that said Search fields are obtained from the view, but the request is always passed to this method. Sub-classes can override this method to dynamically change the search fields based on request content. -
Django-Autocomplete-Light: Multiple fields mutually excluding selections
I is Django Autocomplete Light (DAL) to great effect. It works wonderfully and has done for years on a site of mine. I wanted recently to improve on little aspect of our implementation of it, namely to prevent multiple selection of the same value in a group of DAL widgets. Specifically we built a dynamic Django form with which a list of players can be submitted. There is a template row in a table, and every time you add a player, it copies the template row and adjusts the id of the widgets in the copy as needed and inserts it into the DOM (as a new row). This all works a charm. With the DAL widgets rendered in a select element with a name and id in the form of model-n-field which the POST handler validates wonderfully and all is good. These DAL widgets appear to render in the general form of: <select id="id_model-n-field" name="model-n-field" class="ModelChoiceField select2-hidden-accessible" data-autocomplete-light-language="en" data-autocomplete-light-url="/autocomplete/model/field" data-autocomplete-light-function="select2" data-select2-id="id_model-n-field" aria-hidden="true"> <option value="" selected="" data-select2-id="13">---------</option> </select> <span class="select2 select2-container select2-container--bootstrap select2-container--below select2-container--focus select2-container--open" dir="ltr" data-select2-id="12" style="width: 426.906px;"> <span class="selection"> <span class="select2-selection select2-selection--single ModelChoiceField" role="combobox" aria-haspopup="true" aria-expanded="true" tabindex="2" aria-disabled="false" aria-labelledby="select2-id_model-n-field-container" aria-owns="select2-id_model-n-field-results"> <span class="select2-selection__rendered" id="select2-id_model-n-field-container" role="textbox" aria-readonly="true"> <span class="select2-selection__placeholder"> </span> … -
Django Admin - Many to Many Field - Display only selected options
Basically i have two models: collection and Custom_object. A custom_object has some general fields (id, name, value) and could be anything. A collection is like a group of many custom objects, realized as many to many field in django. E.g. collection collection_id collection_name ... custom_objects = models.ManyToManyField(to=Custom_object, related_name="related_co") I want to inspect on the admin site some collections, mainly which custom_objects are selected. The Problem here is that i have more than 20k different custom_objects, which takes a while to load the page and then the next problem is to scroll all 20k entries down to find some selected custom_objects. For each collection are only about 10-20 custom_objects selected, not so much. I want to see only the selected options, its not important for me to see see or select one of the other 19.980 options, because selection and deselection is done by cronjob. Its just important to see selected custom_objects. Any idea how to do this e.g. in admin.py for the collection model class ? Thanks a lot for bringing in your expertise and knowledge! I tried something like this: class collection(admin.ModelAdmin): search_fields = ['name', 'id'] def formfield_for_manytomany(self, db_field, request, **kwargs): kwargs["queryset"] = collection.objects.filter( ??? ) ? return super(collection, … -
How to upload image from react native to Django along with name and email
Does any body know how we send image,email and name from React Native to Django </Text> <View style={{flexDirection:'row',}}> <View style={{marginTop:20,}}> <Text style={{borderWidth:1, backgroundColor:'white', width:50, height:50, borderRadius:40, textAlign:'center', alignContent:'center', justifyContent:'center', alignSelf:'center' ,alignItems:'center',paddingTop:14,}}> 1 </Text> <Text style={{fontSize:19,color:'white',textAlign:'center', alignContent:'center', justifyContent:'center', alignSelf:'center' ,alignItems:'center',paddingTop:14,}}> Photos </Text> <Text style={{color:'white',fontSize:7,textAlign:'center', alignContent:'center', justifyContent:'center', alignSelf:'center' ,alignItems:'center',paddingTop:14,}}> Enter all the information about {"\n"} your car </Text> </View> <View style={{paddingLeft:10,marginTop:20,}}> <Text style={{borderWidth:1, backgroundColor:'white', width:50, height:50, borderRadius:40, textAlign:'center', alignContent:'center', justifyContent:'center', alignSelf:'center' ,alignItems:'center',paddingTop:14,}}> 2 </Text> <Text style={{fontSize:19,color:'white',textAlign:'center', alignContent:'center', justifyContent:'center', alignSelf:'center' ,alignItems:'center',paddingTop:14,}}> Photos </Text> <Text style={{color:'white',fontSize:7,textAlign:'center', alignContent:'center', justifyContent:'center', alignSelf:'center' ,alignItems:'center',paddingTop:14,}}> Upload pictures of your {"\n"} cars from all angles </Text> </View> <View style={{paddingLeft:10,marginTop:20,}}> <Text style={{borderWidth:1, backgroundColor:'white', width:50, height:50, borderRadius:40, textAlign:'center', alignContent:'center', justifyContent:'center', alignSelf:'center' ,alignItems:'center',paddingTop:14,}}> 3 </Text> <Text style={{fontSize:19,color:'white',textAlign:'center', alignContent:'center', justifyContent:'center', alignSelf:'center' ,alignItems:'center',paddingTop:14,}}> Photos </Text> <Text style={{color:'white',fontSize:7,textAlign:'center', alignContent:'center', justifyContent:'center', alignSelf:'center' ,alignItems:'center',paddingTop:14,}}> Add the price at which you {"\n"} are will to sell the car </Text> </View> </View> </View> </ImageBackground> <View style={{backgroundColor:'green', width:'100%', height:400, marginTop:120,}}> <Text style={{alignSelf:'center', fontSize:25, color:'white',}}> Car Information </Text> <TextInput style={styles.inputstyle} label = "City" value = {city} mode = "outlined" onChangeText= {Text => setcity(Text) } /> <TextInput style={styles.inputstyle} label = "Car Information" value = {carinfo} mode = "outlined" onChangeText= {Text => setcarinfo(Text) } /> <TextInput style={styles.inputstyle} label = "Milage" value = {milage} mode … -
Django .cleaned_data.get()
class UserRegistration: """This class doesn't inherit to any parent class.""" def register(request): if request.method == 'POST': """Then takes the POST data.""" form = UserCreationForm(request.POST) # Check the data from the form if it's valid if form.is_valid(): username = form.cleaned_data.get('username') where's that username coming from that has been passed as a parameter in the cleaned_data? -
Run External Python script outside the django project through html button
I am trying to run python script through html button but I am getting the following error. I don't know why. kindly help to get rid off it. The error is: module 'sys' has no attribute 'execute' views.py: from subprocess import run, PIPE from django.shortcuts import render import requests import sys def external(request): out = run([sys.execute,'/home/abc/Documents/test.py'], shell=False, stdout=PIPE) print(out) return render(request, 'home.html', {{'data1': out}}) home.html: <html> <head> <title> RUN PYTHON SCRIPT </title> </head> <body> <form action='{% url "external" %}' method="post"> {% csrf_token %} <input type="submit" name="btn" value="start analyse" id="toggle1" onclick="location.href='{% url 'external' %}'" /> </form> </body> </html> urls.py: path('external/', views.external, name="external"), Even the button doesn't execute the test.py python script and gives the following error: module 'sys' has no object 'execute' in views.py kindly help me to run script through html button -
Django doesn't save record to database
I have a view with one button that redirect to another view that is supposed to save data to a database HTML view 1 <a href="upd_dab_seq"> <button type="button" class="btn btn-dark">Update DB</button> </a> Python view 2 def upd_dab_seq(request): # clean DB Sequencies.objects.all().delete() arr = os.listdir('main_app/sequencies') for i in range(len(arr)): # Insert in the database Sequencies(name = arr[i], description = '').save() print(arr[i]) return redirect('/settings') MODEL from django.db import models class Sequencies(models.Model): name = models.CharField(max_length=30) description = models.TextField() URLS urlpatterns = [ path("settings", views.settings, name="settings"), path("upd_dab_seq", views.upd_dab_seq, name="upd_dab_seq"), ] Now, everything seems to work but no records have been saved on the databse. The print() works and I got no error. I've tried Sequencies.objects.create(name = arr[i], description = ' ') as well but nothing happens I'm using the default SQLite DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } -
Problem with django foreign key auth_user
I am developping a HR project with django. I want to save the information which user modified my person model the last time. Therefore, my model.py contains lines like these: class person(models.Model): modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name='person_modified', verbose_name='Modifiziert von') In admin.py, I save the modified_by information like this def save_model(self, request, obj, form, change): obj.modified_by = request.user However, my class person is also my authentication user model, as defined in settings.py AUTH_USER_MODEL = 'person.person' I assume that in my database, modified_by directly refers to my AUTH_USER_MODEL. But the database looks like this: "person_person_modified_by_id_5069ed54_fk_auth_user_id" FOREIGN KEY (modified_by_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED auth_user is not filled meaningfully so that I cannot save any information as it crashes when filling the "modified_by" field. Does anyone have a good idea how to solve this problem? I tried changing the ForeignKey to 'self' but this didn't work. Thanks and cheers, Philipp -
Remove Internal Link option
I know this question has been asked before, but the only given solution was hacky and doesn't fully work, at least not with the current version of wagtail. I want to remove the Internal Link option from the page chooser, as for some reason, using the Internal Link just returns "None" meaning it doesn't work. I can link internally manually with the external link option anyway, so I have tried removing it however I can. I have hiding it using CSS and defaulting to external link using JS and hooks, but that doesn't work (any time I create a new link it goes back to defaulting to internal link). I have now also tried replacing wagtailadmin/chooser/_link_types.html by making my own inside templates as the documentation seems to suggest, but that doesn't seem to work either as the old template still seems to be in use... -
How to check if policy ID contains four number exact match in Django
Asking for help on how to detect existing policy that has exact match on filename. Example : GIRL4876S is still passed even though BOY4876T already exists. def policy_exists(policy_id, ref=None): filename = policy_id + '.xml' try: if ref: repo.get_contents('policies/' + filename, ref) else: # no ref default = previous release commit repo.get_contents('policies/' + filename, prev_release_commit()) return True except UnknownObjectException: return False def submit_new(submissions): errors = [] for sub in submissions: if sub.attrib['defect_type'] != 'NV': errors.append('Invalid defect type: ' + sub.attrib['defect_type']) if gh.policy_exists(sub.attrib['policy_id']): errors.append('Existing Policy: ' + sub.attrib['policy_id']) # if sub.attrib['policy_id'].endswith('T'): # errors.append('Terminate policy ' + sub.attrib['policy_id'] + ' is not allowed for this submission type') branch_name = 'NEW-' + ','.join(str(s.attrib['policy_id']) for s in submissions) return branch_name, errors since both GIRL4876S and BOY4876T has 4876 on them. The function should append error. -
v-if and v-else directives to show created and updated dates
I have a django model which stores created and updated date on my front end i have a header called Date in my vue headers i am displaying the created date but i need to display the updated date under the same header when an object is updated. i have same date called row.updated_date_formatted if this is none i need to display created_date else i need to display updated date <template slot="row" slot-scope="{ row, index }"> <td v-text="row.created_date_formatted"> </td> </template> -
Save uploaded InMemoryUploadedFile as tempfile to disk in Django
I'm saving a POST uploaded file to disk by using a technique described here: How to copy InMemoryUploadedFile object to disk from django.core.files.storage import default_storage from django.core.files.base import ContentFile from django.conf import settings data = request.FILES['image'] path = default_storage.save('tmp/%s' % filename, ContentFile(data.read())) tmp_file = os.path.join(settings.MEDIA_ROOT, path) The file does get uploaded and stored at the specified location. However, the content is garbled. It's an image - and when I look at the stored file, I see, the characters are not the same and the image file is damaged. The filesize, however, is the same as the original. I guess, I need to do some conversion before saving the file, but how/which...?