Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to automatically start download after user clicks download button which triggers bucket event?
I am making a website on django which allows a user to upload a csv file and convert it to json. Whenever a user uploads a csv document a lambda fuction is triggered the moment the file lands on an s3 bucket where it gets converted to json and saved to another bucket. After the function generates a pre-signed url with the following code: uri_duration = 90 s3Client = boto3.client('s3') url = s3Client.generate_presigned_url('get_object', Params = {'Bucket': bucket, 'Key': filekey'}, ExpiresIn = uri_duration) My question is how could I start the download with the aid of the boto3 library automatically now that the pre-signed url is generated`? I appreciate any help you can provide -
Django Import Error. Cannot import name reciever
I'm learning django and while trying to use Signal and receiver, I receive an ImportError. File "/Library/Python/2.7/site-packages/django/dispatch/__init__.py", line 9, in <module> from django.dispatch.dispatcher import Signal, receiver ImportError: cannot import name receiver I've seen this post and I tried deleting and re-adding the django module(s) but nothing happened. What can I do to fix this and make it work? I'm using django-2.3 and python 3.7.3 -
Django GenericRelation for the update_or_create
I have an issue with using GenericRelation with update_or_create. I have the following models: class LockCode(TimeStampedModel): context_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) context_id = models.PositiveIntegerField() context = GenericForeignKey('context_type', 'context_id') class Mission(DirtyFieldsMixin, models.Model): lock_codes = GenericRelation( LockCode, content_type_field='context_type', object_id_field='context_id', related_query_name='mission' ) I try to create or update LockCode using the mission as a key: mission = .... LockCode.objects.update_or_create( context=mission, defaults={ #some other columns there } And I have the FieldError: Field 'context' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. It works when I use the context_id and context_type explicitly: LockCode.objects.update_or_create( context_id=mission.pk, context_type=ContentType.objects.get_for_model(Mission), defaults={ #some other columns there } Is it something wrong in my configuration? Or it is only single way to use GenericForeignKey for the update_or_create? -
How to run migrate script?
Trying to run python manage.py migrate but getting error as ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Enforced unique constraints are not supported in Azure SQL Data Warehouse. To create an unenforced unique constraint you must include the NOT ENFORCED syntax as part of your statement. (104467) (SQLExecDirectW)') -
Django - sqlite3.OperationalError unable to open database file [on hold]
I am developing a small app with the django framework and when trying to serve it via apache2 I get the following error: (sqlite3.OperationalError) unable to open database file (Background on this error at: http://sqlalche.me/e/e3q8) My settings.py entry for the database looks like that: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3') } } the db file exists and has the following rights given by chmod: root@myVPS:/var/www/lab# ls -l db.sqlite3 total 30236 -rwxrwxr-x 1 www-data www-data 3018568 Jul 1 22:14 db.sqlite3 the root folder /var/www/lab: drwxrwxr-x 8 www-data www-data 4096 Jul 2 01:15 lab I read that it might be a problem with the rights but I can't seem to find what I did wrong. Traceback: File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/engine/base.py" in _wrap_pool_connect 2228. return fn() File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/pool.py" in connect 434. return _ConnectionFairy._checkout(self) File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/pool.py" in _checkout 831. fairy = _ConnectionRecord.checkout(pool) File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/pool.py" in checkout 563. rec = pool._do_get() File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/pool.py" in _do_get 1355. return self._create_connection() File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/pool.py" in _create_connection 379. return _ConnectionRecord(self) File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/pool.py" in __init__ 508. self.__connect(first_connect_check=True) File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/pool.py" in __connect 710. connection = pool._invoke_creator(self) File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/engine/strategies.py" in connect 114. return dialect.connect(*cargs, **cparams) File "/var/www/lab/venv/lib/python3.5/site-packages/sqlalchemy/engine/default.py" in connect 437. return self.dbapi.connect(*cargs, **cparams) The above exception (unable to open database file) … -
Django: Pre-populate form with request data
I am trying to pre-populate a Django form based on a users POST request data. Am using FormView, so i overide get_initial but request.POST is always empty. I guess am missing something below is snippet from my view def get_initial(self): initial = super(Yo_EnView, self).get_initial() if self.request.POST: initial.update({'src': self.request.src}) return initial -
Django deployment to AWS using wrong python version?
I'm getting this error when deploying a Django 1.11.5, Python 2.7 application to AWS elasticbeanstalk. [2019-07-02T14:39:08.658Z] INFO [2951] - [Application deployment app-1376-190702_143948@1/StartupStage0/AppDeployPreHook/03deploy.py] : Starting activity... [2019-07-02T14:39:32.424Z] INFO [2951] - [Application deployment app-1376-190702_143948@1/StartupStage0/AppDeployPreHook/03deploy.py] : Activity execution failed, because: Collecting git+git://github.com/django-crispy-forms/django-crispy-forms.git@c243b01a41ff2cab28fba219f39f996c1125195d (from -r /opt/python/ondeck/app/requirements.txt (line 19)) Cloning git://github.com/django-crispy-forms/django-crispy-forms.git (to c243b01a41ff2cab28fba219f39f996c1125195d) to /tmp/pip-IgLSZW-build Could not find a tag or branch 'c243b01a41ff2cab28fba219f39f996c1125195d', assuming commit. Collecting app-version==0.2.1 (from -r /opt/python/ondeck/app/requirements.txt (line 1)) Downloading https://files.pythonhosted.org/packages/ac/a7/dedf1c4302ffcd271cdc788308bd0c4ae0c1b6e8aeef63295259213cfa3b/app_version-0.2.1.tar.gz Collecting appdirs==1.4.3 (from -r /opt/python/ondeck/app/requirements.txt (line 2)) Downloading https://files.pythonhosted.org/packages/56/eb/810e700ed1349edde4cbdc1b2a21e28cdf115f9faf263f6bbf8447c1abf3/appdirs-1.4.3-py2.py3-none-any.whl Collecting awsebcli==3.14.1 (from -r /opt/python/ondeck/app/requirements.txt (line 3)) Downloading https://files.pythonhosted.org/packages/9c/63/e05679b01575a4a25f482ea1f0420bf491853c60c71656eb8badd1040e51/awsebcli-3.14.1.tar.gz (233kB) Collecting backports.ssl-match-hostname==3.5.0.1 (from -r /opt/python/ondeck/app/requirements.txt (line 4)) Downloading https://files.pythonhosted.org/packages/76/21/2dc61178a2038a5cb35d14b61467c6ac632791ed05131dda72c20e7b9e23/backports.ssl_match_hostname-3.5.0.1.tar.gz Collecting bleach==2.1.3 (from -r /opt/python/ondeck/app/requirements.txt (line 5)) Downloading https://files.pythonhosted.org/packages/30/b6/a8cffbb9ab4b62b557c22703163735210e9cd857d533740c64e1467d228e/bleach-2.1.3-py2.py3-none-any.whl Collecting blessed==1.14.2 (from -r /opt/python/ondeck/app/requirements.txt (line 6)) Downloading https://files.pythonhosted.org/packages/07/f5/a0e4b579053c7c01186e1a32b25bfad54fa25468e0e489c44572d39d3bf8/blessed-1.14.2-py2.py3-none-any.whl (64kB) Collecting botocore==1.7.7 (from -r /opt/python/ondeck/app/requirements.txt (line 7)) Downloading https://files.pythonhosted.org/packages/5c/64/b351ade40f18a8c05f1dfd231790bfad81cf97196a4ebedc6eee298945d4/botocore-1.7.7-py2.py3-none-any.whl (3.6MB) Collecting cement==2.8.2 (from -r /opt/python/ondeck/app/requirements.txt (line 8)) Downloading https://files.pythonhosted.org/packages/70/60/608f0b8975f4ee7deaaaa7052210d095e0b96e7cd3becdeede9bd13674a1/cement-2.8.2.tar.gz (165kB) Collecting chardet==3.0.4 (from -r /opt/python/ondeck/app/requirements.txt (line 9)) Downloading https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl (133kB) Collecting colorama==0.3.9 (from -r /opt/python/ondeck/app/requirements.txt (line 10)) Downloading https://files.pythonhosted.org/packages/db/c8/7dcf9dbcb22429512708fe3a547f8b6101c0d02137acbd892505aee57adf/colorama-0.3.9-py2.py3-none-any.whl Collecting django==1.11.5 (from -r /opt/python/ondeck/app/requirements.txt (line 11)) Downloading https://files.pythonhosted.org/packages/18/2d/b477232dd619d81766064cd07ba5b35e956ff8a8c5c5d41754e0392b96e3/Django-1.11.5-py2.py3-none-any.whl (6.9MB) Collecting django-adaptors==0.2.5 (from -r /opt/python/ondeck/app/requirements.txt (line 12)) Downloading https://files.pythonhosted.org/packages/a6/fe/320a75cbebdca3217765f89ca18d322c3eeec5e994c9ede4fd5d75e0e1c5/django-adaptors-0.2.5.tar.gz Collecting django-appconf==1.0.2 (from -r /opt/python/ondeck/app/requirements.txt (line 13)) Downloading https://files.pythonhosted.org/packages/5b/78/726cdf3e04660560cf25f9def95b8f2736310c581dabed9adfe60154a9f8/django_appconf-1.0.2-py2.py3-none-any.whl Collecting django-axes==2.3.3 (from -r /opt/python/ondeck/app/requirements.txt (line 14)) Downloading https://files.pythonhosted.org/packages/47/1c/956fb482004f92f0b4978251a70142c11ba3ffb3f56a5ee9373efefaca8f/django-axes-2.3.3.tar.gz Collecting django-bootstrap3==9.0.0 (from -r /opt/python/ondeck/app/requirements.txt (line 15)) Downloading … -
Force password change on first login (Django)
A client requires the ability for managers to add users to a company (with a random one time password) where the user must change their password before accessing anything. I am developing the app in Django 2.2 I made a custom user, replacing username with an email address and I added a change_password bool flag to the user. My change_password form/function works properly, but redirecting does not. urls.py path('change-password/', views.change_password, name='change-password'), views.py class Login(LoginView): def form_valid(self, form): # form is valid (= correct password), now check if user requires to set own password if form.get_user().change_password: return HttpResponseRedirect(reverse('change-password')) else: auth_login(self.request, form.get_user()) return HttpResponseRedirect(self.get_success_url()) def change_password(request): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): form.save() request.user.change_password = False request.user.save() update_session_auth_hash(request, request.user) return redirect(reverse('user_view')) else: return redirect(reverse('change-password')) else: form = PasswordChangeForm(user=request.user) args = {'form': form} return render(request, 'users/change_password.html', args) The expected behavior is to redirect to change-password if the change_password flag is True, however, while the app does redirect to change-password, upon Submission the following error is thrown: NotImplementedError: Django doesn't provide a DB representation for AnonymousUser. If I add the decorator @login_required to my change_password function this error goes away, however, I am redirected back to the login page with … -
csv file going from 316 KB to ~3GB during django app run time then back instantly once app is terminated
The explanation is a bit long, but most of this is to give some background regarding my problem (the problem is probably not Python related, but having extra information wont hurt): I am currently working on a django application. The application window (browser) has two iframes each taking 50% of the screen. On the left-hand side there will be snopes (fact-check website) pages displayed and on the right-hand side one of the pages linked in that specific snopes article will be displayed. A form in the bottom of the app will let the user choose and post whether the RHS page is a source of the claim in the snopes article or not (there is also "invalid input" or "I dont know"). Submitting calls a function which tries to get the other links of the current snopes page, and if there is none, get any pages annotated (in this priority) twice, once, or least (so 0 then 3 then 4 .....). This is done by using a count.csv which simple stores how many each page+link combination has been annotated (as snopes articles can repeat and so can linked sites). The header of count.csv is : page source_url count The pages … -
Reverse for 'logout' not found. 'logout' is not a valid view function or pattern name
New to Django, and attempting to learn how to create a signup page through tutorial. Getting this issue despite following exactly what the tutorial is. -
Ansible causes error 500 on save to database
When use ansible playbook to setup server, then send post to database cause error 500. If I setup by myself (from start, on terminal commands) it's work without problem. This is code I use, not full, only part that I was doing by terminal. The system is ubuntu 18.04 - hosts: all vars: host: "{{ ansible_host }}" site_folder: "/home/{{ ansible_user }}/sites/{{ ansible_host }}" repo_url: "https://github.com/ForisTale/Django_TDD.git" tasks: - name: Deadsnakes PPA to get Python 3.7 apt_repository: repo: ppa:deadsnakes/ppa - name: make sure required packages are installed apt: name: ["nginx", "git", "python3.7", "python3.7-venv"] state: present update_cache: yes - name: Create site folders. file: path: "{{ site_folder }}" state: directory - name: Check if .git exists. stat: path: "{{ site_folder }}/.git" register: git_exists - name: If .git exists fetch repository. command: git fetch args: chdir: "{{ site_folder }}" when: git_exists.stat.exists == True - name: If .git don't exists clone repository command: git clone {{ repo_url }} . args: chdir: "{{ site_folder }}" when: git_exists.stat.exists == False - name: Get local hash commit. local_action: command git log -n 1 --format=%H register: commmit_hash - name: Reset git to actualy used commit. command: git reset --hard {{ commmit_hash.stdout }} args: chdir: "{{ site_folder }}" - name: … -
Auth0: How to Submit POST Using M2M Token with React Frontend
I was unable to find any sort of solution on integrating a working POST-request submission, using Auth0's M2M Token Client Credential Flow process, to submit a POST entry to my Django backend from my React frontend. I’ve currently fully built on a setup compromising of the following, with Auth0 somewhat fully integrated: Frontend: React Browser Setup making POST to retrieve AUTH0 token via Auth0 server. React Browser Setup using retrieved M2M Token based on JWT authentication, to execute GET requests to backend for data. Backend: Django Backend Setup authenticating M2M Token with GET requests to release data. The above setup currently works originally without any Auth0 implementation and subsequently, with GET data requests. However, the issue finally popped up recently, when I attempted to make POST data requests. I do realised that given my setup where, request codes based on React, token used retrieved via M2M setup, I was unable to find any sort of solution on integrating a working POST-request submission to my Django backend. let getBackendConfig = { headers: { "Content-Type": "application/json", Authorization: process.env.REACT_APP_JWT_AUTH0_HEADER + " " + auth0Token, }, }; async function submitLocationViaPOST( dataToPOST ) { setIsLocationUploaded("process"); try { Promise.all([ await axios .post(urlSubmitLocationPOSTAPI, dataToPOST, getBackendConfig) .then(response => … -
Tastypie showing totals while paginating
I'm struggling to find a good way of doing this. I seem to just keep hitting tastypie erros (shouting at me for not returning a query set most of the time). So, Im using tastypie to return a block of data: name, sales, revenue bob, 1, 100 sarah,2, 200 This data nicely paginates using the limit/offset query params. In the same table, per column, I'd like to show the totals (for the whole dataset - including what is on later pages in the pagination). Basically: name, sales, revenue 3, 300 bob, 1, 100 sarah,2, 200 I'm struggling to get this to work with in tastypie. I decided to create one resource for the normal data (seen above), and then have a seperate Totals resource that I could call seperatly. So, I tried adding the below to my SalesTotal resource: def get_object_list(self, request): q = super(MyResource, self).get_object_list(request).aggregate(Sum('sales')) return q But this gives me the error "expecting queryset", as this func should return a queryset - so apply_filters can run. So I tried adding this instead: def apply_filters(self, request, applicable_filters): return self.get_object_list(request).filter(**applicable_filters).aggregate(Sum('sales')) This now throws up an error from the Paginator class. Which leads me to the Resources function get_list(), where all … -
django template tag not getting invoked more than once in javascript function
In my django application, I have created a template tag function that generates a random number that I am assigning as random IDs to programmatically generated elements. import os import random from django import template register = template.Library() @register.tag(name="randomgen") def randomgen(parser, token): items = [] bits = token.split_contents() for item in bits: items.append(item) return RandomgenNode(items[1:]) class RandomgenNode(template.Node): def __init__(self, items): self.items = [] for item in items: self.items.append(item) def render(self, context): arg1 = self.items[0] arg2 = self.items[1] if "hash" in self.items: result = os.urandom(16).encode('hex') elif "float" in self.items: result = random.uniform(int(arg1), int(arg2)) elif not self.items: result = random.random() else: result = random.randint(int(arg1), int(arg2)) return result In my html template, I have used the load tag to import the template tag .py file: {% load custom_tag %} On a particular button click, the randomgen() function is invoked only once: $(document).on("click", ".add_div_btn", function() { let random_id = "{% randomgen 100 1000 %}"; <!-- will generate a random number between 10 and 100 --> console.log("random id: ", random_id); }); However, every button click after the first one generates the same number. On checking the console log, i found out that the randomgen() function within the custom_tag.py file was getting called only once. I … -
django MultiValueDictKeyError error at request.FILES['file']
I am new to python/django and unable to figure out the issue. The requirement is to upload a csv file to load the data into the database. I have a custom model for users where the data needs to be loaded. Error seems to be occurring at csv_file = request.FILES['file'] Error- MultiValueDictKeyError at /upload-csv/ 'file' Request Method: POST Request URL: http://127.0.0.1:8000/upload-csv/ Django Version: 2.2.2 Exception Type: MultiValueDictKeyError Exception Value: 'file' Exception Location: D:\djreact\backend\env\lib\site- packages\django\utils\datastructures.py in __getitem__, line 80 Python Executable: D:\djreact\backend\env\Scripts\python.exe Python Version: 3.7.2 Python Path: ['D:\\djreact\\backend\\src', 'D:\\djreact\\backend\\env\\Scripts\\python37.zip', 'D:\\djreact\\backend\\env\\DLLs', 'D:\\djreact\\backend\\env\\lib', 'D:\\djreact\\backend\\env\\Scripts', 'd:\\python\\python37\\Lib', 'd:\\python\\python37\\DLLs', 'D:\\djreact\\backend\\env', 'D:\\djreact\\backend\\env\\lib\\site-packages'] Server time: Tue, 2 Jul 2019 12:49:52 +0000 View.py - def user_upload(request): template="user_upload.html" prompt = { 'order': 'order of csv should be first_name, last_name, email' } if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): _, created = User.Objects.update_or_create( first_name = column[0], last_name = column[1], email = column[2] ) return render(request, template) template - user_upload.html {% if messages %} {% for message in messages %} <div> <strong>{{message|safe}}</strong> </div> {% endfor %} {% else %} {{order}} <form method="post" encrypt="multipart/form-data"> {% csrf_token %} <label> Upload a file </label> <input type="file" name='file'> </br> … -
JSON field on elasticsearch
I am trying to create an index in elasticsearch. my sample code goes like this, @cjsta.doc_type class Books(DocType): class Meta: model = Book fields = ['name','author','price','additional_info'] here additional_info is a JSON field when I try to rebuild index I am getting, django_elasticsearch_dsl.exceptions.ModelFieldNotMappedError: Cannot convert model field additional_info to an Elasticsearch field! I have also tried initializing additional_info as NestedField. But didn't worked. What is the correct way to initialize a JSONField in fields? -
how to allow the user to filter objects in a database allowing multiple choices for a parameter
In Django I have a form that allow the user to filter objects in a database, this works great when the user chooses one value for parameter but I would like to allow multiple choices. I've tried using checkbox or select multiple, both don't work. I've tried writing a view function with multiple if statement for every possible combination of choices, it works but it's definetely a bad practice. I'm reading the Django tutorial but still haven't found a solution for what I think it's a simple problem. #my models.py class Game(models.Model): name = models.CharField(max_lenght=100) platform = models.CharField(max_lenght=100) is_free = models.BooleanField(default=True) genre = models.CharField(max_lenght=100) #my views.py def index(request): platform = request.GET.get('platform') is_free = request.GET.get('is_free') genre = request.GET.get('genre') if platform is not None: games = games.filter(platform=platform, is_free=is_free, genre=genre) return render(request, 'index_games.html', {'games': games}) /*this is index_games*/ {% extends 'base.html' %} {% block content %} <h1>Games</h1> <form method="get" action="/games/"> <h5>Choose platform</h5> /*only one choice is allowed here*/ <select name="platform"> <option value='PS4'>PS4</option> <option value="XBOX">XBOX</option> <option value='Switch'>Switch</option> </select> /*here's the problem, multiple choices should be allowed for is_free and genre but are not*/ <h5>Free to Play?</h5><br/> <input type="checkbox" name="is_free" value="True" checked>Free<br/> <input type="checkbox" name="is_free" value="False">For sale<br/> <h5>Genre</h5> <input type="checkbox" name="genre" value="Shooter">Shooter<br/> <input type="checkbox" name="genre" … -
Error in date an time parsing in jango ["'Tue, 02 Jul 2019 08:11:45 +0530' value has an invalid format. in YYYY-MM-DD HH:MM[:ss[.uuu]][TZ] format."]
hi i am getting the rss feed as xml and i am parsing , but date an time zone throwing error my model field models.DateTimeField(blank=True, null=True) my xml date and time format <pubDate>Tue, 02 Jul 2019 16:43:41 +0530</pubDate> error is ["'Tue, 02 Jul 2019 08:11:45 +0530' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] so how save this date and time with +0530 or with out +0530 ? -
mod_wsgi error: ModuleNotFoundError: No module named 'django'
I am trying to deploy very basic Django application with Apache 2.4 on Ubuntu 18.04 without using a virtual environment. When wsgi.py executes, it cannot find django module. I have tried setting sys.path in wsgi, various solutions that define different configuration settings for 000-default.conf. Changing ownership of site-packages folder to www-data for Apache, but nothing seems to work. I could make it work using virtualenv but for production server, I do not want to use virtualenv. I can import django in Python's command line without an issue. Following is my sample.tst.conf, if have already activated it using a2ensite command. ServerName sample.tst ServerAdmin webmaster@sample.tst DocumentRoot /var/www/html <Directory /home/raza/projects/sample/sample> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess sample python-path=/home/raza/projects/sample WSGIProcessGroup sample WSGIScriptAlias / /home/raza/projects/sample/sample/wsgi.py <Location /> WSGIProcessGroup sample </Location> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined How can I fix this problem? I am struggling with this issue for more than a week. I am a very experienced programmer but very new to Linux, python, and Apache platform, so I may be making some obvious mistake. I get following error in Apache log file: [Tue Jul 02 18:05:22.458785 2019] [wsgi:error] [pid 12490] [remote 10.10.10.99:51170] mod_wsgi (pid=12490): Target WSGI script '/home/raza/projects/sample/sample/wsgi.py' cannot be loaded as … -
I tried to update image in my app but in database its storing only file name and the file is not getting uploaded?
In my app i have a details where user can view and update their details.I tried to update image in my app but in database its storing only file name and the file is not getting uploaded? If i create a user and upload profile pic its uploading to respective folder.But if i update its not uploading that pic to respective folder rather its storing only file name in database. def accountdetails(request,pk): user=User.objects.get(pk=pk) initial_values= {'Firstname':user.first_name,'Lastname':user.last_name, 'Username':user.username,'Email':user.email} if request.method == "POST": form = Accountdetails(request.POST,request.FILES) if form.is_valid(): email = form.cleaned_data['Email'] Username=form.cleaned_data['Username'] firstname=form.cleaned_data['Firstname'] lastname=form.cleaned_data['Lastname'] user=User.objects.filter(pk=pk).update (first_name=firstname,last_name=lastname, username=Username,email=email) Profile.objects.filter(user_id=pk).update(image = request.FILES['picture']) messages.success(request,'Updated Successfully!') return redirect('accountdetails', pk=pk) -
os.listdir showing deleted files
Using os.listdir to get files of a folder and os.remove to remove files from it and files are still listed after being removed until Django server is restarted. Is it any way to avoid having to restart the server to get the "correct" file list? -
How can I access two models connected by a foreignkey for a DetailView and a CreateView?
I am building a wiki and need to save every revision made for each wikipage. This means that i need a new revision tabel for every wikipage created. I then need to access that information for the template. models.py class Wikipage(models.Model): title = models.CharField(max_length=100) date_created = models.DateTimeField('Created', auto_now_add=True) def __str__(self): return self.title class Meta: verbose_name_plural = "Wikipages" class Revison(models.Model): wikipage = models.ForeignKey(Wikipage, null=True, on_delete=models.CASCADE, related_name='revison') content = models.TextField('Content') author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) last_edit = models.DateTimeField('Last edit', auto_now=True) comment = models.TextField('Comment', blank=True) class Meta: verbose_name = 'Revison' verbose_name_plural = 'Revisons' ordering = ['-last_edit'] get_latest_by = ['last_edit'] def __str__(self): return self.content I wanted to use the DetailView and CreateView that comes with django, but I have not succeeded in accessing specific data from both tables. I have gotten the ListView to work correctly, but that only needs the title from Wikipage, and nothing from Revision. -
How can i search by tag name and if post published
i have 2 problems; the first one; How can i search by tag name tag model is manytomanyfield. the last one; if post published, show posts by tag name. i take published posts using this code " post_list=Post.objects.published()". However, i don't know how can i use filter and published Models.py class PostQuerySet(models.QuerySet): def active(self): return self.filter(status__in=[Post.STATUS_PUBLISHED]) def published(self): return self.filter(status=Post.STATUS_PUBLISHED) class Post(models.Model): STATUS_DRAFT = 1 STATUS_PUBLISHED = 2 STATUSES = ( (STATUS_DRAFT, 'Draft'), (STATUS_PUBLISHED, 'Published'), ) category=models.ManyToManyField(Category) tag=models.ManyToManyField(Tag) user=models.ForeignKey(User,on_delete=models.CASCADE,verbose_name="Yazar",related_name='posts') title=models.CharField(max_length=120,verbose_name="Başlık") content=RichTextField(verbose_name="İçerik") created_date=models.DateTimeField(auto_now_add=True,verbose_name="Oluşturulma Tarihi") updated_date=models.DateTimeField(auto_now=True,verbose_name="Güncellenme Tarihi") image=models.ImageField(null=True,blank=True) slug=models.SlugField(max_length=130,unique=True) status = models.SmallIntegerField(choices=STATUSES) objects = PostQuerySet.as_manager() views.py def post_index(request): #post_list=Post.objects.published().order_by('-created_date') post_list=Post.objects.published() query=request.GET.get('q') if query: post_list=post_list.filter( Q(content__icontains=query)| Q(title__icontains=query) | Q(tag_name__icontains=query)| # doesn't work Q(user__first_name__icontains=query)).distinct()... -
How to process data from one model field to another
I have models of Exercise, Training and Workout. Training contains some exercises (Exercise) Workout contains trainings (Training). Snippet of my models.py: class Exercise(models.Model): user = models.ForeignKey(User, related_name='exercises', on_delete=models.CASCADE) name = models.CharField(max_length=80) description = models.TextField(max_length=300) details = models.ManyToManyField(ExerciseDetail, blank=True) ... class Training(models.Model): user = models.ForeignKey(User, related_name='trainings', on_delete=models.CASCADE) name = models.CharField(max_length=80) description = models.CharField(max_length=250) exercises = models.ManyToManyField(Exercise, related_name='trainings', blank=True) ... class Workout(models.Model): user = models.ForeignKey(User, related_name='workouts', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) name = models.CharField(max_length=200) description = models.TextField(max_length=400, blank=True) trainings = models.ManyToManyField(Training, related_name='workouts', blank=True) ... I would like to have possibility to use something like Workout.objects.get(name='workout').exercises.objects.all() to get a list/set of all exercises included in trainings of chosen Workout. Can someone give a hint how can I do that? -
How to make a form field readonly with the HTML attribute readonly instead of disabled
I want to make my field in a form to be readonly. I have already used disabled in forms but it doesn't send my data to the database when POST request is triggered by the Form. site_location = forms.CharField(disabled=True) So, I inspected the element and manually added readonly attribute to its HTML code to check if readonly is working or not. And readonly has no issues in submitting the form. But disabled tells me that my form is invalid. Readonly and Disabled have some differences according to this answer: What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields? How can I use the readonly in forms instead of disabled??