Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSS file is not loaded
I have a simple Django app and I cannot figure out why my CSS file is not loaded. Any help to nail the problem is appreciated! The error that I am getting is this: GET http://127.0.0.1:8000/static/aztracker/css/mystyle.css net::ERR_ABORTED This is where my css file is sitting: myproject/aztracker/static/aztracker/css/mystyle.css code_search_form.html: {% load staticfiles %} {% load static %} <!DOCTYPE html> <head> <meta charset="utf-8" /> <title>Search Code</title> <!-- CUSTOM STYLES --> <link rel="stylesheet" type="text/css" href="{% static 'aztracker/css/mystyle.css' %}"> </head> <body> <form method="POST" action="/search/"> {% csrf_token %} <input type="text" maxlength="2" style="text-transform:uppercase" placeholder="Search Country Code.." name="cc_textfield" id="cc_input"> <button type="submit" id="search_btn">Search</button> </form> </body> mystyle.css: #search_btn { color:red; } setting.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), '/aztracker/static/', ] -
Django saving DateTimeField in a defined Timezone
This has been a really puzzling issue for me, and after several days of digging around online I've been unable to find any documentation that explains how to accomplish this. Hopefully someone here can shed some light! I am building an application for managing events around the world. I'd like to store the event start and end times in the timezone of their specific locale, so that any user (regardless of their location) can see when that event occurs in that locale's specific timezone. For example, an event occurring in the US/Pacific timezone would be displayed to the user as September 19, 2:30PM PDT To accomplish this, I am capturing 3 fields and storing them. My model: from timezone_utils.fields import TimeZoneField from timezone_utils.choices import PRETTY_COMMON_TIMEZONES_CHOICES class Event(models.Model): [...] event_start = models.DateTimeField(blank=False, null=False) event_end = models.DateTimeField(blank=False, null=False) event_tz = TimeZoneField(choices=PRETTY_COMMON_TIMEZONES_CHOICES, default='US/Pacific') My form: from datetimewidget.widgets import DateTimeWidget class EventForm(forms.ModelForm): dateTimeOptions = { 'format': 'dd/mm/yyyy HH:ii P', 'autoclose': True, 'showMeridian' : True } event_start = forms.DateTimeField(widget=DateTimeWidget(options=dateTimeOptions, usel10n=True, bootstrap_version=3)) event_end = forms.DateTimeField(widget=DateTimeWidget(options=dateTimeOptions, usel10n=True, bootstrap_version=3)) class Meta: model = Event fields = ("name","description","registration_goal","registration_sla","registration_url","event_start","event_end","event_tz",) My view: class EventCreateView(CreateView): form_class = EventForm template_name = "events/event_create.html" model = Event def form_valid(self, form): form_tz = pytz_timezone(str(form.cleaned_data['event_tz'])) timezone.activate(form_tz) print("Before: … -
Getting Known Error In Django In model
Model.py from django.db import models class Albums(models.Model): artist = models.CharField(max_lenght=250) Albums_Name = models.CharField(max_lenght = 500) Album_logo = models.CharField(max_lenght = 250) class Songs(models.Model): albums=models.ForeignKey(Albums,on_delete=models.CASCADE) file_type = models.CharField(max_lenght = 500) Song_title = models.CharField(max_lenght = 500) setting.py INSTALLED_APPS = [ 'Ganaana.apps.GanaanaConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] error: Command using:python manage.py makemigrations Ganaana Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Program Files\Python36\lib\site-packages\django-1.11.5- py3.6.egg\django\core\management__init__.py", line 364, in execut e_from_command_line utility.execute() File "C:\Program Files\Python36\lib\site-packages\django-1.11.5- py3.6.egg\django\core\management__init__.py", line 338, in execute django.setup() File "C:\Program Files\Python36\lib\site-packages\django-1.11.5- py3.6.egg\django__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files\Python36\lib\site-packages\django-1.11.5 py3.6.egg\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Program Files\Python36\lib\site-packages\django-1.11.5- py3.6.egg\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files\Python36\lib\importlib__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 978, in _gcd_import File "", line 961, in _find_and_load File "", line 950, in _find_and_load_unlocked File "", line 655, in _load_unlocked File "", line 678, in exec_module File "", line 205, in _call_with_frames_removed File "E:\PythonDjango\website\Ganaana\models.py", line 4, in class Albums(models.Model): File "E:\PythonDjango\website\Ganaana\models.py", line 5, in Albums artist = models.CharField(self,max_lenght = 250) NameError: name 'self' is not defined PS E:\PythonDjango\website> python manage.py makemigration Ganaana Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Program … -
Django celery importing tasks confusion
I'm new to celery and am trying to understand the important of tasks as per http://docs.celeryq.org/en/latest/userguide/tasks.html#task-names my Django setup is as follows project --home ---tasks.py --jobs ---monitoring_check.py --project ---settings.py --monitoring in my settings.py I have apps installed as such INSTALLED_APPS = ( 'home.apps.HomeConfig', 'monitoring.apps.MonitoringConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'easy_thumbnails', 'storages', 'djcelery', ) in tasks.py i have from celery import task from home.jobs import * @task() def aws_monitoring(): return aws_monitoring() @task() def test(a,b): return a + b now I running python manage.py celery worker --loglevel=info and also manage.py shell in shell I do as guided from the celery docs >>> import home.tasks.test Traceback (most recent call last): File "<console>", line 1, in <module> ModuleNotFoundError: No module named 'home.tasks.test'; 'home.tasks' is not a package >>> it fails, if I do >>> from home.tasks import test >>> test.delay(2,3) <AsyncResult: 050f50d5-8d10-482c-b005-eeaf24c0099e> >>> the shell works but the worker fails [2017-09-19 19:28:26,475: ERROR/MainProcess] Received unregistered task of type 'home.tasks.test'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you are using relative imports? Please see http://url for more information. The full contents of the message body was: {'task': 'home.tasks.test', 'id': '050f50d5-8d10-482c-b005-eeaf24c0099e', 'args': … -
Use Django-Storages with IAM Instance Profiles
Django-Storages provides an S3 file storage backend for Django. It lists AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY as required settings. If I am using an AWS Instance Profile to provide S3 access instead of a key pair, how do I configure Django-Storages? -
django and AWS SES service settings 554 error
I set my settings : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'email-smtp.us-west-2.amazonaws.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'I got something from Amazon SES SMTP Settings Create My SMTP Credentials' EMAIL_HOST_PASSWORD = 'I got something from Amazon SES SMTP Settings Create My SMTP Credentials' EMAIL_USE_TLS = True But When i use this to my django-allauth email verification, There comes SMTPDataError at /accounts/email/ (554, b'Message rejected: Email address is not verified. The following identities failed the check in region US-WEST-2: webmaster@localhost') How can i solve this? -
django sets empty value to excluded model fields
Some of the model field are excluded in the django form. when I use form.save(), the existing values of these fields are automatically replaced by empty string. But according to django doc: "Any fields not included in a form by the above logic will not be set by the form’s save() method" Not sure what I am doing wrong. Here is my form and model: class ProfileEditForm(forms.ModelForm): first_name = forms.CharField( required=True, widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'First Name' }) ) last_name = forms.CharField( required=True, widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Last name' }) ) division = forms.ChoiceField( required=True, choices=[(x, x) for x in range(1, 32)], widget=forms.Select(attrs={'class': 'form-control'}) ) city = forms.ChoiceField( required=True, choices=[(x, x) for x in range(1, 32)], widget=forms.Select(attrs={'class': 'form-control'}) ) thana = forms.ChoiceField( required=True, choices=[(x, x) for x in range(1, 32)], widget=forms.Select(attrs={'class': 'form-control'}) ) national_id = forms.CharField( required=False, widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'National ID' }) ) passport_number = forms.CharField( required=True, widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Passport No' }) ) class Meta: model = Profile exclude = ['user', 'activated', 'activation_key', 'slug', 'created'] # fields = ('username', 'email',) # fields = ('first_name', 'last_name', 'division', 'city', 'thana', 'national_id', 'passport_number') def save(self, commit=True): # Save the provided password in hashed format print("in save!") profile = super(ProfileEditForm, … -
Why navbar dosen't use styles on 8000 port?
I have worked on Django framework. And I have a problem with navbar display. If I changing the port for 8001 or any different to 8000 navbar works correctly. I am using standard bootstrap 4 navbars. So, why 8000 port is avoiding bootstrap styles for navbar? -
orm['model'].objects.create(attr=some_value) causes IntegrityError
There's a one-to-one forward relationship between my model Backlog and Entity. Each backlog has an entity. My code tries to create an entity if a backlog is missing one (it doesn't exist in the db), and links it to the backlog missing the entity. new_entity = orm['entities.entity'].objects.create(long_name=entity_name) if entity_short_name is not None and entity_short_name != '': new_entity.name = entity_short_name if entity_url is not None: new_entity.primary_url = entity_url new_entity.save() backlog.entity = new_entity backlog.save() Each entity object has a unique ID called guid. This is the error I get on the code above: django.db.utils.IntegrityError: duplicate key value violates unique constraint "entities_entity_guid_uniq" DETAIL: Key (guid)=(2f49223d-8732-4582-b8a1-7015f515134a) already exists. What could be causing this Integrity Error? Checking if an entity with this guid exists in the db returns None -
Change in Metaclass handling between python 3.4 and 3.5
I have the following structure (for overriding Django model behaviour): class CustomModelBase(models.base.ModelBase): ... class CustomModel(six.with_metaclass(CustomModelBase), models.base.Model): ... where in django.db.models.base, Model is defined as: class Model(six.with_metaclass(ModelBase)): ... So, I have a class CustomModel derived from Model. The metaclass of Model is ModelBase. The derived class has a metaclass of CustomModelBase, which is derived from ModelBase. Under python 3.4.5, this was fine. Running this under python 3.5.3, and I get: class CustomModel(six.with_metaclass(CustomModelBase), models.Model): TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases Which it is...so I'm not sure exactly why it's complaining, and going through the change list from python 3.4 to 3.5 mentions nothing I can see that would change this behaviour (Django version is 1.10.4 and hasn't changed). -
Django - What is different {% static %} and /static/?
I am studying Django. In my settings.py : STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') and when I try to add an image in a template, <img src="{% static "img/person.png" %}"/> <img src="{{ STATIC_URL }}img/person.png" /> <img src="/static/img/person.png" /> All three are shown in the browser as: <img src="/static/img/person.png" /> Then, What is the different between them? If there is no problem, can I use <img src="/static/img/person.png" /> in the template code? -
Django uploading multiple media and saving
I've tried to research and understand on the documentation, but unable to solve my problem. I've a ModelForm which allows me to select and upload multiple files. However, upon saving, only 1 file is saved to my media root folder despite multiple selection. My guess is that the filename for all files in getlist are same (since they're uploaded at the same time), it overwrites each other in a way and end up only saving 1 media. Appreciate the assistance from the community, thank you ! forms.py class FileFieldForm(forms.ModelForm): stuff_image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = Thing fields = ('title', 'description', 'quantity','stuff_image') -- model.py def generate_filename(instance, filename): ext = filename.split('.')[-1] return '' + str(int(time())) + '.' + ext class Thing(models.Model): title = models.CharField(max_length=255) description = models.TextField(blank = True) quantity = models.IntegerField(blank =True) creation_date = models.DateTimeField(auto_now_add=True) stuff_image = models.FileField(upload_to=generate_filename) def __unicode__(self): return self.title class Meta: ordering = ['title'] @receiver(post_delete, sender=Thing) def stuff_post_delete_handler(sender, **kwargs): Thing = kwargs['instance'] storage, path = Thing.stuff_image.storage, Thing.stuff_image.path storage.delete(path) -- view.py def create_stuff(request): if request.method == 'POST': form = FileFieldForm(request.POST, request.FILES) files = request.FILES.getlist('stuff_image') if form.is_valid(): for f in files: form.save() return redirect('list-stuff') else: form = FileFieldForm() return render(request, 'stuffapp/create_stuff.html', {'form': form}) -
'content' cannot be specified for Article model form as it is a non-editable field
I am currently upgrading a Django 1.9 site to use Django 1.10. I would love to upgrade to Django 1.11, but some of the packages the site uses do not yet support it. Either way, I am getting the following error when I go to localhost:8000 FieldError at / 'content' cannot be specified for Article model form as it is a non-editable field Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.10.9 Exception Type: FieldError Exception Value: 'content' cannot be specified for Article model form as it is a non-editable field Exception Location: /xxx-env/lib/python3.6/site-packages/django/forms/models.py in fields_for_model, line 143 The site is running Django CMS 3.4.4, as well as other Aldryn Plugins, all of which are up-to-date using pip install. The code in question is this: if (fields is not None and f.name in fields and (exclude is None or f.name not in exclude)): raise FieldError( "'%s' cannot be specified for %s model form as it is a non-editable field" % ( f.name, model.__name__) ) continue I would love some tips or directions on how I could troubleshoot this. -
Audio Streaming Application in Python/Django Web Framework on AWS
My Application allows me to upload songs from computer and it works fine when I play my tracks for a certain period of time even from different devices. However, songs stop working when I upload more songs or play old uploaded ones. On AWS, the error_log for example says [Tue Sep 19 09:07:08.992382 2017] [:error] [pid 4962] Not Found: /media/3/Clean Bandit - Rockabye ft. Sean Paul & Anne-Marie Official Video.mp3 On the browser like Chrome, I get this error DOMException: The element has no supported sources. Although, I can see the name of the artist, song name and the length of the song, but it doesn't work giving this error (Oh Snap, there was a playback error!)from the JS file. player.js Anyone had the same issue before? -
CreateAPIView with Empty Serializer (no field)
I'm implementing 'Follow' CreateAPIView. FollowCreateAPIView - gets 'logged-in User' from self.request.user - gets 'user's id' who 'Logged-in User' wants to follow (from url) - with the information above, Follow create new data! Here is urls.py url(r'^follow/(?P<user_id>\d+)$', FollowCreateAPIView.as_view(), name="user_profile"), Model class Follow(models.Model): follower = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='follower') following = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='following') created_at = models.DateTimeField(auto_now_add=True) CreateAPIView (I can't get user_id from URL; print(following_id) returns None ) class FollowCreateAPIView(generics.CreateAPIView): queryset = Follow.objects.all() serializer_class = FollowCreateSerializer def perform_create(self, serializer): following_id = self.request.GET.get('user_id', None) print(following_id) <<<<- HERE! following_user = User.objects.filter(id=following_id) serializer.save(follower=self.request.user, following=following_user) Serializer class FollowCreateSerializer(serializers.ModelSerializer): class Meta: model = Follow fields = () Could you fix this problem? And this Like feature seems very common. Do you have any better approach? (if you have...) Thank you so much! -
create a distinct model option in a dropdown using django
I have created this application but the problem I face now is one that has kept me up all night. I want users to be able to see and select only their own categories when they want to create a post. This is part of my codes and additional codes would be provided on request category model class Category(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1,related_name='categories_created') name = models.CharField(max_length = 120) slug = models.SlugField(unique= True) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) post model class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1,related_name='posts_created') #blank=True, null=True) title = models.CharField(max_length = 120) slug = models.SlugField(unique= True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category_created', null= True) addition codes would be provided immediately on request. Thanks View.py in post app def create(request): if not request.user.is_authenticated(): messages.error(request, "Kindly confirm Your mail") #or raise Http404 form = PostForm(request.POST or None, request.FILES or None) user = request.user categories = Category.objects.filter(category_created__user=user).distinct() if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() create_action(request.user, 'Posts', instance) messages.success(request, "Post created") return HttpResponseRedirect(instance.get_absolute_url()) context = { "form": form, } template = 'create.html' return render(request,template,context) Form class PostForm(forms.ModelForm): class Meta: model = Post fields = [ "title", "content", "category", ] html {% if form %} <form method="POST" action="" enctype="multipart/form-data">{% csrf_token %} {{ form|crispy|safe }} <input … -
update multiple fields via filter for a django model
I have defined the following models: class User(models.Model): userid = models.CharField(max_length=26,unique=True) coins = models.IntegerField() points = models.IntegerField() language = models.CharField(max_length=3) Now I would like to run a filter query and update coins and points for all users matching my query: However, I must have gotten something wrong, since field values won't get updated this way (I don't receive error messages): User.objects.filter(language='en', points__gte=score).update(coins='100', points='10') What is the correct way to update the fields for my selection? -
Adding data via Admin not visible in html template until restart server (python manage.py runserver)
Example models.py from django.db import models class Book(models.Model): name = models.CharField(max_length=200) admin.py from django.contrib import admin from .models import Book admin.site.register(Book) views.py class Home(TemplateView): books = Book.objects.all() def get_context_data(self, **kwargs): context ['books'] = self.books index.html {% for b in books %} <h2> {{ b.name}} </h2> {% endfor %} If I add a new Book via Django administration I need to restart the server in order for the new value to be visible How can I auto-refresh the view if any data is changed via djano admin without having to restart server (python manage.py runserver) All help would be appreciated as I'm stuck can i use refresh_from_db in the view ? -
C:\Python27\python.exe - The FastCGI process exited unexpectedly
I'm trying to install a Django (version 1.9) application in IIS (version 8.5). I've followed several tutorials but I always get this error: HTTP Error 500.0 - Internal Server Error C:\Python27\python.exe - The FastCGI process exited unexpectedly I've tried to run the application in my command line and everything works fine so its some configuration that I'm missing. I've already gave my project permissions for IIS_IUSRS. I've got the following handler configurated: <add name="Django Handler" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python27\python.exe|C:\inetpub\wwwroot\ansr_bk\manage.py fcgi --pythonpath C:\inetpub\wwwroot\ansr_bk\wfastcgi.py --settings ansr.settings" resourceType="Unspecified" requireAccess="Script" /> Do you know which configuration I'm missing? Thanks :) -
Django populating values in the same record whose foreign key has been set before
i have this django app a part of whose models.py is shown below: class user(models.Model): uid=models.IntegerField(unique=True,default=0) uname=models.CharField(max_length=50) email=models.EmailField() password=models.CharField(max_length=20) def __unicode__(self): return u"{} {}".format(self.uid,self.uname) class Meta: db_table="user" class userresp(models.Model): uid=models.ForeignKey(user,to_field='uid',null=True,blank=True,on_delete=models.CASCADE) resp=models.CharField(max_length=20) datetime=models.DateTimeField(default=timezone.now) def __unicode__(self): return u"{} {}".format(self.uid,self.datetime) class Meta: db_table="userresp" a part of view.py def plogin(request): if request.method=='POST': username=request.POST['username'] password=request.POST['password'] if username and password: username_exist=user.objects.filter(uname=username,password=password) if not username_exist: return render(request,'student/loginfailed.html',) else: username_exist=user.objects.get(uname=username,password=password) userid=user.objects.values_list('uid', flat=True).get(uname=username) rep=userresp() rep.uid=user.objects.get(uid=userid) rep.save() return render(request, 'student/loggedin.html', {'username': username_exist,'userid':userid}) return render(request,'student/plogin.html',) here i have populated the "uid" foreign key field of "userresp" table as i login the user. now i want to populate the "resp" field in another view after this happens. But this "resp" has to be in the same row that has "uid" which i entered previously in "plogin" view. How can i do it in this view? def mainpage2(request): if request.method=='POST': response = request.POST.get("audio1", None) if response in ["1"]: return HttpResponse("you are right!") else: return HttpResponse("Oops! you got it wrong.") else: return HttpResponse("invalid user") //audio1 are a set of radio buttons in my template -
user.is_authenticated in Users List
Despite many searches, I have not found any solution to my problem : Content for authenticated user does not display on the view displaying users list. My app has a view displaying a list of users: views.py def UserListView(request): user = User.objects.all().order_by('-date_joined') return render(request, 'accounts/user_list.html', {"user": user}) A base template with this navbar: base.html <nav class="navbar"> <ul> {% if user.is_authenticated %} <li><a class="nav-item" href={% url 'logout' %}>Logout</a></li> {% else %} <li><a class="nav-item" href={% url 'login' %}>Login</a></li> {% endif %} </ul> </nav> Even if the user is logged, the menu displays Login instead of Logout. I am suspecting a problem of context? Any advice is welcome :) -
Let user create celery periodic tasks
I want to ask you about celery and redis usage in django app. I'm learning about celery for about 2 days and I'm still a bit confused :/ I've installed celery and redis and it's working just fine. My problem is, that I want user to create, update and suspend periodic tasks. I've read this article - http://kindshofer.net/2016/11/19/dynamically_adding_a_periodic_task_to_celery.html and this question - How to dynamically add / remove periodic tasks to Celery (celerybeat) a loooot of other articles, but not as useful as these two), and it appears, that I need to use django-celery. I thought, that it's a great option, but then I've read (here --> https://github.com/celery/django-celery ), that django-celery uses django result backend (it means - my db, rigth? And I want to use redis!). Is it possible to use django-celery with redis? Maybe with django-celery I don't need to use redis? Maybe there's some other way of letting user create periodic tasks? I really need my periodic tasks to be fast and lightweight, because there will be a lot of them and they need to be flawless (and that's why I thought that I need to push them somewhere else). I'd really appreciate any suggestions! -
Django form with multiple model instances
I am creating a Django app where, from a page I can add 8 images (with 8 input fields, one of them is the main image of the post) to a Blog Post. I have these 2 models: class Pictures(models.Model): file_path = models.ImageField(upload_to='posts/', null=True) post = models.ForeignKey(BlogPost, on_delete=models.CASCADE, null=True) class BlogPost(models.Model): title = models.CharField(max_length=100) And the following Forms: class CratePostForm(forms.Form): title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) class CreatePicturesPostForm(forms.Form): main_image = forms.FileField() image_1 = forms.FileField(required=False) image_2 = forms.FileField(required=False) image_3 = forms.FileField(required=False) image_4 = forms.FileField(required=False) image_5 = forms.FileField(required=False) image_6 = forms.FileField(required=False) image_7 = forms.FileField(required=False) I can easily create a Post with different form doing something like this: pictures_form = CreatePicturesPostForm(request.POST, request.FILES) and saving every image as a new Picture object with a foreign key to the Post. The problem is happening when I want to create the edit page of the form, I have to load in the form the previous uploaded images and show them to the user. I wanted to do something like the following: pictures_form = EditPicturesAdForm(instance=pictures) but this instance should be a single object, while I have many instances of Pictures object coming from the same model. Any idea? -
Field with null=True and blank=True serializer None error in JS
I have a model class Question(models.Model): question = models.TextField(blank=False, null=False) question_image = models.ImageField(blank=True, null=True, upload_to='question') option = ArrayField(models.CharField(max_length=50, blank=False, null=False),size=4) answer = models.IntegerField(choices=((1,'1'),(2,'2'),(3,'3'),(4,'4'))) description = models.TextField(blank=True,null=True ) coressponding serializer is class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ('id', 'question', 'question_image', 'option', 'answer', 'description') read_only_fields = ('id',) The serialized object I get is {'description': None, 'id': 1, 'answer': 3, 'question_image': None, 'option': ['27', '28', '29', '31'], 'question': 'How many states are there in India?'} I want to use this JSON in javascript which gives me error None is not defined. What is the simplest and clean solution to change None to null in serializer? -
Django FormSet Management Form issue
I know that this issue has been raised many many, I have read all the other answer relating to that problem but I still cannot figure out how to make it work. I even followed that tuto (https://godjango.com/9-forms-part-4-formsets/) on a very simple form but I still get the this famous error : ['ManagementForm data is missing or has been tampered with'] models.py: class InviteForm2(forms.Form): """ Form for member email invite """ Email = forms.EmailField( widget=forms.EmailInput(attrs={ 'placeholder': "Member's mail", }), required=False) class BaseLinkFormSet(BaseFormSet): def clean(self): """ Adds validation to check that no two links have the same anchor or URL and that all links have both an anchor and URL. """ if any(self.errors): return Email = [] duplicates = False for form in self.forms: if form.cleaned_data: email = form.cleaned_data['Email'] # Check that no two links have the same anchor or URL if email: if email in emails: duplicates = True emails.append(email) if duplicates: raise forms.ValidationError( 'You cannot provide twice the same mail', code='duplicate_links' ) views.py: def printmail2(request): InviteFormSet = formset_factory(InviteForm2, formset=BaseLinkFormSet, extra=7) if request.method == 'POST': formset = InviteFormSet(request.POST, prefix='pfix') if(formset.is_valid()): for i in formset: a = i.value() print(a) print("success") else: print("form not valid") else: formset = InviteForm2() return render(request,'invite2.html', {'formset':formset}) …