Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to find Min(Sum(annotated column)) in Django
I have four tables A, B, C and D. each table is associated in a way A -> B -> C -> D by id column. eg. A.id = B.a_id, B.id = C.b_id and C.id = D.c_id I am trying to achieve something like this SELECT x.id, min(x.total) as mintotal FROM (SELECT “A”.”id", SUM((“D”.”amount” * “D”.”quantity")) AS "total", “C”.”id" AS "qid" FROM “A” LEFT OUTER JOIN “B” ON (“A”.”id" = “B”.”a_id") LEFT OUTER JOIN “C” ON (“B”.”id" = “C”.”c_id") LEFT OUTER JOIN “D” ON (“C”.”id" = “D”.”c_id") GROUP BY “A”.”id", “C”.”id") as x group by x.id ORDER BY mintotal ASC My equivalent django code query1 = A.objects.all().annotate(qid = models.F(‘b__c__id'),total=Sum(models.ExpressionWrapper( models.F(‘b__c__d__amount') *models.F('b__c__d__quantity'), output_field=models.DecimalField()))).order_by('total') it gives me the inner query output, however when I try to select id and Min(total) again it throws error - FieldError: Cannot compute Min('total'): 'total' is an aggregate I am new to Django and I am not sure how I can use subquery or exists to get this result. Any help will be appreciated -
My HTML form is not showing block content in Django
I have a base template where I have a Navbar. In my contact_form HTML file I am extending base template. And in block content, I am giving an HTML form, that supposed to be shown in the browser. But In the browser, it shows only the navbar. The form is not showing. Here is my base template: <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <title>Home</title> </head> <body> <!--NAVEBAR --> <nav class="navbar navbar-expand-lg navbar-light bg-dark sticky-top" > <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo03" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand text-white" href="#">Imtinan</a> <div class="collapse navbar-collapse" id="navbarTogglerDemo03"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li class="nav-item active"> <a class="nav-link text-white" href="home.html">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link text-white" href="{% url 'blog' %}">Blog</a> </li> <li class="nav-item"> <a class="nav-link text-white" href="{% url 'contact' %}">Contact</a> </li> <li class="nav-item"> <a class="nav-link text-white" href="about.html">About</a> </li> <li class="nav-item"> <a class="nav-link text-white" href="project.html">Project</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> <!--NAVEBAR END --> {% block content %} {% endblock %} <!-- Optional JavaScript; choose one of … -
Not appear bootstrap validation message in django
In Django I add a bootstrap template with form fields I replace paths by static validation of fields but if I submit form with blan fields there is not any validation messages. In the terminal I see that it is loading all files. Outside of Django template it works. I used template https://getbootstrap.com/docs/4.5/examples/checkout/?fbclid=IwAR3u58tn3MZS8b2a8sRKZYt12Jk_qnC1PW3FSMl1OkHHZC2HyV8dAV2s9zQ [my in DJanko looks:][1] [1]: https://pastebin.com/D5ZDXW2D -
AWS CONFIG FILES FOR ELASICBEANSTALK DON'T WORK
I have an old django project setup with elastic beanstalk using a .ebextensions folder. This old project contains many files, some of which update Apache by putting configuration files into the following location: /etc/httpd/conf.d/ For example, it would add an enable_mod_deflate.conf by having the following command in one of the .ebextensions configuration files: container_commands: 01_setup_apache: # Setup gzip compression on apache server by copying enable_deflate.conf into appropriate directory. command: "cp .ebextensions/enable_mod_deflate.conf /etc/httpd/conf.d/enable_mod_deflate.conf" Similarly there is a file for cache configuration that looks something like this: files: "/etc/httpd/conf.d/enable_cache.conf": mode: "000444" owner: root group: root content: | <IfModule mod_expires.c> ExpiresActive on ExpiresDefault "access plus 1 day" ExpiresByType image/jpg "access plus 1 month" ExpiresByType image/jpeg "access plus 1 month" ExpiresByType image/gif "access plus 1 month" ExpiresByType image/png "access plus 1 month" ExpiresByType text/css "access plus 1 month" ExpiresByType text/javascript "access plus 1 month” ExpiresByType application/javascript "access plus 1 month” ExpiresByType image/ico "access plus 1 month" ExpiresByType text/html "access plus 600 seconds" </IfModule> The problem that I have is that I have just tried to create another Django project. When I ssh into the old ec2 instance (I am using a single instance elastic beanstalk environment), I can see all of the files in … -
'HttpResponse' object has no attribute '_committed'
I am working with a Django project, where I am trying to render a pdf and save it in my database. my models.py: class Final_report(models.Model): industry = models.ForeignKey(Industry, null=True, blank=True, on_delete=models.CASCADE) inspector = models.ForeignKey(Inspector, null=True, blank=True, on_delete=models.CASCADE) created_date = models.DateTimeField(default=datetime.now, blank=True) pdf = models.FileField(upload_to='documents') my views.py: def submit_report(request, pk): template = get_template('app/pdf_rprt.html') Industry_obj = Industry.objects.get(id=pk) Industry_Report_obj = Industry_obj.industry_report_set.all() report_tableA_obj = report_tableA.objects.filter(industry_report__industry=Industry_obj) context = { 'industry' : Industry_obj, 'Industry_Report' : Industry_Report_obj, 'report_tableA' : report_tableA_obj, } html = template.render(context) pdf = render_to_pdf('app/pdf_rprt.html', context) if pdf: this_industry = Industry_obj this_inspector = request.user.inspector_releted_user this_pdf = pdf this_created_date = timezone.now() Final_report_obj = Final_report.objects.create(industry=this_industry, inspector=this_inspector, pdf=this_pdf, created_date=this_created_date) Final_report_obj.save() return redirect('app:index') here the render_to_pdf comes from a custom build function in utils.py: def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None Now it says the following error: Internal Server Error: /submit_report/1/ Traceback (most recent call last): File "G:\Python\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "G:\Python\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "G:\Python\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Project\django\hackathon practice\ProjectSurokkhaBeta_1.7\app\views.py", line 526, in submit_report Final_report_obj = Final_report.objects.create(industry=this_industry, inspector=this_inspector, pdf=this_pdf, created_date=this_created_date) File "G:\Python\lib\site-packages\django\db\models\manager.py", line … -
django not receiving signals from celery
I have a model called class Vcf(models.Model): ... And I have a post_save signal receiver for this model @receiver(post_save, sender=Vcf) def vcf_post_save(sender, instance, created, **kwargs): group = Group.objects.get(name='name') if created: assign_perm('view_vcf', instance.user, instance) assign_perm('view_vcf', group, instance) I have a view function where users can fill out a form and this will start a celery task. Which calls a function get_results which in turn calls another function create_vcf_model @shared_task def do_stuff(user_id, run_id, config): ...other stuff... get_results(run_id) get results(run_id): ...other stuff... create_vcf_model(run_id, vcf_path) create_vcf_model(run_id, vcf_path): vcf, created = Vcf.objects.get_or_create() Problem is here. I am guessing because create function is called from a celery task django is not receiving the signal? -
AttributeError at /accounts/login/ 'str' object has no attribute 'field'
i'm having this error after trying to use the auth system with using crispy form login html page {% extends 'base.html'%} {% block content %} {% load crispy_forms_tags %} <form method="POST"> {% csrf_token %} {{ form.as_p|crispy }} <button type="submit">Log In</button> </form> </div> {% endblock %} -
Django serve various file types using IIS / Virtual Directory
I am trying to serve various file types using Django on a IIS windows server. And for the life of me, I can't seem to figure it out. I am working with a legacy DB that stores file paths in a column. The files are held on a network share so have created a Virtual Folder (tired pass-though and connect as) I get the URLS created in HTML using the file path from the DB / model <td><a href ="/{{doc.location}}" download>{{doc.location}}</a></td> which results in http://panel/docs/07/xxxxxx.doc File downloads but get a Fail - No file in Chrome. The files are mix of doc / pdf/ txt and a few other file types. Any help would be greatly appreciated, racking my brain with this. -
Django: How to link a client-side component with a server-side information
I know the title is maybe confusing, but let me clarify my problem. I have an Animal model with simply a name field in it. In my HTML template, I list each instance of Animal in an a element (display order may vary). view.py: def index(request): animals = Animal.objects.all() return render(request, 'index.html', {'animals': animals}) index.html: {% for animal in animals %} <a>animal.name</a> {% endfor %} Output is something like this: Cow Duck Horse Cat Bee My question is, when the user clicks on an animal, I have to perform certain actions in the database. But how can I know which animal did he click ? I don't want to get the client-side text with javascript, because this is not secure and the user can change it by inspecting the element. I simplified my problem with animals, but in reality it is more complicated than this and I really need to find a secure way to get the correct clicked animal, even if the user changed the text or the HTML class or ID or something like this. -
Handling long file uploads with Django on GKE
I need to be able to upload large files on a Django app hosted on GKE which can take a long time if the connection is slow. I'm relying on gunicorn to serve the application. The problem I have is: once I start the file upload, the gunicorn worker is stuck processing the upload request and cannot process anything else. As a result, kubernetes cannot access the liveness probe and restart the container, which kills the upload. It also means my site is very unresponsive. I could add more gunicorn worker but it's not a proper solution since users can upload many files in parallel. It would just increase the threshold of what I can manage. Scaling up would solve the responsiveness but not the fact the user needs time to upload the file. Since this issue is usually (by usually I mean when not running on kubernetes) solved by putting a nginx sever in front of gunicorn, I was wandering how I could to this with kubernetes. I think I have two solutions: Add an nginx sidecar in the pod. This looks simple enough and would avoids installing something cluster wide. I can also let the GKE ingress handle … -
Django backend in Rest-framework resource for eCommerce
I want to create an eCommerce store's entire backend in django (using Restful framework APIs), I am looking for resource available online especially on github. Ofcourse I have done extensive research but I am unable to find anything that is recently updated and yet simple enough for me to understand, as I am not expert in django yet. All I want is a resource from where I can see overall flow and model it by using their models, views, serializers and permissions as a reference -
How can I save local video file to django FileField?
I create a local video file (.mp4) by adding a logo to an existing video with the following code: logo_path = os.path.join(MEDIA_ROOT, 'logo.png') logo = (mp.ImageClip(logo_path) .set_duration(video.duration) .resize(height=50) # if you need to resize... .margin(right=8, top=8, opacity=0) # (optional) logo-border padding .set_pos(("right", "top"))) video_path = os.path.join(MEDIA_ROOT, 'test7.mp4') audio_path = os.path.join(MEDIA_ROOT, 'temp-audio.m4a') final = mp.CompositeVideoClip([video, logo]) final.write_videofile(video_path, codec='libx264', audio_codec='aac', temp_audiofile=audio_path, remove_temp=True ) I want to save the new video to a FileField of my model. Here is the code: f = open(video_path) flick.videoWithWatermark.save("videoWithWaterMark.mp4", File(f)) I keep getting the error: 'ascii' codec can't decode byte 0xd1 in position 42: ordinal not in range(128) How can I save the video to a FileField? -
Wagtail i18n: only show links to pages that are translated
I'm building an i18n website with Wagtail 2.11.3 and followed the documentation at https://docs.wagtail.io/en/stable/advanced_topics/i18n.html?highlight=i18n, and four languages. I also use django.middleware.locale.LocaleMiddleware to determine the user's preferred language, which "kind of" works (read below). So I have four languages: WAGTAIL_CONTENT_LANGUAGES = LANGUAGES = [ ('de', "Deutsch"), ('fr', "Français"), ('it', "Italiano"), ('en', "English"), ] Only parts of the website should be multi-lingual, some pages are only available in one language. I ended up having four page trees, one for each language, and I'm able to create translations. However, as pointed out, I have some pages that aren't translated at all, but still have a localized version (auto-created when I create a page). So here https://docs.wagtail.io/en/stable/advanced_topics/i18n.html?highlight=i18n#basic-example is an example how the language links can be implemented in the template, but I only want to show the links to pages already translated. Using django_debug_toolbar I couldn't find a template variable to check if a page is translated. How can I accomplish that? Also related: Using django.middleware.locale.LocaleMiddleware the preferred language is detected, and I'm on /about_us. However, if I not explicitly set the language code preceding the url (like /de/about_us), the following pages will change back to my browser's language as I navigate at the … -
How can you output the values in the same page?
I'm trying to build an email scrapper on Django and that when you enter a URL, the result should be outputted in the same page. For now, the result is outputted in another page but I want it to be in the same one. I don't know how should I do this. I know I should be using an AJAX request but don't know how to make the form take the action of the AJAX request. Any help I would really appreciate it! form: <form class="card card-sm" action="{% url 'emailsearcher' %}" id='InputSearch' method="GET"> <div class="card-body row no-gutters align-items-center"> <div class="col-auto"> <i class="fas fa-search h4 text-body"></i> </div> <!--end of col--> <div class="col"> <input type="text" class="form-control form-control-lg form-control-borderless" placeholder="Introduce URL" name="Email" id="InputSearch" value="{{ Email.get }}" aria-describedby="searchHelp"> </div> <!--end of col--> <div class="col-auto"> <button class="btn btn-lg btn-success" type="search" onclick="total()">Find Email Address</button> </div> <!--end of col--> </div> </form> -
How to get multiple related models with as few queries possible
I am having some difficulty linking/obtaining data from 3 models all related to one another. I'm thinking i've either designed them incorrectly or I don't fully understand how to work with parental and many-to-many fields. There are 3 models (full models shown at end of question): ClubManager Where club names are entered ClubTimetables The timetable, relevant to the ClubManager DaysOfTheWeek Mon-Sun, used by ClubTimetables For which I am trying to retrieve information from all of them: the name of the club, its timetable(s) and for each timetable the days of the week it's linked to. However, I can't seem to do it in a way that doesn't constantly hit the database. First thing I tried was to get ClubManager and select_related it's timetable but couldn't figure out how to preselect the DaysOfTheWeek it was connected with. The approach I am trying now is to instead get the ClubTimetable and use select_related and prefetch_related on both the models it's linked with, like so timetable = ClubTimetables.objects.select_related('attached_to').prefetch_related('weekday') for t in timetable: print(t.attached_to.name) This results in such a query connection.queries [{'sql': 'SELECT "club_clubtimetables"."id", "club_clubtimetables"."sort_order", "club_clubtimetables"."address_line_1", "club_clubtimetables"."address_line_2", "club_clubtimetables"."address_city", "club_clubtimetables"."address_county", "club_clubtimetables"."address_country", "club_clubtimetables"."map_coord_lat", "club_clubtimetables"."map_coord_lon", "club_clubtimetables"."attached_to_id", "club_clubtimetables"."start_time", "club_clubtimetables"."end_time", "club_clubmanager"."id", "club_clubmanager"."name" FROM "club_clubtimetables" INNER JOIN "club_clubmanager" ON ("club_clubtimetables"."attached_to_id" … -
DRF: Route with and without arguments
I have a pretty simple urls.py: router = routers.DefaultRouter() router.register(r'products', views.ProductViewSet, basename = "product") urlpatterns = [ url('^api/', include(router.urls)), ...] where Product looks like this: class Product(models.Model): user = models.ManyToManyField(User, related_name="User", blank = True) name = models.CharField('name', max_length=120) What I want is a view that returns products from a user, if a user is handed to it, and returns all products when no user is submitted. I read multiple posts 1, 2, 3 but I could not solve it. Getting all products works: class ProductViewSet(LoginRequiredMixin, viewsets.ViewSet): login_url = "/login/" def list(self, request): data = [{"products": Product.objects.all(),}] results = ProductSerializer(data, many = True).data return Response(results) Serializer.py: class ProductSerializer(serializers.Serializer): products = serializers.CharField(max_length = 120) Can I add another method to my ProductViewSet, and how do I have to alter the urls.py so that I can call (for User with id=1): http://127.0.0.1:8002/api/products/1 -
Django rest-auth, I dont understand Token Authentication and permissions. Cant get credentials
Simple twitter like app, trying to understand permissions and authentication. So i have 3 views for now, all posts views, specific person's posts, and a create post view. Looks like this: @api_view(['GET']) @permission_classes((IsAuthenticated,)) def posts(request): posts = Post.objects.order_by("-created") serializer = PostSerializer(posts, many=True) return Response(serializer.data) @api_view(['GET']) @permission_classes((IsAuthenticated,)) def profile(request, name): posts = Post.objects.filter(user__username=name) serializer = PostSerializer(posts, many=True) return Response(serializer.data) @api_view(['POST']) @permission_classes((IsAuthenticated,)) def post_create(request): data = request.data print(request.user) serializer = PostSerializer(data=data) if serializer.is_valid(): serializer.save(user=request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Relevant settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', 'network', # my app ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } I'm using rest-auth and allauth currently for logging in and registration, their URLs are working fine i think and I can register users and login and get my tokens. However, whenever i go to one of the URLs, it just says { "detail": "Authentication credentials were not provided." } Even though I LITERALLY just logged in using the rest-auth URL and/or admin. I think I have a slight idea on whats going on after hours of searching, I need to somehow pass in my token whenever I … -
Django change value in queryset from null to string
I'd like to change the value of specific properties in a queryset from null and "null" to "Field does not exist" and "Field exists but does not have value". The model contains a property for custom fields that is returned as null if the field doesn't exits, or "null" if the field exists but does not have a value. Thus the returned list has the following objects: [ "object_1": { "custom_field": null }, "object_2": { "custom_field": "null" } ] I'd like to change both of these values to "Field does not exist" and "Field exists but does not have value" in the result but I do not want to update these values, just change how they are returned. Is that possible? -
Multifield foreign key constraint with Django Models?
What I'm curious about is if the following is possible. Consider these two sets of tables: # report +----+-------------+------+ | id | report_name | year | +----+-------------+------+ | 1 | RPT | 2018 | | 2 | RPT | 2019 | | 3 | RPT | 2020 | +----+-------------+------+ # report_details +----+-----------+----------------+---------+---------+ | id | report_id | report_name_fk | year_fk | details | +----+-----------+----------------+---------+---------+ | 11 | 1 | RPT | 2018 | ABC | | 12 | 2 | RPT | 2019 | DEF | | 13 | 3 | RPT | 2020 | GHI | +----+-----------+----------------+---------+---------+ And: # report +----+-------------+------+ | id | report_name | year | +----+-------------+------+ | 1 | RPT | 2018 | | 2 | RPT | 2019 | | 3 | RPT | 2020 | +----+-------------+------+ # report_details +----+----------------+---------+---------+ | id | report_name_fk | year_fk | details | +----+----------------+---------+---------+ | 11 | RPT | 2018 | ABC | | 12 | RPT | 2019 | DEF | | 13 | RPT | 2020 | GHI | +----+-----------+----------------+---------+---------+ Lets say I want to change the report_name in the table report for year = 2020 to just TST. I want that to CASCADE to related tables … -
how to check if the logged in user is a member of M2M field in the template? django
i have build a project to for real estate , a real estate owned by one person (account) and have multiple admins M2M class RealEstate(models.Model): owner = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,default='') admins = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='managers') code = models.UUIDField(unique=True,default=uuid.uuid4,editable=False) in the template (navbar) if logged in user was owner or an user within admins(managers) list create new post will appear i tried this {% if request.user.realestate.owner or request.user in request.user.realestate.managers.all %} <a class="nav-link" href="{% url 'listings:new_post' %}"> <i class="fas fa-user-plus"></i>+create new post</a> </i> {% else %} # some more condition but the after the or not worked request.user in request.user.realestate.managers.all to check if the logged in user is in the admins list or not , but doesnt work !is there something i have to change in the template!? or is it a right way to set similar conditions ? thank you -
how to make two different logins for users and admins
Here I m using django allauth for user management and I want to make two different logins for users and admin. Also the problem is how to save the user rating and review in the database. -
TypeError: UserAdmin() takes 1 positional argument but 2 were given
I am making an abstract user in which i get this error please solve it . i want make a custom user model django. Error (venv) python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/mraries/Documents/shift_api/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/mraries/Documents/shift_api/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/mraries/Documents/shift_api/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mraries/Documents/shift_api/venv/lib/python3.7/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/home/mraries/Documents/shift_api/venv/lib/python3.7/site-packages/django/contrib/admin/apps.py", line 24, in ready self.module.autodiscover() File "/home/mraries/Documents/shift_api/venv/lib/python3.7/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/mraries/Documents/shift_api/venv/lib/python3.7/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/mraries/Documents/shift_api/shift/admin.py", line 24, in <module> admin.site.register(User,UserAdmin) File "/home/mraries/Documents/shift_api/venv/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 134, in register self._registry[model] = admin_class(model, self) TypeError: UserAdmin() takes 1 positional argument but 2 were given Admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.utils.translation import gettext as _ from .models import … -
OperationalError: foreign key mismatch in Django
I'm receiving this error when I try to apply this changes: class Category(models.Model): name = models.CharField(primary_key=True, max_length=64) class Auction(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=100, default="") image_url = models.CharField(max_length=100, default="https://elitescreens.com/images/product_album/no_image.png") category = models.ForeignKey(Category, on_delete=models.CASCADE, default="undefined", related_name="auction_category") Every auction object has a category associated, but I can't avoid the mismatch error. What have I done wrong? I know there are similar questions in stackoverflow but they weren't enough to help me out in this -
Consume an API in Django REST, server side, and serve it ,client side, in Angular
I have an Angular app that consume API client side. Since it's bad practice to do so (I don't want to expose my API credentials), I decided to split into backend/ frontend before myapp get to big. I succeed to implement my Angular into a Django REST framework app and everything is working fine. But now I need to change my API logic and have DRF consume the external API I had: Angular <---API---> ext data Now I have: Django/ Angular <---API---> ext data What I need: Angular <---API---> Django <---API---> ext data But I am very confused about how to accomplish it. I have experience with setting up API endpoints in DRF, but only for data from models within DRF. I know as well how to consume API in Django. But how can I chain two API calls? Do I have to create a model to store the queries and then the response? Do I need to write serializers even if the returned data is json all the way? How my frontend will now that the data from the external API is available? What I need is someone to explain me what is the pattern for this task. -
Direct assignment to the forward side of a many-to-many set is prohibited. Use activity.set() instead. React client/Django server|
I'm a beginner with a few months under my belt but am practically new to django. class Locations(ViewSet): def create(self, request): user = VacaUser.objects.get(user=request.auth.user) location = Location() # activity = Activity.objects.filter() location.user = user location.title = request.data["title"] location.time = request.data["time"] location.description = request.data["description"] location.photo = request.data["photo"] try: location.save() # location.set(activity) location.activity = Activity.objects.get(pk=request.data["activity"]) serializer = LocationSerializer(Location, context={'request': request}) return Response(serializer.data) except ValidationError as ex: return Response({"reason": ex.message}, status=status.HTTP_400_BAD_REQUEST) class Location(models.Model): time = models.DateField(models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True)) user = models.ForeignKey("VacaUser", on_delete=models.DO_NOTHING, related_name="vacauser") title = models.CharField(max_length=50) description = models.TextField(max_length=200) activity = models.ManyToManyField("Activity", related_name='activities', blank=True) photo = models.ImageField(upload_to=None, height_field=None, width_field=None, max_length=100) class Activities(ViewSet): def create(self, request): activity = Activity() activity.name = request.data["name"] try: activity.save() serializer = ActivitySerializer(activity, context={'request': request}) return Response(serializer.data) except ValidationError as ex: return Response({"reason": ex.message}, status=status.HTTP_400_BAD_REQUEST) class Activity(models.Model): name = models.CharField(max_length=50,) ` POSTMAN EXAMPLE : This is one of my fixtures. { "id": 1, "time": "2018-04-12", "user": { "id": 1, "bio": "Me", "user": 1 }, "title": "Hawaii", "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean mattis lectus sit amet velit viverra viverra. Cras efficitur volutpat sem.", "photo": "http://localhost:8000/https%3A/res.cloudinary.com/db1peeart/image/upload/v1601909566/Michael/hawaii2_jwrmwb.jpg", "activity": [ { "id": 1, "name": "Swimming" }, { "id": 2, "name": "Beach" }, { "id": 3, "name": "Hike" }, …