Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Many-to-Many update, Django signals
I have these models (simplified): class Product(TimeStampedModel): product_id = models.AutoField(primary_key=True, ) shop = models.ForeignKey('Shop', related_name='products', to_field='shop_name', on_delete=models.CASCADE) category = models.ForeignKey('Category', related_name='products', to_field='category_name', on_delete=models.SET_NULL) brand = models.ForeignKey('Brand', related_name='products', to_field='brand_name', on_delete=models.CASCADE) class Brand(models.Model): brand_name = models.CharField(max_length=50) shops = models.ManyToManyField('Shop', related_name='shops') categories = models.ManyToManyField('Category', related_name='categories') class Category(models.Model): category_name = models.CharField(max_length=128) shops = models.ManyToManyField('Shop') class Shop(models.Model): shop_name = models.CharField(max_length=30) In admin I am trying manually to change a Category for bunch of selected Products (I have a custom function for that). But here I see 2 problems: 1) Must be updated M2M relation in Brand->Category, if there was no Brand with this Category. 2) Must be updated M2M relation in Category->Shop, if there was not this selected Category in the Shop. How to do this in the best way? I know that this might be some kind of Django signals use, specially m2m_changed, but I can't understand who is emitter of the signal, and who is receiver, and how to update multiple tables after change in 1 table. -
Django Switching from User to AbstractUser
I'm working with a legacy code base (currently running Django 1.8, almost done being migrated to 1.11) which incorrectly made a User model that inherits from django.contrib.auth.models.User instead of django.contrib.auth.models.AbstractUser This has database lookup implications, and prevents me from taking the irritating-but-possible path towards retroactively changing the project's settings.AUTH_USER_MODEL. This is the custom user model in question: from django.contrib.auth.models import User as AuthUser class User(AuthUser): def is_published(self): return True def save(self, *args, **kwargs): self.is_staff = True super(User, self).save(*args, **kwargs) When I change the object inheritance from AuthUser to django.contrib.auth.models.AbstractUser and try to run migrations, I get the following errors: SystemCheckError: System check identified some issues: ERRORS: accounts.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. accounts.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'User.user_permissions'. auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'User.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change … -
Front-end in 2018: If I use Django, what do I need Vue.js for (as examples)...?
Please bear with me, as I have NO front-end experience whatsoever... I read lots of articles, discussions, etc. etc. but NONE really explains "the building blocks"... therefore, I apologize for asking a stupid question in advance, but here it is: What "tool" is the the most integrated to display Python data analytics based on data in a database on a dynamic website, in accordance with certain selections that the user makes (e.g., "show me A" vs. "show me A and B together", or "show me the mean" instead of "the median"). More specifically, I have Python data analytics code, together with a database (things are stored in the DB, if the user has a specific question, the Python code will extract something from the DB, do some calculation, create some nice graphs, and show the user the results). I want it to be a dynamic web site or web application (even those terms are not clearly defined anymore). It appears I can use Vue.js, or I can use Django, but for some reason, it always seems to tell me I should be using BOTH... WHYT would I need both? What does "a Django" do that "a Vue.js" does not do? … -
Running django cron within AWS ubuntu docker
I'm having problem with running cron jobs (Django, AWS ubuntu docker). I placed next code in etc/cron.d/run_cron SHELL=/bin/bash PATH=/sbin:/bin:/usr/sbin:/usr/bin MAILTO="" HOME=/ */5 * * * * root source /root/.bashrc && /root/base_service_container/api-service/manage.py runcrons --force "boilerplate_draj.cron.SampleCron" >> /root/SampleCron.log I know that cron works, because I can see the output in SampleCron.log file, but it does not add records to the database. Cron job logs in django admin stay empty. But if I run source /root/.bashrc && /root/base_service_container/api-service/manage.py runcrons --force "boilerplate_draj.cron.SampleCron" >> /root/SampleCron.log manually the entry is created in database. What am I doing wrong? -
Django getting request get params in Class
I have a following function: class getAjaxView(BaseDatatableView): model = Roles columns = model.columns order_columns = model.order_columns max_display_length = model.max_display_length def render_column(self, row, column): if column == 'id': return '<input type="checkbox" name="cid[]" value="{{$id}}" class="cid_checkbox flat"/>' else: return super(getAjaxView, self).render_column(row, column) Here the model (Eg: Roles) should come from a GET parameter value and it will change dynamically. How can I access this GET parameter before the function definitions and initialise the variables ? -
Field/columns mismatch in custom django User authentication model
I've been having some problems in the process of writing my own User model and authentication backend. The reason I make a new question is that even though there are many other ones with similar problems, none I could find was relevant enough to mine, and everything else I tried failed. First, the desired outcome: The user logs in with email and password (as opposed to username and password as per Django default). The user specifies a username which does not need to be unique. Instead, the unicity of the user is tested on the email, which has to be unique across all users as it is used for login. To avoid publicly representing users with their email but still allow non-unique usernames, a numeric identifier of five digits is calculated every time the user changes their username (including at creation). The couple username + identifier must be unique. The problem: In the database, I notice the username is placed under the "email" column and vice-versa. As a result, if I try to register a second user with the same username, Django complains even though the email is different. The code: This is the relevant part of my user model: … -
Django Test Debug - Flyway is not found in PyDev's Pythonpath
Trying to configure debugging of a python test script within my Django project in PyDev. When running the debug, the console says: Could not find flyway in your PATH. Please download the command line tool from https://flywaydb.org/documentation/commandline/ even though Flyway seems to be properly configured: The test never starts, Eclipse perspective never gets switched to Debug and execution never stops at the breakpoint: Here's the full Eclipse console contents: pydev debugger: starting (pid: 98747) setup_test_environment({}) {'clean_schema': False, 'traceback': False, 'output_info': False, 'verbosity': 1, 'create_database': False, 'do_flyway_migrations': False, 'drop_existing': True, 'no_color': False, 'pythonpath': None, u'skip_checks': True, 'settings': None} _drop_test_db test_vpdb DROP DATABASE "test_vpdb" {'clean_schema': False, 'traceback': False, 'output_info': False, 'verbosity': 1, 'create_database': True, 'do_flyway_migrations': False, 'drop_existing': False, 'no_color': False, 'pythonpath': None, u'skip_checks': True, 'settings': None} _create_test_db test_vpadb CREATE DATABASE "test_vpadb" OWNER postgres {'clean_schema': False, 'traceback': False, 'output_info': False, 'verbosity': 1, 'create_database': False, 'do_flyway_migrations': True, 'drop_existing': False, 'no_color': False, 'pythonpath': None, u'skip_checks': True, 'settings': None} Could not find flyway in your PATH. Please download the command line tool from https://flywaydb.org/documentation/commandline/ What can I be missing? How does one run a Django test script in PyDev? Thank you in advance. -
Get object but cannot access properties
When retrieving a user object set up as below: class User(models.Model): """ User model """ id = models.UUIDField(primary_key=True, default=uuid4, editable=False) email = models.EmailField(max_length=255, null=True, default=None) password = models.CharField(max_length=255, null=True, default=None) ACCOUNT_CHOICE_UNSET = 0 ACCOUNT_CHOICE_BRAND = 1 ACCOUNT_CHOICE_CREATOR = 2 ACCOUNT_CHOICE_AGENCY = 3 ACCOUNT_CHOICES = ( (ACCOUNT_CHOICE_UNSET, 'Unset'), (ACCOUNT_CHOICE_BRAND, 'Brand'), (ACCOUNT_CHOICE_CREATOR, 'Creator'), (ACCOUNT_CHOICE_AGENCY, 'Agency'), ) account_type = models.IntegerField(choices=ACCOUNT_CHOICES, default=ACCOUNT_CHOICE_UNSET) class Meta: verbose_name_plural = "Users" def __str__(self): return "%s" % self.email In the following manner: try: user = User.objects.get(email=request.data['email']) except User.DoesNotExist: response_details = { 'message': "Invalid email address.", 'code': "400", 'status': HTTP_400_BAD_REQUEST } return Response(response_details, status=response_details['status']) Why can I only view the email property when trying to print it out? I need to be able to access the account_type property as well. if user: print(user) -
How to add datepicker and timepicker to Django forms.SplitDateTimeField?
I have a form that splits the date and time from a datetime field in the model. class MyForm(forms.ModelForm): class Meta: model = MyModel fields = ('name', 'description', 'start', 'end',) widgets = { 'start': forms.SplitDateTimeWidget(), 'end': forms.SplitDateTimeWidget(), } How can I add a datepicker and timepicker to each separate input box that is rendered? Setting: 'start': forms.SplitDateTimeWidget(attrs={'type': 'date'}) makes both inputs datepicker but I need the second one to be a timepicker.. I am using Django 2.0, bootstrap and crispy forms -
Nginx config for django app in kubernetes cluster
I'm having difficulty creating an nginx configuration file for a django app deployed in kubernetes. Nginx and app are two separate containers within the same cluster. From what I understand containers can communicate with each other via 127.0.0.1:XX and via hostnames. I'm using minikube for this. My app container is built from this file: apiVersion: extensions/v1beta1 kind: Deployment metadata: name: website labels: name: website spec: template: metadata: labels: name: website spec: containers: - name: website image: killabien/web ports: - containerPort: 8000 --- apiVersion: v1 kind: Service metadata: name: website labels: name: website spec: type: LoadBalancer ports: - port: 8000 targetPort: 8000 selector: name: website And nginx from this: apiVersion: v1 kind: Service metadata: name: frontend spec: ports: - protocol: TCP port: 80 targetPort: 80 selector: app: website tier: frontend type: LoadBalancer --- apiVersion: extensions/v1beta1 kind: Deployment metadata: name: frontend spec: template: metadata: labels: app: website tier: frontend spec: containers: - image: killabien/nginx name: nginx I can access the application itself(served without static files) but when I try to reach nginx I get 502 Bad Gateway error. Here is the nginx config file: upstream website { server 127.0.0.1:8000; } server { listen 80; location /static { alias /www/davidbien/static; } location / … -
Insert div if background image exists
I have an object that may or may not have an image associated with it. If it does have an image, I want the image to be used as the background-image for a div. If it does not have an image, I don't want the div to show. I'm using django templates. Here's what I tried so far: {% if post.image %} <div class="background"></div> {% endif %} And the CSS is: .background{ position: absolute; z-index: -1; background-image: url("{{ post.image.url }}"); width: 100%; height: 400px; } The images are stored in AWS S3. What's happening is that if the object doesn't have an image, the page doesn't load and tells me that the 'image' attribute has no file associated with it. What can I do? -
Pass a dictionary with error message and print the error message
I'm trying to validate a form from backend itself. I've made a dictionary of error message: error_messages = { 'error': form.errors, } and passed it to HttpResponse: return HttpResponse(json.dumps(error_messages)) i want to show the error message when the form is invalid. This is my updaterow view: def updaterow(request, id): item = get_object_or_404(Studentapp, id=id) if request.method == "POST": form = EntryForm(request.POST, instance=item) error_messages = { 'error': form.errors, } if form.is_valid(): post = form.save(commit=False) post.save() return HttpResponse(json.dumps(error_messages)) else: form = EntryForm() return HttpResponseRedirect(reverse('studentapp:index'), id) return render(request, 'index.html',{'form':form}) I have to make changes in else part also so kindly help me with that too. -
Recursion error in Django template when including a second HTML template
Hello. I'm just finnishing my first Django project, and it's going great. However, I have a little issue when including a HTML template in another. I'd like to have a single file with all form errors display, so I don't have to write the same thing again and again in each form. So, I have this little template: my_app/form_error_messages.html: {% if form.non_field_errors %} <div class="col-sm-12 alert alert-danger alert-dismissable fade show" role="alert"> <button type="button" class="close" data-dismiss="alert" > <span>&times;</span> </button> <div class=""> {{ form.non_field_errors }} </div> </div> {% endif %} {% for field in form.hidden_fields %} {% if field.errors %} <div class="col-sm-12 alert alert-danger alert-dismissable fade show" role="alert"> <button type="button" class="close" data-dismiss="alert" > <span>&times;</span> </button> <div class=""> {{ field.label }}: {{ field.errors }} </div> </div> {% endif %} {% endfor %} {% for field in form.visible_fields %} {% if field.errors %} <div class="col-sm-12 alert alert-danger alert-dismissable fade show" role="alert"> <button type="button" class="close" data-dismiss="alert" > <span>&times;</span> </button> <div class=""> {{ field.label }}: {{ field.errors }} </div> </div> {% endif %} {% endfor %} And on each of my other templates, I have something like this: my_app/other_template_file.html {% extends "base.html" %} <!-- All HTML templates extends from this file --> {% block "my_block" %} … -
Django Deployment on DigitalOcean, Supervisor not working properly
When I run gunicorn --workers 3 --bind 0.0.0.0:8030 config.wsgi, everything works well and I get following: [2018-04-30 14:10:59 +0000] [26681] [INFO] Starting gunicorn 19.7.1 [2018-04-30 14:10:59 +0000] [26681] [INFO] Listening at: http://0.0.0.0:8030 (26681) [2018-04-30 14:10:59 +0000] [26681] [INFO] Using worker: sync [2018-04-30 14:10:59 +0000] [26684] [INFO] Booting worker with pid: 26684 [2018-04-30 14:10:59 +0000] [26685] [INFO] Booting worker with pid: 26685 [2018-04-30 14:10:59 +0000] [26686] [INFO] Booting worker with pid: 26686 The settings used is config.settings.production which is confirmed by non-debug error pages and also by typing echo $DJANGO_SETTINGS_MODULE and getting config.settings.production in return from the same directory. I have used this reference to deploy my app on Digital Ocean and as mentioned in its VI step, I have supervisord configurations as follows: [program:addemic] command=/home/dev/virtualenvs/addemic/bin/gunicorn --workers 3 --bind 0.0.0.0:8030 config.wsgi directory=/home/dev/Addemic/src autostart=true autorestart=true stderr_logfile=/var/log/addemic.err.log stdout_logfile=/var/log/addemic.out.log Running sudo supervisorctl start addemic from the same directory, however, runs the application using local settings (config.settings.local) insted of desired production settings (config.settings.production). This is the first time I am trying to deploy a Django application. Any hints or help to resolve this problem will be highly appreciated. -
How do i have to use normalize_email on django before validating it and saving it?
i'm curious about this matter, how could i be able to make my app to normalize the email and case of the matter normalize username so both can't be repite with a case insensitive issue, any tips would very appreciate, my django version is the 1.11.2 and my python version is 3.6.4, either way thank you. -
Django 2: using apps as a microservice?
This builds off a previous question Decoupling Django, where I ask how would decouples seemingly interwoven applications (the question is now closed). While I still find that question and answers there informative, it seems that I don't actually know how to integrate external apps in Django in practice. I have made multi-app projects, but all of those apps were made by myself. So I made a simple example app which does it's one thing and one thing well (within the confines of being a demo); namely, it is a feedback app which adds to the bottom of the page a tab to open a form where users can submit feedback about the page to the developers. There is a model that stores relative information (rating, feedback, email, and the page) and this model is integrated into the admin page. Unlike a user model, which may affect page content, backend logic, etc this app is pretty decoupled. In theory the html just needs to be added to the base.html of the new project... but this might mess up the urls.py. So my question is as follows: How would I convert this demo project into something that can be easily integrated into … -
Bcrypt with django login
I am having an issue with setting up my login system. First off, when a user registers, I store their hashed password in the database which is generated in the front end like this: var hashedPassword = bcrypt.hashSync(password, bcrypt.genSaltSync(10)); Now when the user logs in, I need to compare a plaintext password against the hashed password in order to get a result. Afterwards I want to return a message with the token and user.accountType in the response. How do I go about doing this? This is my code so far: class UserLogin(views.APIView): """ User Login HTTP POST """ def post(self, request): if not request.data: response_details = { 'message': "Please provide a valid email and password.", 'code': "400", 'status': HTTP_400_BAD_REQUEST } return Response(response_details, status=response_details['status']) try: user = User.objects.get(email=request.data['email']) except User.DoesNotExist: response_details = { 'message': "Invalid email address.", 'code': "400", 'status': HTTP_400_BAD_REQUEST } return Response(response_details, status=response_details['status']) if user: print(user) # if bcrypt.hashpw(request.data['password'], user['password']): # print("It matches") # else: # print("It does not match") payload = { 'email': user.email, 'account_type': user.account_type } jwt_token = {'token': jwt.encode(payload, "SECRET_KEY")} response_details = { 'data': json.dumps(jwt_token), 'message': 'Login success!', 'code': "200", 'status': HTTP_200_OK } return Response(response_details, status=response_details['status']) else: response_details = { 'message': "Invalid username and password combination.", … -
DJANGO: create a button that allows to download a zip file
I've created a little site with django: i'd like to insert a button that allows the user to download a zip file. How could i make it? I can't find the right tool to do that. -
Bulkcreate in Django with pandas from django shell
I'm trying to run a script from the django shell to bulkcreate a database from a csv. I'm not sure if my pandas is wrong or my django model is to blame. I'm using Python3 and I'm not sure if that affects things either. I'm getting pretty lost in the django docs I want to import this csv from kaggle: https://www.kaggle.com/weil41/flights/data script: import pandas as pd data = pd.read_csv('data/Flights.csv', sep=',') # year,month,day,dep_time,dep_delay,arr_time,arr_delay,cancelled, # carrier,tailnum,flight,origin,dest,air_time,distance,hour,min flights = [ Flight( year = tmp_data.ix[row]['year'], month = tmp_data.ix[row]['month'], day = tmp_data.ix[row]['day'], dep_time = tmp_data.ix[row]['dep_time'], dep_delay = tmp_data.ix[row]['dep_delay'], arr_time = tmp_data.ix[row]['arr_time'], arr_delay = tmp_data.ix[row]['arr_delay'], cancelled = tmp_data.ix[row]['cancelled'], carrier = tmp_data.ix[row]['carrier'], tailnum = tmp_data.ix[row]['tailnum'], flight = tmp_data.ix[row]['flight'], origin = tmp_data.ix[row]['origin'], dest = tmp_data.ix[row]['dest'], air_time = tmp_data.ix[row]['air_time'], distance = tmp_data.ix[row]['distance'], hour = tmp_data.ix[row]['hour'], min = tmp_data.ix[row]['min'], ) for row in data['ID'] ] Flight.objects.bulk_create(flights) models.py from django.db import models # year,month,day,dep_time,dep_delay,arr_time,arr_delay,cancelled, # carrier,tailnum,flight,origin,dest,air_time,distance,hour,min class Flight(models.Model): year = models.CharField(max_length=100, default='') month = models.CharField(max_length=100, default='') day = models.CharField(max_length=100, default='') dep_time = models.CharField(max_length=100, default='') arr_time = models.CharField(max_length=100, default='') arr_delay = models.CharField(max_length=100, default='') cancelled = models.CharField(max_length=100, default='') carrier = models.CharField(max_length=100, default='') tailnum = models.CharField(max_length=100, default='') flight = models.CharField(max_length=100, default='') origin = models.CharField(max_length=100, default='') dest = models.CharField(max_length=100, default='') air_time = models.CharField(max_length=100, default='') distance … -
Django Ajax Modify avatar failed
I'm trying to use Django Ajax to Modify user's avatar, but it doesn't work.There is no any error information, just doesn't work. Here is my form in template: <form class="clearfix" id="jsAvatarForm" enctype="multipart/form-data" autocomplete="off" method="post" action="{% url 'users:image_upload' %}" target='frameFile'> <img id="avatarShow" src="{{ MEDIA_URL }}{{ request.user.image }}"/> <input type="file" name="image" id="avatarUp" class=""/> <button type="submit">Modify Avatar</button> {% csrf_token %} </form> Here is my Ajax: $("#jsAvatarForm").submit(function(){ var image = $("#avatarShow").val() $.ajax({ cache: false, type: "POST", url:"{% url 'users:image_upload' %}", data:{'user_pk':{{ user.pk }}, 'image':image}, async: true, beforeSend:function(xhr, settings){ xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}"); }, success: function(data) { if(data.status == 'fail'){ if(data.msg == '用户未登录'){ window.location.href="login"; }else{ alert(data.msg) } }else if(data.status == 'success'){ window.location.reload();//refresh current page. } }, }); return false; }); Here is views.py: class UploadImageView(LoginRequiredMixin, View): def post(self, request): user_pk = request.POST.get("user_pk", 0) image = request.FILES.get('image') user_change = UserProfile() user_change.id = user_pk user_change.image = image user_change.save return HttpResponse('ok') Actually I also have a forms.py but I don't know how to use it with ajax: class UploadImageForm(forms.ModelForm): class Meta: model = UserProfile fields = ['image'] Here is my user model, note:I have rewrote my own USER: class UserProfile(AbstractUser): image = models.ImageField(upload_to="image/%Y/%m", default="image/default.png", max_length=100,verbose_name='头像') class Meta: verbose_name = "用户信息" verbose_name_plural = verbose_name def __str__(self): return self.username Any … -
Facebook-Style multiple profile functionality for a Django Social Media Website
I am in the process of creating a "Facebook-Style" multiple profile functionality for a Django Social Media Website. With "Facebook-Style" I mean that, what is important is to design a system that allows users to interact with the Website using more than one profile tied to the same User Account, and choose which profile they want to be identified with from drop down menu in Facebook Fashion. I am confident that I can manage all the code by myself, so I am not asking you to write a lot of stuff of course! That's my job. What would be deeply appreciated is some wise words from experienced Django Developers,that could positively influence the design of the new functionality I need to implement. Because let's admit it. At the moment I think the model design is pretty flawed. Let me explain. So far, a user can only create one profile, that extends the Django User Model, in the tipical manner, like so: from django.contrib.auth.models import User class SiteContributor(models.Model): """ The Model for a Contributor Instance. Extends the Django User Model to provide extra details for the profile. """ user = models.ForeignKey(User, related_name="contributor") gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default='F') avatar = ImageField(upload_to='avatars', blank=True, … -
It is possible to use "choices" of a table column for the below code segment in Django?
I want to use the select method option from a table column please help me by providing any hints T_Semester = (('FIRST SEMESTER','First Semester'),('SECOND SEMESTER','Second Semester')) # Each field must be minimum two field and minimum one charecter T_Year = (('FIRST YEAR','First Year'),('SECOND YEAR','Second Year'),('THIRD YEAR','Third Year'),('FOURTH YEAR','Fourth Year')) T_Dept = (('CSE','CSE'),('EEE','EEE'),('HUM','HUM'),('CE','CE'),('ME','ME')) class Subject(models.Model): course_no = models.CharField(max_length=20) title = models.CharField(max_length=200) year = models.CharField(max_length=100,choices=T_Year) semester = models.CharField(max_length=100,choices=T_Semester) -
djangocms: move data from deprecated cmsplugin-filer-*-plugins to djangocms-*-plugins
Since the cmsplugin-filer-*-plugins are deprecated with django 3.5, I need a way to keep my plugins with moving them to the newer djangocms-*-plugins. I am using the cmsplugin-filer plugins FilerFile, FilerFolder and FilerImage. Also I got a custom plugin which inherits from FilerImage. I need to move those to the newer djangocms-file-file, djangocms-file-folder and djangocms-picture without losing my plugins / data. -
Django CSS relative paths not working in Amazon S3
I'm really stuck on something and would really appreciate if someone could help me. I've spent hours on SO and tried all the suggestions but still doesn't work. Basically I'm using S3 for my static files for a website. Most of the images are referenced in the templates but I notice that every single referenced image or file (fonts in particular) are not working. I've made all the files public in S3 and can access them with the public links. This is my setting.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'app/static'), ] AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' AWS_STORAGE_BUCKET_NAME = 'abc-bucket' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) DEFAULT_FILE_STORAGE = 'app.storage_backends.MediaStorage' I've remove the AWS access and secret keys for this post. The fonts.css contains the following; @font-face { font-family: 'rt-icons-2'; src:url('../../fonts/rt-icons-23dab.eot?wz19bt'); src:url('../../fonts/rt-icons-2d41d.eot?#iefixwz19bt') format('embedded-opentype'), url('../../fonts/rt-icons-23dab.ttf?wz19bt') format('truetype'), url('../../fonts/rt-icons-23dab.woff?wz19bt') format('woff'), url('../../fonts/rt-icons-23dab.svg?wz19bt#rt-icons-2') format('svg'); font-weight: normal; font-style: normal; } and the AWS folder structure is; static - content - css - fonts.css - fonts - rt-icons-23dab.eot - rt-icons-2d41d.eot - rt-icons-23dab.ttf - rt-icons-23dab.woff - rt-icons-23dab.svg I know the CSS is working as all the styling is fine so the fonts.css is … -
Additional forms in formsets not added in request.post
I have a formset initially made of two forms but I added the ability to add extra (identical) forms as explained in Dynamically adding a form to a Django formset with Ajax (NB: I have no experience with javascript, I take the snippet as it is) However, when I post data with a third form filled (thus an extra field), data corresponding to this form do not appear in request.POST, as it is detected as invalid: [{}, {}, {'user': ['This field is required.'], 'score': ['This field is required.']}] <QueryDict: {'csrfmiddlewaretoken': ['VAsOnDSxZMhIti2CjwmHrlAYk8IALUzpHz9A8Snhi6xnHqvk5BbLceAJU4anAXe4'], 'form-1-score': ['0'], 'form-1-user': ['4'], 'form-TOTAL_FORMS': ['3'], 'form-0-score': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-INITIAL_FORMS': ['0'], 'form-0-user': ['1'], 'form-MIN_NUM_FORMS': ['0']}> {'user': <User: neon29>, 'score': 0} {'user': <User: John>, 'score': 0} invalid form Here are the relevant code snippet: game_create.html: {% extends "base.html" %} {% block content %} <h1>Enregistrement d'un nouveau match!</h1> <div id="form_set"> <form action="/nouveau_match/" method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <ul> {% for field in form %} <li> {{ field.label_tag }} {{ field }} </li> {% endfor %} </ul> {% endfor %} <input type="submit" value="Sauvegarder"/> </form> </div> <input type="button" id="add_more" value="Ajouter un joueurs"> <div id="empty_form" style="display:none"> <table class='no_error'> {{ formset.empty_form.as_p }} </table> </div> <script> $('#add_more').click(function …