Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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?? -
invalid character in identifier in django
I am writing a simple code in django Code: status = self.get_object() owner = status.owner_id print("status.status ", status.status) if (status.status == "Active"): subject = 'Yantraksh-RFQ Status' message = 'You have succesfully raised RFQ' # shipper_email reci = Teacher.objects.filter(user_id=owner).values_list("shipper_email", flat=True) email_from = settings_bak.EMAIL_HOST_USER send_mail(subject, message, email_from, reci, fail_silently=False) But it is saying > SyntaxError: invalid character in identifier I am not able to find any error in the syntax, please help! error log: File "D:\Downloads-HDD\My work -- agg\django_school\classroom\views\teachers.py", line 220 reci = Teacher.objects.filter(user_id=owner).values_list("shipper_email", flat=True) ^ SyntaxError: invalid character in identifier -
How To Initialize A Value in ForeignKey Dropdown from View in Django
I need to set the value of my ForeignKey dropdown = to a url parameter when the form is rendered. I am able to successfully set other form fields to this value, but not the ForeignKey. I am trying to initialize the 'reference' form field which is a foreign key using the reference_id value which is passed via the url. I can successfully assign this value to the three other fields in the form, but not to 'reference'. Models.py class Manifests(models.Model): reference = models.ForeignKey(Orders) cases = models.IntegerField() description = models.CharField(max_length=1000) count = models.IntegerField() def __str__(self): return self.description Forms.py class CreateManifestForm(forms.ModelForm): class Meta: model = Manifests fields = ('reference', 'cases', 'description', 'count') Views.py def add_manifest(request, reference_id): if request.method == "POST": form = CreateManifestForm(request.POST) if form.is_valid(): instance = form.save(commit=False) try: order = Orders.objects.get(id=reference_id) except Orders.DoesNotExist: pass instance.reference = order instance.save() return redirect('add_manifest', reference_id=reference_id) #this is where my problem is form = CreateManifestForm(initial={'reference': reference_id}) reference = request.POST.get('reference') manifests = Manifests.objects.all().filter(reference=reference) context = { 'form': form, 'reference_id': reference_id, 'manifests' : manifests, } return render(request, 'add_manifest.html', context) And just in case it's needed: urls.py url(r'^add_manifest/(?P<reference_id>\d+)/$', add_manifest, name='add_manifest'), There are no errors, but the field does not set to the value passed through the URL. Like … -
Django SingleTableView object has no attribute 'filter'
When I am rendering a table from a legacy MySQL database using the class-based (SingleTableView) view I recieve the following message: "...object has no attribute 'filter'" I am trying to visualize the table by following the solution from Nicolas Kuttler (https://kuttler.eu/en/post/using-django-tables2-filters-crispy-forms-together/?c=208349) and the solution from this ticket: How do I filter tables with Django generic views?. When I deployed the solution initially it worked well, meaning that I saw the filter, and the table, but at some point the error message appeared. As I am being a beginner in web-developing I have no idea on what am I doing wrong, therefore I would greatly appreciate an advise of the wise community =) #tables.py import django_tables2 as tables from .models import ValuesModel class ValuesModelTable(tables.Table): export_formats = ['csv', 'xls'] col1 = tables.Column(accessor='pk_t.pk_type.type1', verbose_name='Column One') .... class Meta: model = ValuesModel template_name = 'django_tables2/bootstrap.html' .... +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #filters.py import django_filters class ValuesModelFilter(django_filters.FilterSet): col1 = django_filters.CharFilter(field_name='pk_t__pk_type__type1', lookup_expr='icontains', label='Column One') .... +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #forms.py from .models import ValuesModel from crispy_forms.helper import FormHelper class ValuesModelListFormHelper(FormHelper): form_method = 'GET' model = ValuesModel form_tag = False +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #utils.py from django_tables2 import SingleTableView class PagedFilteredTableView(SingleTableView): filter_class = None formhelper_class = None context_filter_name = 'filter' def get_quryset(self, **kwargs): qs = super(PagedFilteredTableView, self).get_queryset() … -
Django how to get file path defined in the custom field
I'm using Django 2.2 and Django REST Framework. I'm writing a custom DRF serializer field, extending the JSONField to perform validation using jsonschema. I have defined the path of the scheme in the myapp.serializers like class MySerializer(serializers.Serializer): j_data = JSONSchemaField(schema='json_schema/validate.json') The file is saved in the myapp/json_schema/validate.json and the JSONSchemaField is defined in a file outside the application. json_validate.py class JSONSchemaField(JSONField): def to_internal_value(self, data): // Get file path here. return super().to_internal_value(data) How can I get the path to the schema in the JSONSchemaField class? -
Django get certain object from paginated object. Like `after` in Apollo
I am trying to implement Ariadne to my django app. I got problem with pagination. Well i am using django's default pagination. Thing is i want to select after certain objects in paginated queryset. Here is my resolver. So there is an after argument which would be optional but when provided i have to fetch from paginated queryset right after it's value. In this case after="some-UUID" def resolve_artist_releases(artist, *_, single=None, first=10, skip=1, after=None, last=None): albums = artist.album_set.all() if single is None else artist.album_set.filter(single=single) p = Paginator(albums.order_by("-created_dt"), first) if last: p = Paginator(albums.order_by("created_dt"), last) return p.page(skip).object_list Can you guys help me on this? -
Model instances saved only partially
I have a fairly complex view with several subforms and formsets with both many-to-many and one-to-one relationships. When getting a form from context object, I'm hitting a weird issue that some of the data is not saved. Correct model instance is created with form.save(), I can see all the fields I filled out in form, but all that's added to the database is pk, all the fields are empty. The same happens when I'm saving with commit=False and then saving again, when I'm updating fields manually and then saving or when I'm using force_insert=True. Creating new instances in the same code block however are saved without an issue. This doesn't end here, when saving many-to-many relationships, child models are saved without a hitch, but most of the time, m2m through models are not created. I said most of the time, because every once in a while they are. But even if they're not, the id descriptor in database is incremented so what I'm seeing in the through table is few lines, much less than there should be with non-sequential id-s. What am I dealing with here, does anybody have a clue? I'm out of ideas what to try next. I …