Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
(Django)(Important)(Short) How can I roll back DB that changed in unwanted way after renaming fields in models.py
I have a question in Django. I renamed fields in my models.py on my editor. After renaming the name of fields, I made makemigrations and did 'migrate' on cmd. After 'migrate', I checked my database on DB broswer and I found that not only the name of fields changed, but the data of the fields also changed into the name of fields I just changed as just lowercased. i.e.) Original name of field was ingredient and I changed the name to Essential_ingredient. I checked DB and turned out that all of data for the column of changed field is essential_field like picture. Database after renaming fields I posted this question on FB page and one said I can roll back(revert) by doing "migrate ". So I tried it and then it turned out that the field came back correctly to purposedly migrated file, but the data of the field still haven't changed back yet. Database after reverting migrations I guess this problem happened because, when I renamed fields, I renamed two of them at the same time. I saw a comment on stackoverflow that I'm supposed rename the one field at a time, but this was after I'd changed names … -
How to change the name of objects in Django admin?
I am using this code: def __str__(self): return self.title But the names of each objects are still not changing: What to do? -
Django raw query syntax and parameters
What is the correct syntax for raw queries in Django? I always see those easy kind of examples like: lname = 'Doe' connection.execute('SELECT * FROM table WHERE last_name = %s', [lname]) It's awesome how less one parameter explains if you dive into deeper detail! How about: set_var = ((0,'val',3.5),(1,'tadaa',5)) connection.execute("INSERT INTO table VALUES (%s)",[set_var[0]]) or: head = [col1 int(11), col2 int(12), col3 varchar(255)] connection.execute("CREATE TABLE IF NOT EXISTS `%s` %s", [table, '('+str(', '.join(head))+')']) and then there is: query = """SELECT %s FROM special_table""" connection.execute(query, ["*"]) or I could write everyhting simple into a string? connection.execute("SELECT "+injection+" FROM yetAnotherTable") Do I have to use anywhere ';' in the End of the query? And I also saw, that people used {}. format() for querystrings ... And what's the point about backticks? Why shall I not use them? How can I handle a tablename including a "-" ? I'm super confused about the syntax for writing raw queries. Especially about the parameter part. What is allowed? And what is not allowed? Could somebody delight the topic a bit more than the explanations of the Django doc, please! -
How to set environment variables for Django settings.py with Jenkins
I have a settings.py file for my Django project that reads in environment variables for some fields. This works great for local development. I'm not sure of how to make this work for my Jenkins build (Freestyle project). An extra layer of complexity is that some of these variables contain sensitive data (passwords, etc.) and so need to be secured. So far, I have been able to use Credentials Binding Plugin to set up a secret .env file and can successfully access that as an environment variable. How do I go about setting all the 'actual' variables from that file? Or is this bad practice? If it's not bad, wouldn't those variables continue living on the server after the build has finished? If it is bad, what is the better way to do this? I can update the settings.py file easily enough if needed to make this work. -
Bootstrap cards showing on the right side of the page
I want to add 3 cards, but when I try, the cards appear on the right side of the page maybe it is an error on the code before the cards. This is the code of the cards. <div class="card-deck mb-3 text-center"> <div class="card mb-4"> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> </div> <div class="card"> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> </div> <div class="card"> <img src="..." class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> </div> </div> This is what I am getting, I want it to be at the middle. This is the page. -
Difference between using querying data and creating one through admin page?
I made some models and filled them with fields i.e. CharField and TextField. I registered my model in admin.py so that admin has the ability to create and edit the models in the admin page. Why do people use the terminal shell to query the database rather than using the admin page to simply create it there without the little hassle of importing the model and querying the database in the shell? -
Can't launch docker composer
I have this rep with a Django app and Docker, but docker-compose up is not working. This is my output: Starting covidoff-web_db_1 ... done Starting covidoff-web_webapp_1 ... done Starting covidoff-web_webserver_1 ... done Attaching to covidoff-web_db_1, covidoff-web_webapp_1, covidoff-web_webserver_1 db_1 | 2020-03-20 00:50:54.601 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2020-03-20 00:50:54.601 UTC [1] LOG: listening on IPv6 address "::", port 5432 webapp_1 | HOST: db:5432, DB: None, USER: postgres db_1 | 2020-03-20 00:50:54.605 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" webapp_1 | ==> Django setup, executing: flush db_1 | 2020-03-20 00:50:54.620 UTC [24] LOG: database system was interrupted; last known up at 2020-03-20 00:25:37 UTC db_1 | 2020-03-20 00:50:54.802 UTC [24] LOG: database system was not properly shut down; automatic recovery in progress db_1 | 2020-03-20 00:50:54.804 UTC [24] LOG: invalid record length at 0/16538C0: wanted 24, got 0 db_1 | 2020-03-20 00:50:54.804 UTC [24] LOG: redo is not required db_1 | 2020-03-20 00:50:54.817 UTC [1] LOG: database system is ready to accept connections webapp_1 | ==> Django setup, executing: migrate webapp_1 | Operations to perform: webapp_1 | Apply all migrations: admin, announcements, auth, contenttypes, sessions, tracker webapp_1 | Running migrations: webapp_1 | No migrations … -
Django raw queries with large params
I feel like going nuts with raw queries. Always Django complains about my misstakes: I try to write a function to copy a table from one database to another. CODE: def copy_tables(projectname): with connections['DB1'].cursor() as db1cursor: tables = get_all_custom_tables(projectname, 'DB1') for table in tables: with connections['django'].cursor() as db2cursor: db1cursor.execute("SELECT * FROM `" + table + "`") values = db1cursor.fetchall() db1cursor.execute("SHOW COLUMNS FROM `" + table + "`") columns = db1cursor.fetchall() v_col = [] for col in columns: v_col.append("`"+str(col[0]) + "` " + str(col[1])) #db2cursor.execute("DROP TABLE IF EXISTS `" + table + "`") ISSUE HERE----> db2cursor.execute("CREATE TABLE IF NOT EXISTS `%s` (%s)", [table, ", ".join(v_col)]) db2cursor.execute("INSERT INTO `%s` VALUES %s" ,[table, values[0]]) django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''userID int(11), TaskID varchar(128), techID varchar(128), `imgI' at line 1") I don't see the error? What is it? Do the execute paramters need to have special types? Does it matter if I always handle Strings? I also had an issue with None for a field before I run into this issue. Can somebody point me at a good ressource for mysql-python syntax. … -
Multiplos models - tres apps
Boa noite prezados... meu projeto de TCC, tem três apps: turmas, salas e alocar. eu preciso fazer as alocações das turmas nas salas, depois de alocadas preciso marcar um boleano da turma como alocada, e um boleano da sala como indisponivel. abaixo envio o codigo para ficar melhor elucidado. como devo implementar isso? estou empacado nesse ponto, confesso que sou inexperiente com django. ''' app turmas class Turma(models.Model): turma = models.CharField('Turma', max_length=20) curso = models.CharField('Curso', null=False, max_length=50) periodo = models.CharField('Periodo', null=False, max_length=50) disciplina = models.CharField('Disciplina', max_length=50) qtdalunos = models.IntegerField('Qtd') professor = models.CharField('Professor', max_length=50) alocada = models.BooleanField('Alocada', default=False) internet = models.BooleanField('Internet', default=False) projetor = models.BooleanField('Projetor', default=False) computador = models.BooleanField('Computador', default=False) ''' ''' #app salas class Sala(models.Model): bloco = models.ForeignKey(Bloco, on_delete=models.PROTECT) sala = models.CharField('Sala: ', unique=True, max_length=50) capmaxima = models.IntegerField('Cap. Máxima: ') disponivel = models.BooleanField('Disponivel', default=True) ocupada = models.BooleanField('Ocupada', default=False) internet = models.BooleanField('Internet', default=False) projetor = models.BooleanField('Projetor', default=True) computador = models.BooleanField('Computador', default=False) #alocar class Alocar(models.Model): data = models.DateField('Data', auto_now=True, blank=True) dias = [ ('A Confirmar', 'A Confirmar'), ('Segunda', 'Segunda'), ('Terça', 'Terça'), ('Quarta', 'Quarta'), ('Quinta', 'Quinta'), ('Sexta', 'Sexta'), ('Sábado', 'Sábado'), ] dia = models.CharField('Dia', max_length=11, choices=dias, default='A Confirmar') horario = models.ForeignKey(Horario, on_delete=models.CASCADE) turma = models.ForeignKey(Turma, on_delete=models.SET()) sala = models.ForeignKey(Sala, on_delete=models.SET())ode here Obrigado pela … -
Django change extablished column with values into a ForeignKey
I have the following model in place: class IssueDescription(models.Model): no = models.CharField(max_length=10, primary_key=True) title = models.CharField(max_length=200, blank=False) confirm = models.TextField() remedy = models.TextField() subsystem = models.CharField(max_length=50, blank=False) It already lives in Postgres DB, and is populated with values. The values held in it came from a .csv file (including subsystem values). What I realized, is that I would like to make subsystem column into a ForeignKey, and move all the values from it into a separate table, e.g.: class Subsystems(models.Model): subsystem = models.CharField(max_length=50, blank=False) class IssueDescription(models.Model): no = models.CharField(max_length=10, primary_key=True) title = models.CharField(max_length=200, blank=False) confirm = models.TextField() remedy = models.TextField() subsystem = models.ForeignKey(Subsystems, on_delete=models.PROTECT, blank=False) What would be the cleanest way of moving already established values in the original IssueDescription model's subsystem column to a newly created Subsystems table, and drawing all the links via ForeignKey field in a new IssueDescription model? -
Django-Filters , Django-tables autocomplete search
Im quite new to django so not very familiar with things. Im trying to autocomplete one of the files and clients filters for django-tables. I was trying to use django-autocomplete-light ( dal). Using Python3 also and django version 2.2.8. Im finding that dal.autocomplete doesnt have Select2QuerySetView or ModelSelect2. Im using django-tables 2 example to filter the table by fields but my 'exact' filterset like files and clients are long lists and hard to read so i want to be able to autocomplete search in the filter forms. Any help is much appreciated. filters.py class ClientFilesFilter(FilterSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) requestdatetime = django_filters.IsoDateTimeFromToRangeFilter( lookup_expr=('icontains'), widget=django_filters.widgets.RangeWidget( attrs={'type':'datetime-local'} ) ) #file = django_filters.ModelChoiceFilter(queryset=Files.objects.all(), # widget=autocomplete.ModelSelect2(url='files-autocomplete')) class Meta: model = ClientFiles fields = {"client": ["exact"], "httpstatus": ["exact"], "objectsize": ["gte"], "referrer": ["icontains"]} views.py class FileAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Files.objects.filter(name='file_name.zip') return qs class FilteredPersonListView(ExportMixin, SingleTableMixin, FilterView): table_class = ClientFilesTable model = ClientFiles template_name = "bootstrap_template.html" filterset_class = ClientFilesFilter export_formats = ("csv", "json") def get_queryset(self): return super().get_queryset() def get_table_kwargs(self): return {"template_name": "django_tables2/bootstrap.html"}. urls.py urlpatterns = [ path("", FilteredPersonListView.as_view(), name="filtertableview"), path("api/", include('app.urls')), path("admin/", admin.site.urls), url(r'^file-autocomplete/$', FileAutocomplete.as_view(), name='file-autocomplete') ] -
Page not found when rendering page on Django
Trying to render a page but keep getting page not found error message despite trying different patterns on urls to define the path. This is what I have in my urls.py path('students/', include(([ path('', students.dashboard, name='quiz_list'), path('edit_user', students.edit_user, name='edit_user'), path('mentors', students.mentor_list, name='mentors'), path('what_is_ml', students.what_is_ml, name="what_is_machine_learning"), ], 'classroom'), namespace='students')), In my views (students.py): @login_required @student_required def what_is_ml(request): return render(request, 'classroom/students/what_is_machine_learning.html') and in my html: <i class="fa fa-fw fa-circle text-green-300" href="{% url 'students:what_is_machine_learning' %}"></i>What is Python This is the structure of my template files classroom -->students >what_is_machine_learning.html I am confused because this is how I defined every other page I am rendering. I have also tried this <i class="fa fa-fw fa-circle text-green-300" href="{% url 'students:what_is_ml' %}"></i>What is Python</i> and <i class="fa fa-fw fa-circle text-green-300" href="{% url 'what_is_ml' %}"></i>What is Python</i> But get the NoReverseMatch error messages -
get_foo_display isn't functioning well with DRF
I have this class MEMBERSHIP_STATUS: PENDING = 0 DECLINED = 1 MEMBER = 2 and the model is class Membership(models.Model): MEMBERSHIP_STATUS = ( (MEMBERSHIP_STATUS.PENDING, _('Pending')), (MEMBERSHIP_STATUS.DECLINED, _('Declined')), (MEMBERSHIP_STATUS.MEMBER, _('Member')), ) user = models.OneToOneField(User, on_delete=models.CASCADE) status = models.IntegerField(max_length=10, choices=MEMBERSHIP_STATUS, default=MEMBERSHIP_STATUS.PENDING) def __str__(self): return self.user.username now, in serializers.py, I have this class MembershipSerializer(serializers.ModelSerializer): user = UserSerializer() family = FamilySerializer() status = serializers.SerializerMethodField() class Meta: model = Membership fields = '__all__' def get_status(self, membership): return membership.get_status_display() This always returns 0, Even tho I'm expecting it to return the display. The solution I found is class MEMBERSHIP_STATUS: PENDING = '0' DECLINED = '1' MEMBER = '2' Changing the Integers to Strings seems to work, But I don't understand why. Any explaination? -
How can I load only one object from react-redux using api?
I am working on a simple web app that allows user login. I am using python == 3.7.4 django == 3.0.4 djangorestframework == 3.11.0 react == 16.13 axios == 0.19.2 In my users's api, # localhost:8000/api/users [ { "url": "http://localhost:8000/api/users/2/", "id": 2, "username": "foo", "boards": [ "http://localhost:8000/api/boards/15/" ] }, { "url": "http://localhost:8000/api/users/3/", "id": 3, "username": "poopoop", "boards": [] }, ] My auth in action is, // actions/auth.js import { USER_LOADED, USER_LOADING } from './types' export const loadUser = () => (dispatch, getState) => { dispatch({ type: USER_LOADING }) const token = getState().users.token; const config = { headers: { 'Content-type': 'application/json' } } if(token) { config.headers['Authorization'] = 'Token ${token}'; } axios.get('/api/users', config) .then(res => { dispatch({ type: USER_LOADED, payload: res.data }); }).catch(err => { dispatch(returnErrors(err.response.data, err.response.state)); dispatch({ type:AUTH_ERROR }) }) } reducers/auth.js const initialState = { token: localStorage.getItem("token"), isAuthenticated: null, isLoading: false, user: null }; export default function(state=initialState, action){ switch(action.type){ case USER_LOADING: return { ...state, isLoading: true } case USER_LOADED: return { ...state, isAuthenticated: true, isLoading: false, user: action.payload } case AUTH_ERROR: case LOGIN_FAIL: localStorage.removeItem('token'); return { ...state, token: null, user: null, isAuthenticated: false, isLoading: false } case LOGIN_SUCCESS: localStorage.setItem("token", action.payload.token); return { ...state, ...action.payload, isAuthenticated: true, isLoading: false } default: … -
Use an image in Wagtail's Base.html template
I'm looking to add a logo to my base.html by pulling from the page model... But I don't have access to the base.html page model through wagtail, and so I don't know where to create a ImageChooserPanel to specify the logo for my navbar (which should be applied to all pages). -
super().__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'max_lenght'
Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\MobilineWest\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\MobilineWest\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\MobilineWest\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\MobilineWest\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\MobilineWest\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\MobilineWest\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\django\myfirst\myfirst\apps\articles\models.py", line 8, in <module> class Comment(models.Model): File "D:\django\myfirst\myfirst\apps\articles\models.py", line 10, in Comment author_name = models.CharField('имя автора', max_lenght = 50) File "C:\Users\MobilineWest\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields\__init__.py", line 984, in __init__ super().__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'max_lenght' -
Django - Fetch values from children via Foreign Key, while looping the parent objects in template
I am quite new to Django and probably this will be totaly noobish question, but I am stuck in this situation and bit help would be much appreciated. I have the following models: class BillType(models.Model): name = models.CharField(max_length=200) created_on = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.name class Bill(models.Model): bill_type = models.ForeignKey(BillType, on_delete=models.CASCADE) month = models.CharField(max_length=200) amount = models.IntegerField() due_date = models.CharField(max_length=200) note = models.TextField(blank=True) recurring = models.BooleanField(default=True) currency = models.CharField(max_length=100) created_on = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.month and the following view: def billingOverview(request): bill_types = BillType.objects.all() context = { 'bill_types': bill_types, } return render(request, 'management/billing-overview.html', context) In the template, I am using the For loop to loop through the BillType objects and that part is working fine. However, for each of the looped BillType objects that are rendered separately in the template, I need to access and show the data for 'month' corresponding to that particular BillType object. Can you help me with an example of how I can do that action? Thanks, Bojan In case the template is needed: {% for bill_type in bill_types %} <!-- Billing overview column --> <div> <!-- Billing overview widget --> <div class="bo-widget"> <div class="bo-widget-header"> <div> <h2>{{ bill_type.name }}</h2> <span>Overview of {{ bill_type.name|lower … -
TypeError: Tried to update field dashboard.Product.province with a model instance
I am trying to save the url in my object where the encrypted id of my object is located. So it writes all fields and finally tries to add the url to the already called object. Then my error is shown 'TypeError: Tried to update field dashboard.Product.province with a model instance.' How do I save my url after calling object.save () once. Maybe there is a better way to get object.id before calling object save (). I would not have to save the same object a second time. Thank you in advance for any help. Models.py class Product(models.Model): type = models.CharField(max_length=50) img = models.ImageField() img_sm = ResizedImageField(size=[400, 400], crop=['middle', 'center'], force_format='JPEG', quality=50) category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=200) description = models.TextField() province = models.CharField(max_length=100) city = models.CharField(max_length=100) name_user = models.CharField(max_length=50) phone = models.CharField(max_length=50) date_created = models.DateTimeField(auto_now_add=True) url = models.URLField() #aktualny url produktu pawnshop_send = models.IntegerField(default=random_pawnshop) def __str__(self): return '%s - %s - %s' % (self.type, self.name, self.city) class Meta: ordering = ['-date_created', ] views.py if request.method == 'POST': form = FormNewProduct(request.POST, request.FILES) if form.is_valid(): cd = form.cleaned_data object = Product() object.type = type object.img = cd['img'] object.img_sm = cd['img'] object.category = get_instance(cd['category'], Category) object.name = cd['name'] object.description = cd['description'] … -
How can i deploy a Django API
How can i deploy a Django API to an server? Is there a command like python3 manage.py deploy? In order for me to copy paste the produced files to the server -
django-allauth: Facebook always requires entering password
I have set user registration via Facebook with django-allauth. Everything works fine, except for one thing: when I am redirected to Facebook for logging in, I am required to enter my Facebook password. How can this be avoided? I want perform the login silently, without the user being prompted to commit any additional actions. My allauth settings in settings.py: SOCIALACCOUNT_PROVIDERS = \ { 'facebook': {'METHOD': 'oauth2', 'SCOPE': ['email','public_profile', 'user_friends'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'verified', 'locale', 'timezone', 'link', 'gender', 'updated_time'], 'EXCHANGE_TOKEN': True, 'LOCALE_FUNC': lambda request: 'path.to.callable', 'VERIFIED_EMAIL': False, 'VERSION': 'v2.4'}, 'google': { 'SCOPE': ['https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email'], 'AUTH_PARAMS': {'access_type': 'online'}, } } -
Django: Update Fields, throws "Save with update_fields did not affect any rows." Even though row is updated
I have a table with a row that needs to be updated. This Table however has a trigger. For simplicity I have limited the trigger to present my case. Alter TRIGGER Cow_UpdateTrigger ON Cow FOR update AS select * from Cow This trigger gets called when an Update occurs, however the trigger doesn't modify any fields with in the Cow Table. The code below shows me attempting to updating the name of a Cow. It throws the following exception upon saving. "Save with update_fields did not affect any rows." However the name of the cow actually has been updated. cow = Models.Cow.objects.get(pk=1) cow.name = "Life" cow.save(update_fields=["name"]) # Raises Error, However successfully updates fields. Further Analysis with the cursor. c = cursor.execute("""Update COW set cow_name = "Love" where COW_ID = '1' """) c.rowcount The following code is ran with three different update trigger scenarios. The returning row count reflecting the rows changed differs. Trigger is removed and Update is performed. Row count = 1 The Trigger is created with a select statement . Row count = -1 however a row has changed A trigger is created with an update statement to randomly change an attribute in updated row. This also returns … -
Django saving data with form
I already saw many Stack overflow posts, but cannot find any problem on my code, but this code doesn't save any piece of data. models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=50, blank=True) content = models.CharField(max_length=200, blank=True) post_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title forms.py from django.forms import ModelForm from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = ['title', 'content', 'post_date'] views.py from django.shortcuts import render from django.template import loader from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.http import Http404 from .models import Post from .forms import PostForm # Create your views here. def index(request): latest_post_list = Post.objects.order_by('-post_date')[:5] template = loader.get_template('form/index.html') context = {'latest_post_list':latest_post_list} return render(request, 'form/index.html', context) def posts(request, post_id): post = get_object_or_404(Post, pk=post_id) return render(request, 'form/posts.html', {'post':post}) def posting(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.save() return HttpResponseRedirect('/') else: print(form.errors) else: form = PostForm() return render(request, 'form/posting.html', {'form' : form}) posting.html <form action="/form/" method="post"> {% csrf_token %} {{ form }} <input type='submit' value='Submit'> </form> <script src="" async defer></script> I swear I saw many questions about it, but still I'm in trouble :/ I thought form.save in the views.py would make it work … -
Uploading multiple files using react and DJango REST API
I am building a project in which users can upload videos in bulk, My code works fine but I want to show the users a progress bar when their videos are being uploaded to the server, By doing some research on the internet I found that the onUploadProgress event of Axios can be used, but I have no idea on how to send the upload progress of each video file individually. Below is my code reducers.js file- import * as actionTypes from "../actions/types"; const intialState = { isLoading: false, uploadProgress: 0, error: null }; export default function(state = intialState, action) { switch (action.type) { case actionTypes.ADD_VIDEO_START: case actionTypes.ADD_VIDEO_SUCCESS: case actionTypes.ADD_VIDEO_ERROR: return { ...state, isLoading: action.isLoading, error: action.error }; case actionTypes.VIDEO_UPLOAD_PROGRESS: return { ...state, uploadProgress: action.percentage }; default: return state; } } actions.js import * as actionTypes from "./types"; import { getToken, VIDEO_URL } from "./Utils"; import axios from "axios"; export const addVideos = video => dispatch => { if (getToken()) { dispatch({ type: actionTypes.ADD_VIDEO_START, isLoading: true, error: null, }); const config = { headers: { Accept: "application/json", "Content-Type": "multipart/form-data", Authorization: `Token ${getToken()}` }, onUploadProgress: progressEvent => { const { loaded, total } = progressEvent; let percentage = Math.floor((loaded * 100) … -
Can I use digital ocean spaces for user uploaded files with django?
I would like to have a central place for images, javascript, css, etc. to enable horizontal scaling on my Django application. Currently I am looking at DigitalCcean spaces however in their guides it seems only possible to upload files manually using: python manage.py collectstatic Does anyone have experience using DigitalOcean spaces with media files? I basically want to make sure that a file uploaded on one server, is accessible by another server. Thanks in advance! -
Getting authenticated username in Django
I'm using Django's built in user who is in my application authenticates and uses some service. Now my problem is, I want to get current user's username and write it to database. Here I've used such method that mentioned User model as a ForeignKey, but it is assigning to database as an empty data. But I want to write current user's name. Here are my codes: views.py: @login_required(login_url='sign_in') def upload_document(request): context = {} form = UploadDocumentForm() if request.method == 'POST': form = UploadDocumentForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() return redirect('index') context = {'form':form} return render(request, 'upload_document.html', context) models.py: class OriginalDocument(models.Model): document = models.FileField(upload_to='static/original_document', blank=False) document_title = models.CharField(max_length=300) student_name = models.CharField(max_length=100) teacher_name = models.CharField(max_length=100) document_type = models.CharField(max_length=100) university = models.ForeignKey(University, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add = True) checked_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.document_title