Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'file' object has no attribute '_committed' - django
I need to create a record with a one-to-one relationship and another field, the model of the one-to-one relationship has a filefield, when I create it, it throws me the error of the title. This is my code. Models class Proyecto(models.Model): user = models.CharField(max_length=50) nombre_p = models.CharField(max_length=50) descripcion_p = models.CharField(max_length=50) file_arff = models.FileField(upload_to='arff') def __unicode__(self): return str(self.file_arff) class Escenario(models.Model): proyecto = models.ForeignKey(Proyecto) file_txt = models.FileField(upload_to='txt/') View id_proyecto = Proyecto.objects.get(pk=request.session['proyecto_id']) escenario = Escenario(proyecto=id_proyecto, file_txt=file_txt) escenario.save() throw me this error : AttributeError: 'file' object has no attribute '_committed' -
Django table doesn't exist after migration
I'm developing a test app in Google App Engine with Django + Python 3.7; I successfully launched the test app and created a new app both at local side and on app engine server. Now I'm trying to create a little bit more complex model. I created the model + view + url file and template and migrated it (with an apparent success), but if I try to visualize the template at the local server, I retrieve this error: ProgrammingError at / (1146, "Table 'djangoseo.keywords_keywords' doesn't exist") I tried to migrate the model another time, used syncdb command with no success. This is the model from django.db import models class Keywords(models.Model): keyword_name = models.CharField(max_length=200) keyword_tags = models.ManyToManyField('Tags') keyword_urls = models.ManyToManyField('Urls', through='Rankings') avg_volume = models.IntegerField(default=0) jan_volume = models.IntegerField(default=0) feb_volume = models.IntegerField(default=0) mar_volume = models.IntegerField(default=0) apr_volume = models.IntegerField(default=0) may_volume = models.IntegerField(default=0) jun_volume = models.IntegerField(default=0) jul_volume = models.IntegerField(default=0) aug_volume = models.IntegerField(default=0) sep_volume = models.IntegerField(default=0) oct_volume = models.IntegerField(default=0) nov_volume = models.IntegerField(default=0) dec_volume = models.IntegerField(default=0) intent = models.CharField(max_length=200) micromoment = models.CharField(max_length=200) language = models.CharField(max_length=200) addedby = models.CharField(max_length=200) def __str__(self): return self.keyword_name class Tags(models.Model): tag_name = models.CharField(max_length=200) addedby = models.CharField(max_length=200) def __str__(self): return self.tag_name class Urls(models.Model): url_name = models.CharField(max_length=300) domain = models.CharField(max_length=200) def __str__(self): return self.url_name … -
Google Translation API id blocking ip address for too many requests
I'm setting up a Django Views that requests products data from an API, parse them with BeautifulSoup, apply the googletrans module and save the response into my Postgresql database. Everything was working fine yesterday until suddenly, Google blocked access on my IP address for too many requests at once.. I just turned on my LTE to change my IP address and it worked. But now, to make sure that it doesn't happen with this IP address again I need to find a way to call the googletrans API in batches or any other solution that would prevent me from getting blocked again. This is my Views: from bs4 import BeautifulSoup from googletrans import Translator import requests import json def api_data(request): if request.GET.get('mybtn'): # to improve, == 'something': resp_1 = requests.get( "https://www.headout.com/api/public/v1/product/listing/list-by/city?language=fr&cityCode=PARIS&limit=5000&currencyCode=CAD", headers={ "Headout-Auth": HEADOUT_PRODUCTION_API_KEY }) resp_1_data = resp_1.json() base_url_2 = "https://www.headout.com/api/public/v1/product/get/" translator = Translator() for item in resp_1_data['items']: print('translating item {}'.format(item['id'])) # concat ID to the URL string url = '{}{}'.format(base_url_2, item['id'] + '?language=fr') # make the HTTP request resp_2 = requests.get( url, headers={ "Headout-Auth": HEADOUT_PRODUCTION_API_KEY }) resp_2_data = resp_2.json() descriptiontxt = resp_2_data['contentListHtml'][0]['html'][0:2040] + ' ...' #Parsing work soup = BeautifulSoup(descriptiontxt, 'lxml') parsed = soup.find('p').text #Translation doesn't work translation = … -
object of type 'User' has no len()
I got a project that was not developed by me. I'm redoing him now. Tell me why this error occurs? For traceback I can not even understand where to look. Perhaps need to look for the cause in the template? Django 1.11 Traceback: File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 217. response = self.process_exception_by_middleware(e, request) File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 215. response = response.render() File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/template/response.py" in render 107. self.content = self.rendered_content File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/template/response.py" in rendered_content 84. content = template.render(context, self._request) File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/template/backends/django.py" in render 66. return self.template.render(context) File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/template/base.py" in render 207. return self._render(context) File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/test/utils.py" in instrumented_test_render 107. return self.nodelist.render(context) File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/template/base.py" in render 990. bit = node.render_annotated(context) File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/template/base.py" in render_annotated 957. return self.render(context) File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render 177. return compiled_parent._render(context) File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/test/utils.py" in instrumented_test_render 107. return self.nodelist.render(context) File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/template/base.py" in render 990. bit = node.render_annotated(context) File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/template/base.py" in render_annotated 957. return self.render(context) File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render 177. return compiled_parent._render(context) File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/test/utils.py" in instrumented_test_render 107. return self.nodelist.render(context) File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/template/base.py" in render 990. bit = node.render_annotated(context) File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/template/base.py" in render_annotated 957. return self.render(context) File "/home/m0nte-cr1st0/.virtualenvs/midgard/local/lib/python2.7/site-packages/django/template/loader_tags.py" … -
Make Django-Rest-Framework API specific for the User (url/username)
My Django Backend is built up like this: We have Studyplans, that have tasks connected to them. Right now I get the studyplans via a url that looks something like this: 'url:8000/database/studyplans'. What I want is to get the studyplans connected to the user your logged in to. So the url would look something like this: 'url:8000/database/studyplans/WilliamABC', or some other user: 'url:8000/database/studyplans/Bruce123' Models: from django.db import models from datetime import date #Create your models here. class StudyplanTask(models.Model): title = models.CharField(max_length=150) description = models.CharField(max_length=1000, blank=True) state = models.CharField(max_length=20) doneby = models.DateField(default=date.today) class Meta: verbose_name_plural = 'Tasks' def __str__(self): return self.title class StudiePlan(models.Model): title = models.CharField(max_length=150) description = models.CharField(max_length=1000) tasks = models.ManyToManyField(StudyplanTask, blank=True) doneby = models.DateField(default=date.today) class Meta: verbose_name_plural = 'Studyplans' def __str__(self): return self.title Serializers: from rest_framework import serializers from .models import StudiePlan, StudyplanTask class StudyplanTaskSerializer(serializers.ModelSerializer): class Meta: model = StudyplanTask fields = ('id', 'title', 'description', 'state', 'doneby') class StudyplanTaskNameSerializer(serializers.ModelSerializer): class Meta: model = StudyplanTask fields = ('id', 'title', 'description', 'state', 'doneby') class StudyplanSerializer(serializers.ModelSerializer): tasks = StudyplanTaskNameSerializer(many=True, read_only=True) class Meta: model = StudiePlan fields = ('id', 'title', 'description', 'tasks', 'doneby') Views: from django.shortcuts import render from rest_framework import viewsets, permissions from .models import StudiePlan, StudyplanTask from .serializers import StudyplanSerializer, StudyplanTaskSerializer # … -
How to build a clean method for a formset?
I'm wondering how can I check the validation of a formset. Let me explain my case. I have a five forms which are contained in a formset. Each form represent a set of a Volleyball match (a Volleyball match is played in 5 sets). I want to be able to submit my formset if there are already three forms that represent a win, because if I have for example the first three sets won by the team one, the fourth and fifth sets are useless to be played, the match is over when there are three winning sets. I don't know if I was very clear... So I'd like to build some validation like this one. If I can have the method, or an example to help me it will be nice. The formset is MatchSetFormset. You'll find my forms.py down bellow : forms.py class SetUpdateForm(forms.ModelForm): class Meta: model = Set fields = [ 'scoreTeam1', 'scoreTeam2', 'match', ] def clean(self): cleaned_data = super().clean() scoreTeam1 = cleaned_data.get("scoreTeam1") scoreTeam2 = cleaned_data.get("scoreTeam2") if cleaned_data.get("match") is not None: sport = cleaned_data.get("match").phase.tournament.sport if scoreTeam1 and scoreTeam2: if scoreTeam1 == scoreTeam2: raise forms.ValidationError("Scores can't be equal") if scoreTeam1 > sport.nbPointPerSet or scoreTeam2 > sport.nbPointPerSet or (scoreTeam1 … -
How to fire m2m_changed signal only once after all changes are made, in Django?
I have the following models in my project: class Topping(models.Model): name = models.CharField(max_length=255) class Pizza(models.Model): name = models.CharField(max_length=255) toppings = models.ManyToManyField(Topping, blank=True) def save(self, *args, **kwargs): print('Saving...') if self.pk: for topping in self.toppings.all(): print(topping.name) super(Pizza, self).save(*args, **kwargs) def toppings_changed(sender, instance, **kwargs): instance.save() m2m_changed.connect(toppings_changed, sender=Pizza.toppings.through) Basically, whenever toppings is changed, the signal is fired. All the signal does is call the Pizza object's save method. Anyway, lets say I have three objects: pizza = Pizza.objects.get(pk=1) # Number of toppings is 0 topping1 = Topping.objects.get(pk=1) topping2 = Topping.objects.get(pk=2) Now, I want to set the two toppings to my pizza. I do this using the following code: pizza = Pizza.objects.get(pk=1) pizza.toppings.set([1, 2]) The toppings are set correctly, however, the pizza's save method is called twice, because the m2m_changed signal is called twice, as there are two changes happening. How can I call this only once after all of the changes has been committed? To clarify, I want both of the toppings to be added, but I want to fire my signal only once, at the end of all the changes. Thanks for any help. -
How to fix this problem with clean method in forms.ModelForm?
I'm doing a application to upload Images. I need validation of one of two fields. By file or by url. I wrote such code, but the view method does not call clean_image in forms.py. Thanks for the help (sorry for my bad English) forms.py class UploadForm(forms.ModelForm): image = forms.ImageField(required=False) url = forms.CharField(max_length=64, required=False) class Meta: model = Image fields = ( 'image', 'url' ) def clean_image(self): image = self.cleaned_data.get('image') url = self.cleaned_data.get('url') if (image != None and url != '') or (image == None and url == ''): raise forms.ValidationError('Fill one field') def save(self): self.clean_image() new_image = Image.objects.create( image=self.cleaned_data.get('image'), url=self.cleaned_data.get('url') ) return new_image views.py def upload(request): if request.method == 'POST': upload_form = UploadForm(request.POST, request.FILES) if upload_form.is_valid(): upload_form.save() return redirect('/') else: upload_form = UploadForm() context = { 'form': upload_form, } return render(request, 'upload_page.html', context) -
Django does not find Pillow though installed
Django struggles to find Pillow and I'm not quite sure why. Environment Linux Alpine based Docker image, Django 2.2. Here are the relevant parts of: The Dockerfile RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev jpeg-dev zlib-dev \ && apk add --no-cache mariadb-dev mariadb-client # install dependencies RUN pip install --upgrade pip RUN pip install pipenv RUN pip install mysqlclient COPY ./Pipfile /usr/src/cms/Pipfile RUN pipenv install --skip-lock --system --dev RUN apk del build-deps The Pipfile [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] [packages] django = "==2.2" markdown = "==3.1.1" pillow = "==5.0.0" [requires] python_version = "3.7" The issue When I run python manage.py runserver 0.0.0.0:8000 from the container, I get the following error: django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: website.Photo.photo: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "pip install Pillow". which is weird because pip install Pillow gives me Requirement already satisfied: Pillow in /usr/local/lib/python3.7/site-packages (5.4.1) About Pillow's conflict with PIL While having a look at /usr/local/lib/python3.7/site-packages, I noticed that I had both PIL and Pillow. Is this: the source of a conflict (Pillow's documentation) is quite specific about the … -
django pandas dataframe download as excel file
I have a Django app that will be placed in a Docker container. The app prepares data in Dataframe format. I would like to allow the user to download the data to his/her local drive as excel file. I have used df.to_excel in the past, but this won't work in this case. Please advise best way to do this. -
Radio Button with default selection in Django
I had the same doubt of radio button in model file. I want it to be a compulsory/required field with default selection to "No". Fields available would be - Yes/No. Any suggestions. B_CHOICES = [('P','Positive'),('N','Negative')] Tag_Type = models.CharField(choices=B_CHOICES, max_length=128) -
How can I make Materialize render in React component?
I am building a simple Django-React application while using Materialize CSS and I have a contact form that I would like for users to pick a date, how do I get the datepicker to show in the Contact component? I realize that when I navigate to the Contact component, the datepicker does not work whereas if I just import the Contact component into the main App component, the datepicker works perfectly! Please what could be wrong? It works when I stick the Contact component in the App.js component <BrowserRouter> <Fragment> <Header /> <Switch> <Route exact path="/" component={Home} /> <Route path="/contact" component={Contact} /> <Route path="/about" component={About} /> </Switch> <Contact /> <Footer /> </Fragment> </BrowserRouter> ``` </Provider> But the date picker and indeed any plugin for that matter that requires initialization in Materialize css does not work -
Django "ValueError: embedded null byte"
I just installed Django and changed the DATABASES from sqlite3 to mysql in settings.py, but when I runserver, "ValueError: embedded null byte" occurs occasionally. What should I do? Python 3.6.1 Django version 2.2.1 (myproject) bash-3.2$ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). 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 "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 95, in handle self.run(**options) File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 577, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 562, in start_django reloader.run(django_main_thread) File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 280, in run self.run_loop() File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 286, in run_loop next(ticker) File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 326, in tick for filepath, mtime in self.snapshot_files(): File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 342, in snapshot_files for file in self.watched_files(): File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 241, in watched_files yield from iter_all_python_module_files() File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", line 103, in iter_all_python_module_files return iter_modules_and_files(modules, frozenset(_error_files)) File "/Users/mydir/.virtualenvs/myproject/lib/python3.6/site-packages/django/utils/autoreload.py", … -
HEROKUJAPENESERANDI
kya madarchod hai heroku bhenkaloda -
Django raw query giving same result on all models
I have 3 models Product, Photo, and ProductLikeDilike. I am performing left outer join on all the 3 models. First I am joining Product with Photo and then the resultant table(temp) I am joining with ProductLikeDilike. Below is the raw sql. Note: olx is the name of django app. data = Product.objects.raw('select * from (select olx_product.id,olx_product.name,olx_photo.file,olx_photo.cover_photo_flag from olx_product left outer join olx_photo on (olx_product.id=olx_photo.reference_id_id) where olx_photo.cover_photo_flag="yes" or olx_photo.cover_photo_flag is null) as temp left outer join olx_productlikedislike on (temp.id=olx_productlikedislike.product_id_id and olx_productlikedislike.product_liked_by_id_id=2)') for x in data: print(x.name) What I want to understand that when I use any of the above 3 models to run the raw sql why I am getting the same result i.e. When I do data = Product.objects.raw('select *.....') for x in data: print(x.name) or data = Photo.objects.raw('select *......') for x in data: print(x.name) or data = ProductLikeDislike.raw('select *.....') for x in data: print(x.name) I am getting the same result. Why? Please help me to understand this. -
How can I test the emailfield validator in django?
I started creating tests for my app. I found some ways to test several things but also wanted to test the email field validator. Who know what can go wrong and when it would come in handy. But basically I just want to know how to do this. So far I tried several Error codes (integrity, value, validation) but all of them caused an error. Searching on the items is rather difficult for the key words, but I did found some angles. None of them worked and, well, I could look for the wrong clues as well. This is what I have: def test_not_an_email(self): self.assertRaises( ValueError, MyUser.objects.create_user, email='jan@pietnl', password='abcd1234' ) But the error message I get is this: django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_myuser.email ====================================================================== FAIL: test_not_an_email (accounts.tests.UserRegistrationTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\xxxxxxxxxxxxxxx\tests.py", line 26, in test_not_an_email MyUser.objects.create_user, email='jan@pietnl', password='abcd1234' AssertionError: ValueError not raised by create_user ---------------------------------------------------------------------- Ran 2 tests in 2.603s FAILED (failures=1, errors=1) Destroying test database for alias 'default'... I thought the test should be correct. What am I doing wrong? Anything that makes me learn to understand this better is much appreciated. -
can't set cookies with ajax and django rest-framework api but with postman it is working?
When I send post request through Postman tool everything works fine. it showing cookies and login but when I try to login from browser it sends response login successfully but not sending any cookie and when I check cookies in developer option it is not showing any cookies. "Sorry I don't know where I am facing problem that's why I copied more code" I am using django-rest-registration: https://github.com/apragacz/django-rest-registration And this is cors-header: https://github.com/ottoyiu/django-cors-headers my django project CORS settings... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_registration', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ORIGIN_WHITELIST = [ 'localhost:63342', ] #CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'cache-control', 'content-length', 'Host', 'Connection', ) This is code of postman which working fine.... var settings = { "async": true, "crossDomain": true, "url": "http://localhost:8000/api/v1/accounts/login/", "method": "POST", "headers": { "Content-Type": "application/json", "User-Agent": "PostmanRuntime/7.13.0", "Accept": "*/*", "Cache-Control": "no-cache", "Postman-Token": "7d5ae21a-9f8c-4178-a2bf-265a53fbfd3f,b500d1d0-4f89-4b2a-a4cc-3aeb5a4e5e62", "Host": "api.dealord.com", "accept-encoding": "gzip, deflate", "content-length": "50", "Connection": "keep-alive", "cache-control": "no-cache" }, "processData": false, "data": "{\n\t\"login\": \"temp1\",\n\t\"password\": \"password\"\n}" } $.ajax(settings).done(function (response) { console.log(response); }); This is my code.... var data = { "login": 'temp1', "password": 'password', }; $.ajax({ "async": … -
Django: Display first Choice Value from tuple
Models.py class Person(models.Model): name = models.CharField(max_length=200) CATEGORY_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=200, choices=CATEGORY_CHOICES) to_be_listed = models.BooleanField(default=True) views.py def index(request,gender): all_details = { 'list': Person.objects.filter(type=gender).order_by('-id'), 'type':category, } return render(request,'index/person.html',context=all_details) On the template, when I call person.gender, I get 'Male' or 'Female' instead of 'M' or 'F'. How to display the value ('M' or 'F') instead of the code ('Male'/'Female')? -
How to make queries from multiple models in a single view
Please, I am working on a school placement system and I have multiple models to query from. First I want to loop through the students' list and check if the two student's ID in the profile and result model match. Then I will check if the student has passed and then place the student. I am using Django 2.2.1. I did a lot of search but to no avail. Please, I need help. Below are some of my codes. Here is my student model. class StudentProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # Extra Fields student_ID = models.CharField(max_length=10) middle_Name = models.CharField(max_length=50, blank=True) gender = models.CharField(max_length=10, choices=STUDENT_GENDER_CHOICES) disability = models.CharField(max_length=5, choices=STUDENT_DISABILITY_CHOICES) locality = models.CharField(max_length=30, choices=STUDENT_LOCALITY_CHOICES) age = models.PositiveIntegerField() profile_picture = models.ImageField(upload_to='profile_photos', blank=True, default='profile_photos/default.svg') def __str__(self): return self.user.username This is my result upload model class StudentResultsUpload(models.Model): # student = models.ForeignKey(User, on_delete=models.CASCADE, null=True) student_ID = models.CharField(max_length=10) english = models.PositiveIntegerField() mathematics = models.PositiveIntegerField() integrated_Science = models.PositiveIntegerField() social_Studies = models.PositiveIntegerField() basic_Design_Technology = models.PositiveIntegerField() home_Economics = models.PositiveIntegerField() ghanaian_Language = models.PositiveIntegerField() french = models.PositiveIntegerField(blank=True) This is my school selection model. I have five of them and they are all the same except the name that changes. class SchoolSelectionOne(models.Model): student = models.ForeignKey(User, on_delete=models.DO_NOTHING) name_of_School = models.CharField(max_length=100) program = models.CharField(max_length=50) residential_Status … -
ValueError: invalid literal for int() with base 10: 'fee_code'
when i am running python manage.py migrate it gives me an error ValueError: invalid literal for int() with base 10: 'fee_code' kindly sove this problem i am trying to migrate my code from django.db import models from django.utils import timezone from students.models import gr_register, Classes, gardian class fees_type(models.Model): fee_code = models.AutoField(primary_key=True) fee_type = models.CharField(max_length=255, default=1) def __str__(self): return str(self.fee_type) class concession_type(models.Model): concession_code = models.AutoField(primary_key=True) concession_type = models.CharField(max_length=255, default=1) concession_percent = models.CharField(max_length=255, default=1) def __str__(self): return str(self.concession_type) class fees_source(models.Model): source_code = models.AutoField(primary_key=True) source_name = models.CharField(max_length=255, default='source_name') def __str__(self): return str(self.source_name) class class_fees(models.Model): class_code = models.ForeignKey(Classes, on_delete=models.CASCADE) fee_code = models.ForeignKey(fees_type, on_delete=models.CASCADE, default='fee_code') fees_amount = models.BigIntegerField(default=1000) def __str__(self): return str(self.fees_amount) class fee(models.Model): BOOL_CHOICES = ((True, 'Yes'), (False, 'No')) Gr_num = models.ForeignKey(gr_register, on_delete=models.CASCADE, default=231) fee_code = models.ForeignKey(fees_type, on_delete=models.CASCADE, default=1) fee_dues = models. BigIntegerField(default=1000) paid_source = models.ForeignKey(fees_source, on_delete=models.CASCADE, default=1) class_name = models.ForeignKey(Classes, on_delete=models.CASCADE, default=1) paid = models.BooleanField(choices=BOOL_CHOICES, default=1) guradian_code = models.ForeignKey(gardian , on_delete=models.CASCADE, default=1) due_date = models.DateField(default=timezone.now) paid_date = models.DateField(default=timezone.now) def __str__(self): return str(self.paid) urls.py path('', views.index, name='index'), path('feestype/', views.feestype, name='feestype'), path('addfeestype/', views.addfeestype, name='addfeestype'), path('editfeestype/<int:pk>/', views.editfeestype, name='editfeestype'), path('deletefeestype/<int:pk>/', views.deletefeestype, name='deletefeestype'), path('concessiontype/', views.concessiontype, name='concessiontype'), path('addconcession/', views.addconcession, name='addconcession'), path('editconcession/<int:pk>/', views.editconcession, name='editconcession'), path('deleteconcession/<int:pk>/', views.deleteconcession, name='deleteconcession'), path('feessource/', views.feessource, name='feessource'), path('addfeessource/', views.addfeessource, name='addfeessource'), path('editfeessource/<int:pk>/', views.editfeessource, name='editfeessource'), path('deletefeessource/<int:pk>/', views.deletefeessource, name='deletefeessource'), path('classfees/', … -
Expand the possibility to put offline a post after an event
I'm trying to expand the function that I've showed in this question using this code: @property def is_expired(self): print(self.publishing_date) if self.membership == "One Month": if self.publishing_date + datetime.timedelta(days=30) < datetime.datetime.now(): message = 'Scaduto' return message else: expiring_date = self.publishing_date + datetime.timedelta(days=30) delta = expiring_date - datetime.datetime.now() return delta else: if self.publishing_date + datetime.timedelta(days=365) < datetime.datetime.now(): message = 'Scaduto' return message else: expiring_date = self.publishing_date + datetime.timedelta(days=365) delta = expiring_date - datetime.datetime.now() return delta return False I want to use this new template: {% for asset in user_details.authorized_user_set.all %} {% if not asset.is_expired %} <tr> <td class="text-left"><p><strong><a class="text-info" href="{{ asset.get_absolute_url }}">{{ asset.title }}</a></strong></p></td> <td class="text-center"> {% if asset.type == "3D Region" %} <p class="badge badge-pill badge-primary">{{ asset.type }}</p> {% elif asset.type == "3D Village" %} <p class="badge badge-pill badge-secondary">{{ asset.type }}</p> {% else %} <p class="badge badge-pill badge-success">{{ asset.type }}</p> {% endif %} </td> <td class="text-right"><p>{{ asset.publishing_date }}</p></td> <td class="text-center"> {% if asset.membership == "One Month" %} <p class="badge badge-pill badge-warning">{{ asset.membership }}</p> {% else %} <p class="badge badge-pill badge-danger">{{ asset.membership }}</p> {% endif %} </td> <td class="text-right"><p>{{ asset.expiring_date }}</p></td> </tr> {% endif %} {% endfor %} Inside Django administration panel I can see all that I want corrctly, as you … -
Distinct on union sub query with Django
I write query in SQL but I don't know how to convert this query to Django ORM: SELECT DISTINCT ON ("id") "id", "name", "national_code", "phone_number", "weight" FROM ( ( SELECT "customer"."id", "customer"."name", "customer"."national_code", "customer"."phone_number", 1 AS "weight" FROM "customer" WHERE ("customer"."national_code" = '0012923409')) UNION ( SELECT "customer"."id", "customer"."name", "customer"."national_code", "customer"."phone_number", 3 AS "weight" FROM "customer" WHERE ("customer"."name"::text LIKE '%test%')) UNION ( SELECT "customer"."id", "customer"."name", "customer"."national_code", "customer"."phone_number", 2 AS "weight" FROM "customer" WHERE (customer"."phone_number" = '09352167214')) ) AS sub ORDER BY "id", 5 ASC limit 20 I try this code: customer_fields = {'id', 'name', 'national_code', 'phone_number'} q_by_national_code = self.only(*customer_fields) \ .filter(national_code__exact="0012923409")\ .annotate(weight=Value(1, output_field=IntegerField())) q_by_phone = self.only(*customer_fields) \ .filter(phone_number__exact='09352167214') \ .annotate(weight=Value(2, output_field=IntegerField())) q_by_name = self.only(*customer_fields) \ .filter(name__contains="test") \ .annotate(weight=Value(3, output_field=IntegerField())) final_query = q_by_national_code.union(q_by_name, q_by_phone) but when I use distinct function on final_query , there is not distinct query in final query. My union query may has duplicate rows base on id filed and because of weight field that I added to each union query, UNION doesn't remove duplicate rows. -
How to make the link appear in base.html in django
I am learning django, I added a new app, the link can be displayed in friendly_link.html, the code is as follows: admin.py from django.contrib import admin from .models import FriendlyLink admin.site.register(FriendlyLink) models.py from django.db import models class FriendlyLink(models.Model): title = models.CharField(max_length=100, default='', verbose_name='title') url = models.CharField(max_length=100, default='', verbose_name='url') class Meta: verbose_name_plural = 'links' def __str__(self): return self.title views.py from django.shortcuts import render from .models import FriendlyLink def friendly_link(request): friendly_link = FriendlyLink.objects.order_by('title') context = {'friendly_link': friendly_link} return render(request, 'friendly_link.html', context) urls.py from django.urls import re_path from . import views urlpatterns = [ re_path(r'^links$', views.friendly_link, name='friendly_link'), ] friendly_link.html {% extends "base.html" %} {% block title %}Links{% endblock %} {% block content %} <ul> {% for link in friendly_link %} <li><a href="{{ link.url }}">{{ link.title }}</a></li> {% empty %} {% endfor %} </ul> {% endblock %} I want the link to appear at the bottom of base.html. How do I change the code? Thank you. -
When trying set corsheaders in settings.py file
(corsheaders.E014) Origin 'http://localhost:4200/' in CORS_ORIGIN_WHITELIST should not have path .Im getting this error. CORS_ORIGIN_WHITELIST = ( 'http://localhost:4200/', ) Origin 'http://localhost:4200/' in CORS_ORIGIN_WHITELIST should not have path .Im getting this error. -
How to avoid provide server address when access ImageField url
I have created model - Profile - which presents user's profile. I have one field which is models.ImageFiled and I have method to get absolute url to this image. I have server in development role, so I've exposed /media folder. When I use full server URL it works. Is there any method to avoid put static web server address? # Profile class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) date_of_birth = models.DateField(blank=True, null=True) photo = models.ImageField(upload_to='users/%Y/%m/%d',blank=True) def __str__(self): return 'Profile for user {}'.format(self.user.username) @property def get_absolute_image_url(self): return "http://127.0.0.1:8000/{0}".format(self.photo.url) in settings.py MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media/')