Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Makemigrations and Migrate keep repeating
Something seems to be occurring with my django app. There are two models, one where I altered and the other a new addition. Ever since these two changes my makemigrations and migrate has continued to be the same changed with the migration number incrementing. When I makemigrations: Migrations for 'om': 0033_auto_20200122_0001.py: - Alter field delivery_date on growerpurchaseorderitem Migrations for 'accounts': 0105_auto_20200122_0001.py: - Alter field created on pushtoken - Alter field push_token on pushtoken And when I migrate Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states... DONE Applying accounts.0105_auto_20200122_0001... OK Applying om.0033_auto_20200122_0001... OK I have tried to fake a migration to get past this but no luck. It is an issue as any new changes are not registering to my models. -
No folder on ubuntu - clamd.scan/clamd.sock
I am trying to install a scanner for my Django application which refers to this place /var/run/clamd.scan/clamd.sock but I don't have the following folder on ubuntu 18+. I tried to install it using sudo apt-get install clamav but I still have no visible folery. How can I install it on ubuntu? or maybe he is in a different place. -
Django : TypeError at "?" __str__ returned non-string (type NoneType)
I tried to make a crud using Django but i got error TypeError at "?" __str__ returned non-string (type NoneType) the model : from django.db import models class Module(models.Model): Module = models.CharField("Module", max_length=255, blank = True, null = True) createdAt = models.DateTimeField("Created At", auto_now_add=True) def __str__(self): return self.Module class Matiere(models.Model): Matiere = models.CharField("Matiere", max_length=255, blank = True, null = True) ModuleId = models.ForeignKey(Module, on_delete=models.CASCADE) createdAt = models.DateTimeField("Created At", auto_now_add=True) def __str__(self): return self.Matiere the view error line: __str__ returned non-string (type NoneType) 34 <div class="col-md-1 col-xs-1 col-sm-1"></div> 35 <div class="col-md-10 col-xs-10 col-sm-10"> 36 <form method="post" novalidate> 37 {% csrf_token %} 38 {% for hidden_field in form.hidden_fields %} 39 {{ hidden_field }} 40 {% endfor %} 41 {% for field in form.visible_fields %} 42 <div class="form-group"> 43 {{ field.label_tag }} 44 {% render_field field class="form-control" %} 45 {% if field.help_text %} 46 <small class="form-text text-muted">{{ field.help_text }}</small> 47 {% endif %} 48 </div> 49 {% endfor %} 50 <button type="submit" class="btn btn-primary">post</button> 51 </form> 52 <br> 53 </div> 54 <div class="col-md-1 col-xs-1 col-sm-1"></div> i don't know how to fix this error ,i searched for error its seems the error in the model exactly in return self the last line but i … -
Django change object names in proxy model
I have a many to many field where Django creates the 'through' table automatically roomextra = models.ManyToManyField( to='hotel.RoomExtra', related_name='room_extra', verbose_name='room extra', ) This is part of a Room class. Both the Room class and RoomExtra class have methods def __str__ To define their object name. A proxy model was introduced to change some text on the Django admin for the through table created by Django: class RoomRoomExtraProxy(Room.roomextra.through): class Meta: proxy = True def __str__(self): return self.room.name + ' // ' + self.roomextra.name However, when you try and delete a room with a room extra you get the following on the 'Are you sure?' page: Summary - Rooms: 1 - Room-roomextra relationships: 1 Objects - Room: 1 - Room-roomextra relationship: Room_roomextra object (8) How do I override 'Room-roomextra' and 'Room_roomextra object (8)' so that they are more user friendly? -
Foreign Key on a customized Users model Django
I have the following 2 models User (customized) and Activity. A user can only be connected to 1 activity but an activity can be referenced from multiple User entries, thus, I have a Many-to-One relationship and I have created this relationship in the following way: Task app models.py from django.utils import timezone from django.contrib.auth import get_user_model User = get_user_model() class Task(models.Model): id = models.AutoField(primary_key=True) responsible = models.ForeignKey(User, on_delete=models.CASCADE) task = models.CharField(null=False, max_length=140) initial_date= models.DateField(default=timezone.now(), null=False) ending_date = models.DateField(default=timezone.now(), null=False) Accounts app models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("User must have an email address.") if not username: raise ValueError("User must have a username.") user = self.model(email=self.normalize_email(email),username=username,) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user(email=self.normalize_email(email),username=username,password=password,) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) # The following fields are required for every custom User model last_login = models.DateTimeField(verbose_name='last login', auto_now=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return … -
Send JSON to Django template
I have a very basic Django view that, once it receives a request, should send a response to the page that the user is visiting, so that i can display a message on that page, without having to refresh the page. Here is my view: def Action(request): response = '' if request.method == 'POST': if request.POST.get('ajaxform', False) == 'submit': data = request.POST.get('formdata', False) mymodel = Userdata() mymodel.save() response = 'Submitted!' return HttpResponse(json.dumps(response), content_type='application/json') Basically, when a POST request is received, this view should send a JSON response to the template with the message Submitted. This view works, when i'm browsing my template, on my Dev tools i can see the JSON response Submitted being received by the page, but i don't understand how can i show it using Jquery. Can someone point me out on how could i create a Jquery function that is triggered only when a Json response is received by a Django view? Basically, in this case, when the Django view fires the response Submitted, my Jquery function should receive that message and do some stuff with it. -
Why I get error when run two tests in Django APITestCase?
I make tests for my API. When I run two tests I get error apps.users.models.DoesNotExist: User matching query does not exist. in line self.user = User.objects.get(pk=48) on the second test. But if I run only one test, test is passed. What is the reason? class UsersTestCase(APITestCase): def setUp(self): user_data = [] for i in range(1, 124): user_data.append({ 'email': 'first@mail.com'+str(i), 'first_name': "firstname"+str(i), 'last_name': "lastname"+str(i), 'ip_address': "192.168.0."+str(i), }) users = User.objects.bulk_create([User(**i) for i in user_data]) self.user = User.objects.get(pk=48) # I get error in this line def test_users_list(self): ... def test_users_pagination(self): url = reverse('users-list') self.client.force_authenticate(self.user) response = self.client.get(url, {'users_count': 24, 'page': 2}) -
Using models in a scrape to access data
I'm using Django with BeautifulSoup to scrape a number of websites. I want to use a list of websites in a DB I have set up with my Django App to loop through some websites and grab some information I have a "Webpages" file with "models.py". This all works and I have set up a webpage that lists the websites in the DB I have then added a "Scrape.py" file and can successfully do a simple scrape by going to Git Bash and running "py scrape.py" However, I want to loop through the websites in my DB. To do so I thought I would need to do this first and then use it to fetch data from .webpages.models import Webpage But before I add any further code I get the error "ImportError: attempted relative import with no known parent package" I have also tried from webpages.models import Webpage But then I get the error "ModuleNotFoundError: No module named 'webpages'" I have searched online and found this guide, and followed but no such luck. As guide it asks you to place the following code in the file print('__file__={0:<35} | __name__={1:<20} | __package__={2:<20}'.format(__file__,__name__,str(__package__))) ... and the becomes clear as when I run … -
nginx working with ip but not domain name
I'm trying to set up a django app with gunicorn and ngix. I followed this tutorial. Everything seems to be working but when I edit the server_name in /etc/nginx/sites-available/project to anything other than the serevr ip address I get the default nginx index page instead of the django app. When this is the server config: server { listen 80; server_name <myserverip>; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/django/project; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } everything works as expected (nginx serves the app) when I put the ip address into my browser, but if the I add a domain name to replace the ip or in addition to the ip all I get is the nginx page in either location. My ALLOWED_HOSTS in settings.py includes the server ip and the domain name. I cannot see any issue in the nginx logs either. Not sure what the issue is at this point. -
How can I read a dictionary from database without it being turned into a string by django?
My database contains a dictionary. When I read the dictionary from the database and try to do something with it it fails because the dictionary has been automatically converted into a string. Any way to avoid Django turning the dict into a string? -
Django JSON structure for a javascript app
I am creating a course exam, but however the front end. I need to add some buttons created by javascript, but before creating the buttons needs to be done via API which needs key, value to be created correctly, but I am not getting as expected. models class Question(models.Model): text = models.CharField(max_length=200, blank=False, null=False) def __str__(self): return 'Question: ' + self.text class Answer(models.Model): text = models.CharField(max_length=200, blank=False, null=False) correct = models.BooleanField(default=False) question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='choices') def __str__(self): return 'Answer: ' + self.text class ActiveQuestion(models.Model): qid = models.UUIDField(primary_key=True, default=uuid.uuid4) question = models.ForeignKey(Question, on_delete=models.CASCADE) given_answer = models.ForeignKey(Answer, on_delete=models.CASCADE, related_name='given_answer_id', null=True) serializer class QuestionNoAnswerSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ('text', 'choices') class ActiveQuestionSerializer(serializers.ModelSerializer): question = QuestionNoAnswerSerializer() class Meta: model = ActiveQuestion fields = ('qid','question', 'given_answer_id') # read_only_fields = ('qid',) views class ActiveQuestionViewSet(viewsets.ViewSet): permission_classes = (AllowAny,) def list(self, request): random_question = Question.objects.order_by('?').first() active_question = ActiveQuestion(question=random_question) serializer = ActiveQuestionSerializer(active_question) active_question.save() return Response(serializer.data) desired json { "qid": "94109a2e-95ef-4ba5-bd95-46ebb2a12603", "question": { "text": "1sf", "choices": [ "id", "value" ] }, "given_answer": null } -
Django SQL setting up a default schema to all the tables
I am setting up a local environment for a project which is built with DJANGO+React and SQl I had my Sql connection set up like this DATABASES={ 'default': { 'ENGINE':'sql_server.pyodbc', 'NAME':'Test_Db', 'USER':'Test_User', 'PASSWORD':'************', 'HOST':'*******', 'PORT':'****', 'OPTIONS': { 'dsn':'FreeTDS', 'autocommit':True, } } } I was able to connect to database but for some reason there were new tables created back in database with new schema dbo and all the tables are empty. But I have all the user data in different schema app. where i need to connect and perform all the operations. When I am running the local server it's refrencing it to DBO where I don't have any data which resulting login errors. Is there any way I can set in manage.py or setting.py to consider app schema for all the models defined. -
How to fix QuerySet' object has no attribute issue?
I need to create the new object or just update if already existing. I receive: QuerySet' object has no attribute "seat". Don't know what I'm doing wrong. models: class rows_and_seats(models.Model): movie = models.ForeignKey(Movies, on_delete=models.CASCADE) row = models.CharField(max_length = 1) number = models.IntegerField() def __str__(self): return f'{self.movie}' class Reservation(models.Model): customer = models.ForeignKey(User, on_delete=models.CASCADE) movie = models.ForeignKey(Movies, on_delete=models.CASCADE) seat = models.ManyToManyField(rows_and_seats) ordered = models.DateTimeField(default=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), blank=True, null=True) def __str__(self): return f'{self.customer.username}:{self.movie.title}:{self.ordered}' views @login_required def buy_seats(request, pk): if request.method == "POST" and request.session.get("seats"): seats = request.session.pop("seats") movie = Movies.objects.get(pk=pk) customer = User.objects.get(pk=request.user.id) for s in seats: user_reserved_seats = rows_and_seats.objects.get(movie=movie, row=s[:1], number=int(s[2:])) reservation_check = Reservation.objects.filter(customer=customer, movie=movie) if reservation_check.exists(): reservation_check.seat.add(user_reserved_seats) else: new_reservation = Reservation.objects.create(customer=customer, movie=movie) new_reservation.seat.add(user_reserved_seats) messages.success(request,"You have succesfully reserved the seats.") return redirect("home") return redirect("home") My goal is to keep rows_and_seat in manyTomany in order to display only one reservation of user in admin panel, instead of the list of repeating itself titles. -
Command errored out with exit status 1:
I am trying to install django cookie-cutter but when I performed the command: pip install -r requirements\local.txt The command line shows the error: ERROR: Command errored out with exit status 1: command: 'c:\users\rahul\cookie\env\env\my_env\scripts\python.exe' 'c:\users\rahul\cookie\env\env\my_env\lib\site-packages\pip' install --ignore-installed --no-user --prefix 'C:\Users\rahul\AppData\Local\Temp\pip-build-env-adqz_mlm\overlay' --no-warn-script-location --no-binary :all: --only-binary :none: -i https://pypi.org/simple -- 'setuptools>=40.6.0' wheel 'cffi>=1.0' cwd: None Complete output (35 lines): Collecting setuptools>=40.6.0 Using cached setuptools-45.1.0.zip (859 kB) Collecting wheel Using cached wheel-0.33.6.tar.gz (48 kB) Collecting cffi>=1.0 Using cached cffi-1.13.2.tar.gz (460 kB) ERROR: Command errored out with exit status 1: command: 'c:\users\rahul\cookie\env\env\my_env\scripts\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\rahul\\AppData\\Local\\Temp\\pip-install-bikylb6j\\cffi\\setup.py'"'"'; __file__='"'"'C:\\Users\\rahul\\AppData\\Local\\Temp\\pip-install-bikylb6j\\cffi\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\rahul\AppData\Local\Temp\pip-install-bikylb6j\cffi\pip-egg-info' cwd: C:\Users\rahul\AppData\Local\Temp\pip-install-bikylb6j\cffi\ Complete output (23 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\rahul\AppData\Local\Temp\pip-install-bikylb6j\cffi\setup.py", line 127, in <module> if sys.platform == 'win32' and uses_msvc(): File "C:\Users\rahul\AppData\Local\Temp\pip-install-bikylb6j\cffi\setup.py", line 105, in uses_msvc return config.try_compile('#ifndef _MSC_VER\n#error "not MSVC"\n#endif') File "c:\users\rahul\appdata\local\programs\python\python37-32\Lib\distutils\command\config.py", line 227, in try_compile self._compile(body, headers, include_dirs, lang) File "c:\users\rahul\appdata\local\programs\python\python37-32\Lib\distutils\command\config.py", line 133, in _compile self.compiler.compile([src], include_dirs=include_dirs) File "c:\users\rahul\appdata\local\programs\python\python37-32\Lib\distutils\_msvccompiler.py", line 346, in compile self.initialize() File "c:\users\rahul\appdata\local\programs\python\python37-32\Lib\distutils\_msvccompiler.py", line 239, in initialize vc_env = _get_vc_env(plat_spec) File "c:\users\rahul\cookie\env\env\my_env\lib\site-packages\setuptools\msvc.py", line 171, in msvc14_get_vc_env return EnvironmentInfo(plat_spec, vc_min_ver=14.0).return_env() File "c:\users\rahul\cookie\env\env\my_env\lib\site-packages\setuptools\msvc.py", line 1075, in __init__ self.si = SystemInfo(self.ri, vc_ver) File "c:\users\rahul\cookie\env\env\my_env\lib\site-packages\setuptools\msvc.py", line … -
Django: pass request.user to form using FormView class
I've a model List that is related on a ForeignKey to User model. I'm using FormView class to show this form on template, besides sending a variable context listas that is a queryset of all the List objects related to logged in user. However, passing the user to the form before saving it, gives me this error: TypeError at /listas/ __init__() got an unexpected keyword argument 'user' I'm open to user CreateView as according to my research is more approiated to my need to creating a new record and show a queryset on template. models.py: class List(models.Model): LISTA_STATUS = ( ('recibida_pagada', 'Recibida y pagada'), ('recibida_no_pagada', 'Recibida pero no pagada'), ('en_revision', 'En revision'), ('en_camino', 'En camino'), ('entregada', 'Entregada'), ('cancelada', 'Cancelada') ) name = models.CharField(max_length=100, default='Lista anónima') user = models.ForeignKey(User, on_delete=models.CASCADE) school = models.OneToOneField(School, on_delete=models.CASCADE, null=True, blank=True) status = models.CharField(max_length=20, choices=LISTA_STATUS, default='recibida_no_pagada') created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['created_at'] def __str__(self): return str(self.id) views.py: class ListFormView(LoginRequiredMixin, FormView): form_class = ListForm template_name = "scolarte/listas.html" success_url = reverse_lazy('lists:my_lists') def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) context['listas'] = List.objects.filter(user=request.user) return self.render_to_response(context) def form_valid(self, form): form = ListForm(data=self.request.POST, user=self.request.user) form.save() return super(ListFormView, self).form_valid(form) html: {% block content %} <div class="container"> <div … -
TemplateDoesNotExist at /users/profile/
I am trying to make a profile page, which simply is a page with user details, such as firstname, lastname, email, etc. But I think there is something wrong with my view or my url.py or my setting, which gives me an error of TemplateDoesNotExist at /users/profile/ (users/profile.html). Other pages are working fine though. Here is my traceback: File "/Documents/morse_log/m_env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Documents/morse_log/m_env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) *File "/Documents/morse_log/m_env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs)* File "/Documents/morse_log/users/views.py", line 32, in profile return render(request, 'users/profile.html', args) File "/Documents/morse_log/m_env/lib/python3.7/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Documents/morse_log/m_env/lib/python3.7/site packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/Documents/morse_log/m_env/lib/python3.7/site-packages/django/template/loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) Exception Type: TemplateDoesNotExist at /users/profile/ Exception Value: users/profile.html settings.py: INSTALLED_APPS = [ # My apps 'morse_logs', 'users', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] /users/urls.py: from django.urls import path, include from django.contrib.auth.models import User from . import views app_name = 'users' urlpatterns = [ # Include default auth … -
Reload the page without refreshing with django and ajax
i'm developing a site that uses Django to check cryptocurrency prices. I want to load a value stored in django sqlite3 database file without refreshing (F5) using ajax. What should I do? (However, if the user manually refreshes the page, the value will change. This is because the value is loaded from the database.) Cryptocurrency prices and other information are automatically collected by the crawler and stored in real time in db.sqlite3 in your Django project. index.html (this HTML template is static, its value does not change in real time.) {% extends 'exchange/layout.html' %} {% load humanize %} {% block title %}XCoin{% endblock %} {% block body %} <table class="table table-condensed"> <thead> <tr> <th>#</th> <th>Name</th> <th>Price</th> <th>Market Cap</th> <th>Volume (24h)</th> <th>Circulating Supply</th> </tr> </thead> <tbody> {% for coin in coins %} <tr> <td>{{coin.ranking}}</td> <td>[ {{coin.abbreviation}} ] {{coin.name}}</td> <td>{{coin.price|intcomma}}$</td> <td>{{coin.marketcap|intcomma}}$</td> <td>{{coin.volume|intcomma}}$</td> <td>{{coin.circulatingsupply|intcomma}} {{coin.abbreviation}}</td> </tr> {% endfor %} </tbody> </table> {% endblock %} urls.py from django.contrib import admin from django.urls import path from . import views app_name = 'exchange' urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='home'), ] models.py from django.db import models class Coin(models.Model): ranking = models.IntegerField() # coin ranking abbreviation = models.CharField(max_length=10) # coin symbol name = models.CharField(max_length=20) # coin … -
Django admin change many to many label text
I have the field as part of a Room class roomextra = models.ManyToManyField( to='hotel.RoomExtra', related_name='room_extra', verbose_name='room extra', ) whereby Django has created the many to many relationship for me. This relationship is displayed as a TabularInline: admin.py class RoomExtraInLine(admin.TabularInline): model = Room.roomextra.through extra = 1 verbose_name = _('Customise Room Extra') verbose_name_plural = _('Customise Room Extra(s)') form = AddRoomAddRoomExtrasForm In the Django admin, if I add a room extra I get the text in the image below: Room_roomextra object (5) above the option I have selected. How can I change the Room_roomextra string? -
How to sort by the sum of a related field in Django using class based views?
If I have a model of an Agent that looks like this: class Agent(models.Model): name = models.CharField(max_length=100) and a related model that looks like this: class Deal(models.Model): agent = models.ForeignKey(Agent, on_delete=models.CASCADE) price = models.IntegerField() and a view that looked like this: from django.views.generic import ListView class AgentListView(ListView): model = Agent I know that I can adjust the sort order of the agents in the queryset and I even know how to sort the agents by the number of deals they have like so: queryset = Agent.objects.all().annotate(uc_count=Count('deal')).order_by('-uc_count') However, I cannot figure out how to sort the deals by the sum of the price of the deals for each agent. I'm relatively new to Django so please blast me if I made a dumb mistake. -
My Django website uses url redirect defined in separate project folder
I am testing the developing of a new project and I am having a strange problem. In the previous project I was working on, the following rule was defined: from django.views.generic import RedirectView urlpatterns += [ path('', RedirectView.as_view(url='catalog/', permanent=True)), ] Now in the new project I try to define the following rule urlpatterns += [ path('', include('funpage.urls')), ] This has no effect and the catalog rule is applied. I do not understand why this is. They are in separate project folders. Why would that rule be active still? The relevant Apache configuration is the following WSGIScriptAlias / /srv/django_projects/myapp/myapp/wsgi.py WSGIPythonPath /srv/django_projects/myapp Alias /static/ /srv/django_projects/myapp/static/ <Directory /srv/django_projects/myapp> Require all granted #<Files wsgi.py> #Require all granted #</Files> </Directory> -
Can not run tests
Structure of project proj/ apps/ app1/ ... tests.py ... proj/ tests.py class UsersTestCase(APITestCase): def setUp(self): self.user = User.objects.get(id=3) self.client = APIClient() def test_users_list(self): ... I run python manage.py test --settings=proj.settings.local and see Ran 0 tests in 0.000s Why? -
TypeError: 'int' object is not iterable serializer Django Serializer for one-to-many
I am facing a strange situation, Following is my code for models. class Sector(models.Model): sector_name = models.CharField(max_length=255, null=False) sector_desc = models.CharField(max_length=1024, null=False) def __set__(self): return "{} - {}".format(self.sector_name, self.sector_desc) class TrailCompany(models.Model): sector = models.ForeignKey(Sector, on_delete=models.CASCADE, related_name="sector_id") comp_name = models.CharField(max_length=255, null=False) comp_desc = models.CharField(max_length=1024, null=False) def __set__(self): return "{} - {}".format(self.sector, self.comp_name, self.comp_desc) class Trail(models.Model): company = models.ForeignKey(TrailCompany, on_delete=models.CASCADE, related_name="company_id") trail_id = models.CharField(max_length=255, null=False) tri = models.CharField(max_length=255, null=False) exp_pdufa = models.CharField(max_length=255, null=False) def __set__(self): return "{} - {}".format(self.company, self.exp_pdufa, self.trail_id, self.tri, self.exp_pdufa) Following is my code for the serializer, class SectorSerializer(serializers.ModelSerializer): class Meta: model = Sector fields = '__all__' class TrailCompanySerializer(serializers.ModelSerializer): sectors = SectorSerializer(source="sector_id", many=True) class Meta: model = TrailCompany fields = '__all__' class TrailSerializer(serializers.ModelSerializer): companies = TrailCompanySerializer(source="company_id", many=True) class Meta: model = Trail fields = '__all__' When I try to serilize object I am getting the stated error, trail_query = Trail.objects.all() trails = TrailSerializer(trail_query, many=True) return Response({"success": True, 'trails': trails.data}) Please help me to figure out and resolve the problem. Thanks. -
How to configure AWS API Gateway to get a pdf response?
PDF is received from the server with response headers Content-type : application/pdf and Content-dispositon : attachment whereas from API Gateway the PDF response gets corrupted with a change in file size as well. I was able to configure Method Response to application/pdf. Though I still have no solution for content disposition header which does not appear in the response header of API Gateway. -
Whitenoise collectstatic failing on none existent file
I seem to be getting an issue with serving running collectstatic when whitenoise is enabled. I keep getting an error about a missing file - not quite sure why. Here is the fill traceback Post-processing 'third/vendors/owl-carousel/assets/owl.carousel.css' failed! Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/thegqvow/virtualenv/gradientboostmvp/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/thegqvow/virtualenv/gradientboostmvp/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/thegqvow/virtualenv/gradientboostmvp/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/thegqvow/virtualenv/gradientboostmvp/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/thegqvow/virtualenv/gradientboostmvp/3.7/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 189, in handle collected = self.collect() File "/home/thegqvow/virtualenv/gradientboostmvp/3.7/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 135, in collect raise processed File "/home/thegqvow/virtualenv/gradientboostmvp/3.7/lib/python3.7/site-packages/django/contrib/staticfiles/storage.py", line 296, in _post_process content = pattern.sub(converter, content) File "/home/thegqvow/virtualenv/gradientboostmvp/3.7/lib/python3.7/site-packages/django/contrib/staticfiles/storage.py", line 197, in converter force=True, hashed_files=hashed_files, File "/home/thegqvow/virtualenv/gradientboostmvp/3.7/lib/python3.7/site-packages/django/contrib/staticfiles/storage.py", line 134, in _url hashed_name = hashed_name_func(*args) File "/home/thegqvow/virtualenv/gradientboostmvp/3.7/lib/python3.7/site-packages/django/contrib/staticfiles/storage.py", line 345, in _stored_name cache_name = self.clean_name(self.hashed_name(name)) File "/home/thegqvow/virtualenv/gradientboostmvp/3.7/lib/python3.7/site-packages/django/contrib/staticfiles/storage.py", line 94, in hashed_name raise ValueError("The file '%s' could not be found with %r." % (filename, self)) ValueError: The file 'third/vendors/owl-carousel/assets/owl.video.play.png' could not be found with <django.contrib.staticfiles.storage.ManifestStaticFilesStorage object at 0x7f5018ab78d0>. -
Foreign Key dependencies While deleting table
In my Postgresql, I have a main table TABLE_MAIN containing 10 columns in which 7 of the columns are foreign keys to the primary keys of the other 7 tables. Now, in one of the tables (not TABLE_MAIN) let's call it child_table, whenever I click Refresh Button in the UI, I am emptying all the data in child_table using the following Django ORM query and then insert relevant data. child_table.objects.all().delete() I have lots of important data in TABLE_MAIN of around 1000 rows, and to my shock, whenever I click the Refresh button in the UI(which deleted all the data in child_table) I found that TABLE_MAIN data is completely gone. What is happening here? Is it due to the foreign key dependencies?? and the other child_tables data is completely safe, but TABLE_MAIN data is lost. Deleting one primary key in child_table for which it's a foreign key from TABLE_MAIN field will affect to lose all the data in TABLE_MAIN?