Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
real-time update of the views in the template (Django)
for example: views.py a=0 while True: a=a+1 how can I render (a) in real time in a template? -
ORA-00955: name is already used by an existing object during migrating to oracle db
I added a new model in models.py. And i have successfully done with makemigrations. During makemigrations, i haven't face any issues. But when i try to migrate this model to the DB server, I am getting error as "django.db.utils.DatabaseError: ORA-00955: name is already used by an existing object". I am sure that there is no other model name with this new model name. Could you please let me know what is the issue and the resolution. Thanks in advance models.py class ProdServersMountPoints(models.Model): mountpoint = models.CharField(max_length=100) check_fabs_servers = models.BooleanField() check_oc_servers = models.BooleanField() class Meta: db_table = 'PROD_SERVERS_MOUNTPOINTS' def __str__(self): return str(self.mountpoint) Error: (venv_2.7.12) -bash-4.1$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, fabi, sessions Running migrations: Applying fabi.0002_auto_20171205_0057...Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/scratch/kvkumari/tools_setup/Python/framework/venv_2.7.12/lib/python2.7/site-packages/django/core/management/init.py", line 367, in execute_from_command_line utility.execute() File "/scratch/kvkumari/tools_setup/Python/framework/venv_2.7.12/lib/python2.7/site-packages/django/core/management/init.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/scratch/kvkumari/tools_setup/Python/framework/venv_2.7.12/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/scratch/kvkumari/tools_setup/Python/framework/venv_2.7.12/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/scratch/kvkumari/tools_setup/Python/framework/venv_2.7.12/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/scratch/kvkumari/tools_setup/Python/framework/venv_2.7.12/lib/python2.7/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/scratch/kvkumari/tools_setup/Python/framework/venv_2.7.12/lib/python2.7/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/scratch/kvkumari/tools_setup/Python/framework/venv_2.7.12/lib/python2.7/site-packages/django/db/migrations/executor.py", line 244, in … -
Python/Django 2.0/Bootstrap3: Retrieving data from db based on form inputs using Django
I am new to Django and Python. So I need help on an issue. I have checked StackOverflow for finding similar problems, but could not solve the problem yet. I am creating a web app on django and there I want to retrieve the tours from the db based on the criteria accepted from a form. But it is not working. Here is what I did: models.py from django.db import models from django.forms import ModelForm from django.contrib.auth.models import User from django.db.models.signals import post_save from django.urls import reverse class Tour(models.Model): TourOperator = models.ForeignKey(TourOperator, on_delete=models.PROTECT) TourCode = models.CharField(max_length=10, unique=True, help_text='Ex. JT001 ') Title = models.CharField(max_length=200, help_text="Title of the tour here") Slug = models.SlugField(max_length=200) Type = models.CharField(max_length=200, choices = TOUR_TYPES, help_text="Select from the list") Duration = models.IntegerField(default=0) ShortDesc = models.CharField(max_length=200, help_text='Short description in 200') Description = models.TextField(help_text='Description of the tour...') Itinerary = models.CharField(max_length=500, help_text="Itinerary of the tour...") Inclusions = models.CharField(max_length=200, help_text="Inclusions of the tour; Seperate them with commas") Exclusions = models.CharField(max_length=200, help_text="Exclusions of the tour; Seperate them with commas") Difficulty = models.CharField(max_length=20, help_text="Enter a value between 1 to 10") GroupSize = models.CharField(max_length=2, help_text="Group size") Seasonality = models.CharField(max_length=100, help_text="Seasonality of the tour; Ex. July - September") Highlights = models.CharField(max_length=100, help_text="Highlights of the tour; Ex. … -
Celery Gevent Pool - ConcurrentObjectUseError
I have a celery worker that is using the gevent pool which does HTTP requests and adds another celery task with page source. I'm using Django, RabbitMQ as a broker, Redis as a celery result backend, Celery 4.1.0. The task has ignore_result=True but I'm getting this error pretty often ConcurrentObjectUseError: This socket is already used by another greenlet: <bound method Waiter.switch of <gevent.hub.Waiter...> I see it is related to the Redis connection. I can't figure out how to solve this. This is more or less the logic of the task. I also tried using a semaphore when calling process_task.apply_async but it didn't work. from gevent.lock import BoundedSemaphore sem = BoundedSemaphore(1) @app.task(ignore_result=True, queue='request_queue') def request_task(url, *args, **kwargs): # make the request req = requests.get(url) request = { 'status_code': req.status_code, 'content': req.text, 'headers': dict(req.headers), 'encoding': req.encoding } with sem: process_task.apply_async(kwargs={'url': url, 'request': request}) print(f'Done - {url}') This is the stack trace: cancel_wait_ex: [Errno 9] File descriptor was closed in another greenlet File "redis/connection.py", line 543, in send_packed_command self._sock.sendall(item) File "gevent/_socket3.py", line 424, in sendall data_sent += self.send(data_memory[data_sent:], flags, timeout=timeleft) File "gevent/_socket3.py", line 394, in send self._wait(self._write_event) File "gevent/_socket3.py", line 156, in _wait self.hub.wait(watcher) File "gevent/hub.py", line 651, in wait result = waiter.get() … -
Django for Python 2.7 (OS: Linux Fedora 27)
I have already succesfully installed Django 2.0.3 on Python 3.5.2 As beginner, I wold like to take solid steps and get through the Django tutorials on web, unfortunately I see many of them are relevant towards python 2. What is the best way to install Django on Python 2.7 and still keep Django on Python 3.5, I am concerned with errors popping once I try to install it v2.7 when it's already installed on v3.5 -
Messagebird in Django REST
I am creating a verification system in a django restframework API and preferred using the messagebird client for this purpose. Can anyone help guide me with creating the request in the django views? -
Send file through Django Rest
I need to download image object from vary object storage buckets, and send that to a user through Django Rest Framework. I have something like that: if request.method == 'GET': # Get object using swiftclient conn = swiftclient.client.Connection(**credentials) container, file = 'container_name', 'object_name' _, data = conn.get_object(container, file) # Send object to the browser return Response(data, content_type="image/png") data variable contains bytes type. While testing I'm receiving error: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte What can be solution for this problem? -
Django Viewset Pagination throws serialization error
I have something like this: Paginating Viewset: class FeedViewSet(ModelViewSet): queryset = Feed.objects.all() serializer_class = FeedSerializer def list(self, request, *args, **kwargs): paginator = pagination.LimitOffsetPagination() paginator.default_limit = 15 paginator.limit = paginator.get_limit(request) paginator.offset = paginator.get_offset(request) feeds = paginator.paginate_queryset(Feed.objects.all(), request) return Response( data={ 'feeds': feeds, 'limit': paginator.limit, 'offset': paginator.offset, 'overall_count': paginator.count } ) Feeds Model: class Feed(Base): headline = models.CharField(max_length=255) link = models.CharField(max_length=255, unique=True) summary = models.TextField() published_date = models.DateTimeField() views = models.IntegerField(default=0) shares = models.IntegerField(default=0) source = models.ForeignKey(Source, on_delete=models.CASCADE, ) reader = models.ManyToManyField(User, through='Bookmark') Feed Serializer: class FeedSerializer(serializers.ModelSerializer): class Meta: fields = ( 'id', 'headline', 'link', 'summary', 'published_date', 'views', 'shares', 'source', 'created', 'modified', ) model = models.Feed I am new to Django. I might be absolutely wrong here. I have gone through official DRF here : http://www.django-rest-framework.org but couldn't figure out the correct way of implementing pagination. I get something like this : TypeError: Object of type 'Feed' is not JSON serializable What am I doing wrong? If this is not the right way to do it, how should it be done. What changes do I need to make? -
Django Unicode Error with ukraine letter 'і'
I have input field in my template, i need to submit students name, which contain ukrainian letters, it works fine with all character except 'І' i get this all the time - exception. Viki says that Unicode supports all ukrainian characters, eveb 'і', bu it crashes every time My view for this template class Mark_View(Data_Mark): template_name = 'main/mark/view.html' reverse_link='mark-view' def post(self, request, *args, **kwargs): if request.POST.__contains__('student_name'): student_name = request.POST['student_name'] print (student_name) if student_name is not '': if Student.objects.filter(name = student_name): sum_mark=self.model.objects.filter(id_student__name= student_name).aggregate(Avg('mark')) messages.warning(request, sum_mark['mark__avg']) return HttpResponseRedirect(reverse(self.reverse_link)) else: messages.warning(request, 'Такого студента не існує!') return HttpResponseRedirect(reverse(self.reverse_link)) else: messages.warning(request, 'Будь ласка, введіть Ім`я') return HttpResponseRedirect(reverse(self.reverse_link)) elif request.POST.__contains__('group_name'): group_name = request.POST['group_name'] if group_name is not '': if Group.objects.filter(name = group_name): group_sum = Mark.objects.filter(id_student__id_group__name=group_name).aggregate(Avg('mark')) messages.warning(request, group_sum['mark__avg']) return HttpResponseRedirect(reverse(self.reverse_link)) else: messages.warning(request, 'Такої групи не існує!') return HttpResponseRedirect(reverse(self.reverse_link)) else: messages.warning(request, 'Будь ласка, введіть назву группи') return HttpResponseRedirect(reverse(self.reverse_link)) elif request.POST.__contains__('course_name'): course_name = request.POST['course_name'] if course_name is not '': if Course.objects.filter(course = course_name): course_sum = Mark.objects.filter(id_student__id_group__id_course__course = course_name).aggregate(Avg('mark')) messages.warning(request, course_sum['mark__avg']) return HttpResponseRedirect(reverse(self.reverse_link)) else: messages.warning(request, 'Такого курсу не існує!') return HttpResponseRedirect(reverse(self.reverse_link)) else: messages.warning(request, 'Будь ласка, введіть назву курсу') return HttpResponseRedirect(reverse(self.reverse_link)) -
Delete image from template in django
I want to delete the image which appears on the widgets in my template.I have got this JS code which deletes a function. The Fiddle here shows that it is working there but when I put that in django it does not works for some reason.I have just made minor change in image path. Fiddle The JS Code in my template is as follows: for(var index=0;index<json.length;index++) { {% load static %} gridster.add_widget('<li class="new" ><button class="delete-widget-button" style="float: right;">-</button><div class="imagewrap"><img src="{% get_static_prefix %}images/'+json[index].html+'"><input type="button" class="removediv" value="X" /></div></li>',json[index].size_x,json[index].size_y,json[index].col,json[index].row); } $('.removediv').on('click', function () { $(this).closest('div.imagewrap').remove(); }); h -
Calling login_required inside decorator
I'm trying to write a custom decorator, which will do some checks to see if a user has permission to access a page, but prior to that, the user needs to be authenticated. I thought of using Django's login_required decorator, and then doing my custom logic, however I can't seem to find any way to call the login_required decorator inside my own. I do know that there are alternatives, like decorating my view like this: @login_required @my_custom_decorator def my_view(request): pass Or checking for user.is_authenticated() inside my decorator: def my_custom_decorator(view_func): @wraps(view_func) def wrapper(request, *args, **kwargs): if not request.user.is_authenticated(): redirect(...) However I'd like to user Django's logic from login_required. Is there any way to call a decorator inside a decorator, or any other way to implement my logic without using 2 separate decorators? -
Django, Celery: Cannot import name "shared_task"
I'm trying to setup celery on django project. I'm following this tutorial, but It has an issue. this is my app struct myproject/ myapp/ __init__.py tasks.py ... project/ __init__.py celery.py ... in settings.py BROKER_URL = 'amqp://' CELERY_RESULT_BACKEND = 'django-db' project/init.py from __future__ import absolute_import, unicode_literals # This willmake sure the app is always imported when # Django starts so that shared_task_will use this app. from .celery import app as celery_app __all__ = ('celery_app',) celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('myproject') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace=-'CELERY' means all celery-related configuration keys # should have a 'CELERY_' prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) finally, tasks.py from __future__ import absolute_import, unicode_literals from project.celery import shared_task @shared_task def say_hello(): print("Hello, celery!") I followed the tutorial almost same, but when I test with shell, this following error occurs. Python 3.6.3 (default, Oct 6 2017, 08:44:35) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" … -
I wanna use url's data in method
I wanna use url's data in method.Now urls.py is from django.urls import path from . import views urlpatterns = [ path('data/<int:id>', views.data, name='data'), ] I wrote in views.py @csrf_exempt def data(request,<int:id>): results = Users.objects.filter(user=id) print(results) return HttpResponse('<h1>OK</h1>') But I got an error, formal parameter name expected in <int:id> of (request,<int:id>). If I access http://127.0.0.1:8000/data/3, my ideal system print user's data has id=3. I cannot understand how I can do it. What is wrong in my code? -
Exception Value: Reverse for 'myapp.views.SaveProfile' not found. 'myapp.views.SaveProfile' is not a valid view function or pattern name
Exception Value: Reverse for 'myapp.views.SaveProfile' not found. 'myapp.views.SaveProfile' is not a valid view function or pattern name.Exception Value: Reverse for 'myapp.views.SaveProfile' not found. 'myapp.views.SaveProfile' is not a valid view function or pattern name.Exception Value: Reverse for 'myapp.views.SaveProfile' not found. 'myapp.views.SaveProfile' is not a valid view function or pattern name.Exception Value: Reverse for 'myapp.views.SaveProfile' not found. 'myapp.views.SaveProfile' is not a valid view function or pattern name.Exception Value: Reverse for 'myapp.views.SaveProfile' not found. 'myapp.views.SaveProfile' is not a valid view function or pattern name.Exception Value: Reverse for 'myapp.views.SaveProfile' not found. 'myapp.views.SaveProfile' is not a valid view function or pattern name.Exception Value: Reverse for 'myapp.views.SaveProfile' not found. 'myapp.views.SaveProfile' is not a valid view function or pattern name.Exception Value: Reverse for 'myapp.views.SaveProfile' not found. 'myapp.views.SaveProfile' is not a valid view function or pattern name.Exception Value: Reverse for 'myapp.views.SaveProfile' not found. 'myapp.views.SaveProfile' is not a valid view function or pattern name.Exception Value: Reverse for 'myapp.views.SaveProfile' not found. 'myapp.views.SaveProfile' is not a valid view function or pattern name.Exception Value: Reverse for 'myapp.views.SaveProfile' not found. 'myapp.views.SaveProfile' is not a valid view function or pattern name.Exception Value: Reverse for 'myapp.views.SaveProfile' not found. 'myapp.views.SaveProfile' is not a valid view function or pattern name.Exception Value: Reverse for 'myapp.views.SaveProfile' not found. 'myapp.views.SaveProfile' … -
Can't render attributes of an objecte linked with M2M field
Trying to render attributes of objects that are linked with another object via m2m field. #models class Arm(models.Model): cmrs = models.ManyToManyField(CMR, null=True) class CMR(models.Model): client = models.ForeignKey('Client', on_delete=models.CASCADE, null=True, default="", blank=True) The view if us.groups.filter(name__in = ['prime']): query_set = Plan.objects.order_by('-pk') query_ys = Arm.objects.filter(date=ys) query_rn = Arm.objects.filter(date=rn) query_tm = Arm.objects.filter(date=tm) client_rn = query_rn.prefetch_related('cmrs') args = {'query_rn': query_rn, 'cl_rn': client_rn, 'query_tm': query_tm, 'query_ys': query_ys, 'query_set': query_set } return render(request, 'personnel/schedule/test-schedule-full.html', args) And the template <tbody id="add"> {% for query in query_rn %} <tr class="row100 body {{ query.status }}" data-href="/personnel/arm/{{ query.id }}"> <td class="cell100 column1">{{ query.driver }}</td> <td class="cell100 column2">{% for idem in cl_rn.cmrs.all %} {{ idem.client }} {% endfor %}</td> <td class="cell100 column3">{{ query.des_from}}</td> <td class="cell100 columnarrow"><i class="fas fa-arrow-circle-right"></i></td> <td class="cell100 column4">{{ query.des_to }}</td> </tr> {% endfor %} </tbody> What I am trying to do is to show all the values of the client field of an CMR objects that are linked with Arm in <td class="cell100 column2"></td> but it shows nothing instead. -
Invalid block tag on line 18: 'endblock', expected 'endblock' or 'endblock extra_js'
I'm getting the following error: TemplateSyntaxError at /open_trades/ Invalid block tag on line 18: 'endblock', expected 'endblock' or 'endblock extra_js'. Did you forget to register or load this tag? The following piece of code gives this error: {% block extra_js %} <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $( function() { var availableTags = {{ cryptos }}; $( "#autocomplete" ).autocomplete({ source: availableTags }); } ); </script> {% endblock extra_js %} This template file extends base.html, which contains the following line in the head tag: {% block extra_js %}{% endblock extra_js %} I've checked the other questions on here regarding this type of error, but all of those involved some kind of typo. I've retyped the entire thing, including the {% extends "base.html" %}. I've also checked that my Python code definitely includes the list variable called cryptos in the context variables. What else can I try to fix this issue? Thanks in advance for your help. -
Django Admin: edit view shows no fields at all
I have defined a couple of models in a new Django 1.8 app. When I visit the Django Admin, the list view (the table where you see one row per each objects instance) works fine. My surprise is that when I click on any NSGateway item and enter the edit or create page, there are no fields; just the Save buttons. How can this be possible? All the NSGateway fields are shown as columns in the list view. But the edit view shows no fields! These are the models: from django.db import models class Enterprise(models.Model): enterprise_id = models.CharField(max_length=40, primary_key=True) description = models.CharField(max_length=500, null=True) name = models.CharField(max_length=500) creationDate = models.DateTimeField() lastUpdatedDate = models.DateTimeField() def __unicode__(self): return self.description class NSGateway(models.Model): nsgateway_id = models.CharField(max_length=40, primary_key=True) creationDate = models.DateTimeField() description = models.CharField(max_length=500, null=True) lastUpdatedDate = models.DateTimeField() personality = models.CharField(max_length=50) name = models.CharField(max_length=500) # Each NSG belongs to 1 and only 1 Enterprise. # Thus, when we delete de Enterprise, we delete its NSG enterprise = models.ForeignKey(Enterprise, on_delete=models.CASCADE) def __unicode__(self): return self.description This is how the corresponding admin.py: from django.contrib import admin from flexwan_import.models import Enterprise, NSGateway class EnterpriseAdmin(admin.ModelAdmin): list_display = ('enterprise_id', 'name', 'description', 'creationDate', 'lastUpdatedDate') search_fields = ['enterprise_id', 'description'] class NSGatewayAdmin(admin.ModelAdmin): list_display = ('nsgateway_id', … -
Secondary API call within Django Server Failed but working for external API
I have to call an API endpoint from another API endpoint within a Django Project. This is like: http://<IP>:<PORT>/primaryendpoint/ => this is mapped to one Class Based View (class getPrimaryendpoint) which will do another API call in the same server i.e. it will call http://<IP>:<PORT>/secondaryendpoint/ For this I'm using requests, creating session to call from primaryendpoint to secondaryendpoint. **When using 3rd party URL endpoint instead of http://<IP>:<PORT>/secondaryendpoint/, it's working fine( i.e. from primary endpoint we are able to call 3rd party URL EP which is outside of our Django Project ) but for this internal call (within Django project) it's throwing error : Expecting value: line 1 column 1 (char 0) Note: This was working fine in Windows but failing in Linux system. Using: Django 1.11, Django REST Framework, Python 3.6 -
Django - Tastypie provide summary of data returned
Hi I have a resource named employees which have 10 columns. How can I create a /employees/summary/ endpoint which only returns 5 columns but have all features of the main /employees/ endpoint such as filters and ordering. What i have tried to do is modify the result from get_list() but thats turning out to be hard. class EmployeeResouece(ModelResource): class Meta: queryset = Employees.objects.all() resource_name = 'employees' allowed_methods = ['get','post','put','patch'] def prepend_urls(self): return [ url(r"^(?P<resource_name>%s)/summary%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('summary'), name="summary"), ] def summary(self, request, **kwargs): result=EmployeeResouece().get_list(request) ### LIMIT COLUMNS TO 5### return result -
what if i don't use template of Django, how to setting static
I don't want to use Django's template, in order to make Front and back separate.my project structure: In index.html <script src="./bundle/common.js"></script> <script src="./bundle/bundle.js"></script> when running the server, get error Not Found: /bundle/common.js "GET /bundle/common.js HTTP/1.1" 404 2304 Not Found: /bundle/bundle.js Any one can help me? how to set the static to make it working? -
git pull doesn't update files on pythonanywhere
I am following Django Girls Tutorial, I am on html section - https://tutorial.djangogirls.org/en/html/ - where git is updated than files are transferred to pythonanywhere by using git pull. My git has been updated however, after git pull on pythonanywhere I do not see updated Files. I rerun my web app as well, no changes. After git pull I see files changes, insertions and deletion, but no files updated in FILES section. Thank You for help, Bogdan enter image description here -
Django admin download
how to add the ability to download files to the admin panel? Only administrators can download. in views i generate exel file, and how to download it to the administrator from django.http import HttpResponse import xlsxwriter from main.models import * def toxlsx(request): data = Contact.objects.all() workbook = xlsxwriter.Workbook('contacts.xlsx') worksheet = workbook.add_worksheet('contacts') worksheet.write(0, 0, '№') worksheet.write(0, 1, 'Имя') worksheet.write(0, 2, 'Телефон') worksheet.write(0, 3, 'Электронный адрес') worksheet.write(0, 4, 'Город') worksheet.write(0, 4, 'Дата') count = 1 for data_item in data: worksheet.set_column(count, 1, 60) worksheet.write(count, 0, count) worksheet.write(count, 1, data_item.name) worksheet.write(count, 2, data_item.phone) worksheet.write(count, 3, data_item.email) worksheet.write(count, 4, data_item.city) worksheet.write(count, 4, data_item.date.strftime("%d/%m/%y %H:%M:%S")) count += 1 workbook.close() return HttpResponse() -
DRF foreign primary key that auto increments with nested serializers for cascade insert
I want to insert a Conversation model that has a child class to Message model. I also want it to use a single Viewset method for the saving. The Message has a foreign key to the primary key of Conversation. I'm looking for something similar to the java + spring class implementation wherein the Parent references the Child class. The Parent and Child have an auto_increment annotation. Spring JPA save is called and the insert is cascaded. Is there something like this for Django Rest Framework? Or Django Framework? json: { "model": "conversation", "id": "auto_increment", "title": "chat", "message": { "model": "message", "participant_id": 1, "message": "hi" } } -
I wanna resist id in serial number
I wanna resist id in serial number like 1,2,3・・・.I wrote codes to resist User data like, from django.db import models import uuid # Create your models here. def get_next(): try: return Users.objects.latest('pk').increment_num + 1 except: return 1 class Users(models.Model): id = models.UUIDField(primary_key=True, default=get_next, editable=False) sex = models.CharField(max_length=100, null=True, default=None) age = models.CharField(max_length=100, null=True, default=None) But when I try to resist user's data,django.core.exceptions.ValidationError: ["'1' is not a valid UUID."] error happens. So I rewrote id = models.IntegerField(primary_key=True, default=get_next),but if i regist multiple user's data,only id=1's data is remain and I cannot understand but other data was deleted.What is wrong in my code?How should I fix this? -
Django query over two tables without foreign key
Hi i'm working on django. I have two models books and authors but there is no foreign key relationship between them. Models: class Books(models.Model): bookid = models.IntegerField(primary_key=True) bookname = models.CharField(max_length=50) authorid = models.CharField(max_length=50) class Meta: managed = False db_table = 'books' class Authors(models.Model): authorid = models.IntegerField(primary_key=True) authorname = models.CharField(max_length=50) class Meta: managed = False db_table = 'authors' Now, I'm want to fetch author and related books based on author name. class Author_Books(generics.GenericAPIView): def get(self, request, *args, **kwargs): try: authorname = 'Author Name' # filtering authors authors = Authors.objects.filter(authorname__icontains=authorname) # get author related books How to acheive it without using raw sql query. return HttpResponse(authors) except Exception as err: return HttpResponse(err)