Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I translate SQL query to to django ORM
I'm working on making some data consults in Django but I don't understand quite well its ORM system yet. I need to get the transactions' quantity for a particularly transaction's projections. To put it briefly, I want to translate this SQL query to Python/Django syntax: select cp.name, count(*) as total from core_transaction ct inner join core_projection cp on ct.projection_id = cp.id group by cp.name These are the models involved: class Transaction(models.Model): date = models.DateField() projection = models.ForeignKey('Projection', blank=False, null=False, related_name='transactions') class Projection(models.Model): name = models.CharField(max_length=150) description = models.CharField(max_length=300, blank=True, null=True) -
Django: Why celery can't find app folder in new django, celery version?
Firstly, I referred this but couldn't solve it. Problem is that: celery command can't recognize my app module. >> celery --workdir=super_crawler/ --app=config.celery:app worker Usage: celery [OPTIONS] COMMAND [ARGS]... Error: Invalid value for "-A" / "--app": Unable to load celery application. While trying to load the module config.celery:app the following error occurred: Traceback (most recent call last): File "/Users/chois/opt/miniconda3/envs/super_crawler_project/lib/python3.7/site-packages/celery/bin/celery.py", line 50, in convert return find_app(value) File "/Users/chois/opt/miniconda3/envs/super_crawler_project/lib/python3.7/site-packages/celery/app/utils.py", line 384, in find_app sym = symbol_by_name(app, imp=imp) File "/Users/chois/opt/miniconda3/envs/super_crawler_project/lib/python3.7/site-packages/kombu/utils/imports.py", line 56, in symbol_by_name module = imp(module_name, package=package, **kwargs) File "/Users/chois/opt/miniconda3/envs/super_crawler_project/lib/python3.7/site-packages/celery/utils/imports.py", line 107, in import_from_cwd return imp(module, package=package) File "/Users/chois/opt/miniconda3/envs/super_crawler_project/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 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'config' Library versions Django==3.1.2 celery==5.0.1 django-celery-beat==2.1.0 Folder Structure super_crawler_project ├── Dockerfile ├── Makefile ├── super_crawler │ ├── manage.py │ ├── config │ │ ├── __init__.py │ │ ├── apps.py │ │ ├── celery.py │ │ ├── settings.py │ │ ├── urls.py │ │ … -
function dearmor(text) does not exist\nLINE 1: ..._on\" FROM \"users_user\" WHERE convert_from(decrypt(dearmor()
I am using a extension in django https://github.com/dcwatson/django-pgcrypto to encrpt and dcrpt data and when I am doing lookup like Employee.objects.filter(date_hired__gt="1981-01-01", salary__lt=60000) Its giving me errot error message: function dearmor(text) does not exist\nLINE 1: ..._on\" FROM \"users_user\" WHERE convert_from(decrypt(dearmor() I am using PostgreSQL 13.0 and django 3.1 -
Compare products together in django
When I select a product, the next modal displays the same product and I can not select the next product, what should be done so that the choices do not affect each other? I use models and can only make one choice To have. I show two of the following modal to the user so that he can have 2 choices, but he can only have one choice. view : def view(request, id): products = get_object_or_404(Product, id=id) ... is_select = False if request.method == 'POST': product_id = request.POST.get('select') filter = Product.objects.get(id=product_id) is_select = True return render(request, 'home/new.html', {'products': products,...}) template : <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-example-modal-sm">Small modal</button> <div class="modal fade bd-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <form method="post" action=""> <div class="row p-5"> {% csrf_token %} {% if category %} {% for img in new_1 %} <div class="col-4"> <input type="radio" {% if products.id == img.id %}checked {% endif %} name="select" value="{{ img.id }}" onchange="this.form.submit();"> </div> {% endfor %} {% else %} ... {% endif %} </div> </form> </div> </div> </div> -
python3 manage.py createsuperuser does not work
when I use python3 manage.py createsuperuser it shows: Username (leave blank to use 'user'): but when i tap enter it doesnt work it shows: Username (leave blank to use 'user'): ^M OR Username (leave blank to use 'user'): user^M the " ^M " appears when I tap Enter. -
Django model_name.item.add(item) add item to all records in the model
I am trying to achieve an order system for an e-commerce site with Django. I have Order Model and OrderItem Model as such class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) date_added = models.DateTimeField(auto_now=True) date_ordered = models.DateTimeField(null = True) def __str__(self): return self.product.name class Order(models.Model): ref_code = models.UUIDField(default=uuid.uuid4, editable=False) items = models.ManyToManyField(OrderItem) owner = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=True) date_ordered = models.DateTimeField(auto_now=True) shipping = models.ForeignKey(AddressAndInfo, on_delete=models.SET_NULL, null=True) is_shipped = models.BooleanField(default=False) price = models.FloatField(default=0.0) And My view function is such: def checkout(request): order_items = OrderItem.objects.filter( owner=request.user).filter(is_ordered=False).all() address = AddressAndInfo.objects.filter(user=request.user).get() if(order_items.count() > 0): total = 0 for item in OrderItem.objects.filter(owner=request.user).filter(is_ordered=False).all(): if item.product.discounted_price > 0: total = total + item.product.discounted_price else: total = total + item.product.price order = Order.objects.create( owner = Profile.objects.get(user= request.user.id), shipping = address, price = total ) new = Order.objects.get(items = None) print(new.ref_code) new.items.add(OrderItem.objects.get(owner=request.user, is_ordered=False)) for item in order_items: item.is_ordered = True item.save() return redirect('dash') else: messages.success(request, 'No item in Cart') return redirect('index') Now the problem here is that when I try to add the second order from the user it adds order-item from the second order to all the existing order and. The result is that all the orders have same … -
Where is /app/hello/templates/db.html located?
I'm new to Heroku and Django and am in the middle of this instruction. As suggested, I put the following URL to my browser: https://xxxx-xxxxx-12345.herokuapp.com/db/ Then, I got this error: TemplateSyntaxError at /db/ 'staticfiles' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz I googled and found a solution that staticfiles in db.html should be changed to static, so I changed: db.html: {% extends "base.html" %} {% load static %} {% block content %} <div class="container"> <h2>Page View Report</h2> <ul> {% for greeting in greetings %} <li>{{ greeting.when }}</li> {% endfor %} </ul> </div> {% endblock %} However, the error don't go away. Then, I noticed that the contents of db.html is different from mine, which is located under C:\Users\xxxxx\python-getting-started\hello\templates\. In template /app/hello/templates/db.html, error at line 2 'staticfiles' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz 1 {% extends "base.html" %} 2 {% load staticfiles %} 3 4 {% block content %} 5 <div class="container"> 6 7 8 <h2>Page View Report</h2> 9 10 11 <ul> 12 ... Where is this file /app/hello/templates/db.html located? I really can't find it. Please … -
Django Rest Framework - Serializer not saving Model that has an ImageField
I have a model of images, Image that have foreign keys on different types of articles. I want to expose this model via a REST interface (built with Django-Rest-Framework) and upload images to it via AJAX calls in Angular 10. Doing File Uploads in general works so far, as I was able to follow this guide here successfully. It does however somehow not work with my ImageModel and ImageSerializer. When I fire my AJAX call at the moment, currently I get a HTTP 500 response on the frontend and this error in the backend in Django: File "/home/isofruit/.virtualenvs/AldruneWiki-xa3nBChR/lib/python3.6/site-packages/rest_framework/serializers.py", line 207, in save 'create() did not return an object instance.' This is a console log of the content of the FormData object I send via AJAX call, which fails for my Image model (Console log was taken by iterating over FormData, as just logging FormData doesn't show its content). Note that bar the image, none of these values are required in the model: Find below the model, the serializer and the view from DRF, as well as my Type-Script POST method to call that API: //Typescript ImageUploadService.ts post method postImage(imageModel: Image, imageFile: File){ const url = `${Constants.wikiApiUrl}/image/upload/`; const formData: FormData = … -
How to use MultipleChoiceFilter in graphene-django?
I have an Django application with graphql endpoint. I need the ability to filter objects at once by several values of a certain field. I have the following graphene Scheme: class ChannelFilter(FilterSet): type = MultipleChoiceFilter(choices=Channel.TYPES) class Meta: model = Channel fields = ['type'] class ChannelNode(DjangoObjectType): class Meta: model = Channel filter_fields = ['type'] interfaces = (relay.Node,) class Query(graphene.ObjectType): channels = DjangoFilterConnectionField( ChannelNode, filterset_class=ChannelFilter ) schema = graphene.Schema(query=Query) Then i tried the following graphql queries to filter my objects: query { channels(type: "BOT") { edges { node { id } } } } As a result, the following error: { "errors": [ { "message": "['{\"type\": [{\"message\": \"Enter a list of values.\", \"code\": \"invalid_list\"}]}']", "locations": [ { "line": 2, "column": 3 } ], "path": [ "channels" ] } ], "data": { "channels": null } } query { channels(type: ["BOT"]) { edges { node { id } } } } As a result, the following error: { "errors": [ { "message": "Argument \"type\" has invalid value [\"BOT\"].\nExpected type \"String\", found [\"BOT\"].", "locations": [ { "line": 2, "column": 18 } ] } ] } How to use MultipleChoiceFilter correctly? Thanks -
django count instances in a model
I have a model ItemAdded and i made a signal so every time a user add an item to the cart an instance is created in the ItemAdded model so what i want to do is count the most added items (in an ascending order) , so what is the easiest way to do this ?? this is the model : class ItemAdded(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) # User instance instance.id content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # User, Product, Order, Cart, Address object_id = models.PositiveIntegerField() # , Product id, content_object = GenericForeignKey('content_type', 'object_id') # Product instance timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return "%s added on %s" %(self.content_object, self.timestamp) class Meta: ordering = ['-timestamp'] # most recent saved show up first verbose_name = 'Object added' verbose_name_plural = 'Objects addded' -
Django giving error and Invalid Parameter to prefetch_related()
I know same questions are already asked but i am just unable to resolve my issue. I have 3 Models class CustomerPackage(models.Model): name = models.CharField(max_length= 20,blank=False, null=False) module = models.ForeignKey(Module, null=False, blank=False, on_delete=models.PROTECT) currency = models.ForeignKey(PackageCurrency,blank=False, null=False, on_delete=models.PROTECT, default=1) description = models.CharField(max_length= 500, blank=False, null=False) is_active = models.BooleanField(default=1) def __str__(self): return str(self.name) class UsecasePackage(models.Model): package = models.ForeignKey(CustomerPackage, null=False, blank=False, on_delete=models.PROTECT) use_case = models.ForeignKey(UseCase, default=1, null=False, blank=False, on_delete=models.PROTECT) month_price = models.IntegerField( null=False, blank=False) quarter_price = models.IntegerField(null=False, blank=False) annual_price = models.IntegerField( null=False, blank=False) def __str__(self): return str(self.package) class PackageCurrency(models.Model): name = models.CharField(max_length= 20,blank=False, null=False) def __str__(self): return str(self.name) I want to get the result by reverse joining CustomerPackage model with other i.e UsecasePackage. I tried to do that like CustomerPackage.objects.filter(module=id).prefetch_related('UsecasePackage_set') It gives me the error that Cannot find 'UsecasePackage_set' on CustomerPackage object, 'UsecasePackage_set' is an invalid parameter to prefetch_related() -
Not able to access a django app in a django project(both are in same directory)
So, I'm trying to create a django project with a django app which can upload and download files. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'uploadapp.apps.UploadappConfig' ] I'm tryind to write this but this is not working and I'm getting an error which says that no module named uploadapp exists. What could be the reason for this? -
Django migrate does not create any migrations on Elastic Beanstalk
As title says. Here is my .ebextestions/django.config (not included in .gitignore of course) container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate python3 manage.py migrate user_auth --noinput" leader_only: true 02_collectstatic: command: "source /var/app/venv/*/bin/activate python3 manage.py collectstatic --noinput" 03_createsu: command: "source /var/app/venv/*/bin/activate python3 manage.py createsu" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "myApp.settings" PYTHONPATH: "/var/app/venv/staging-LQM1lest/bin:$PYTHONPATH" aws:elasticbeanstalk:container:python: WSGIPath: "myApp.wsgi:application" aws:elasticbeanstalk:environment:proxy:staticfiles: /static: static packages: yum: git: [] python3-devel: [] mariadb-devel: [] setting.py file # [...] if 'RDS_HOSTNAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } # [...] cfn-init-cmd.log file 2020-10-24 19:06:58,897 P9954 [INFO] ************************************************************ 2020-10-24 19:06:58,898 P9954 [INFO] ConfigSet Infra-EmbeddedPreBuild 2020-10-24 19:06:58,901 P9954 [INFO] ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2020-10-24 19:06:58,901 P9954 [INFO] Config prebuild_0_myApp 2020-10-24 19:07:03,679 P10119 [INFO] ************************************************************ 2020-10-24 19:07:03,679 P10119 [INFO] ConfigSet Infra-EmbeddedPostBuild 2020-10-24 19:07:03,682 P10119 [INFO] ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2020-10-24 19:07:03,682 P10119 [INFO] Config postbuild_0_myApp 2020-10-24 19:07:03,690 P10119 [INFO] ============================================================ 2020-10-24 19:07:03,690 P10119 [INFO] Test for Command 01_migrate <<== Test succeded 2020-10-24 19:07:03,694 P10119 [INFO] Completed successfully. 2020-10-24 19:07:03,694 P10119 [INFO] ============================================================ 2020-10-24 19:07:03,694 P10119 [INFO] Command 01_migrate 2020-10-24 19:07:03,697 P10119 [INFO] Completed successfully. <<== Migration completed 2020-10-24 19:07:03,704 P10119 [INFO] ============================================================ 2020-10-24 19:07:03,704 P10119 [INFO] Command 02_collectstatic 2020-10-24 19:07:03,708 P10119 [INFO] Completed successfully. 2020-10-24 19:07:03,715 P10119 [INFO] … -
Does Django Rest Framework provides ModelViewSet but for single object
In my application I need to perform CRUD operations on a specific object (for instance the current logged users). I'm attempting to achieve a ModelViewSet which will operate only on a given queryset (for instance, request.user). A ModelViewSet exposes the following endpoints [GET, POST, PATCH, etc...] thing/{id} Since the object is given, I don't need anymore to retrieve the object with a specific ID. So I need something similar to a ModelViewSet but without the ending {id} part [GET, POST, PATCH, etc...] thing In there an already implemeted class to do this? I need to perform CRUD operations. -
Fetching data in realtime from databases via python's gui and web applications
Could someone please explain me the ways that I can receive data from databases (for example sqlite3) in realtime/online. Need an app which would be similiar to chat but with saving all messages to a database and showing messages in a specific window only from database in realtime (may be with a few seconds delay not so important). The main principle of the application - is the global mailing of information between production departments. Each message contains important information like: message text, ip address, username and etc. Do I understand right that for the web-applications there is only one way is to make json-API and fetch data from there using AJAX call? This is my example how I've done it: django (sqlite3) -> rest_framework's serializer -> JS Ajax (5 seconds delay script). (I've already implemented it in work company). So is there any AJAX alternative and is it possible to realize it with another way? Second question is how to make same application via GUI? I googled several days to find a such kind of example but there are only examples with the next functionality: "press button -> make query to db -> receive data". I would like to hear … -
How to develop multi country website for domain specific country with location specifc ads
I have a classified ads web that is developed on the Django rest framework and React.js and I want to deploy it on the country-specific domain, for example, Canada .ca India .in, etc what strategy should I follow to make it easily manageable and each domain-specific web show location related ads. Thanks -
Seller deletes an item from their store. What should happen to a buyer's order history that includes this item?
In buyer's order history, I am saving seller's items that were purchased, as objects. If a particular item object is deleted by a seller, this item shows up as null in order history. Should I be saving item object's data as plaintext to avoid losing data? -
Foreign keys are saved as integer instead of the string attributes in django model. Why can't foreign key value be string?
Foreign keys are saved as integer instead of the string attributes in django model. Why not string? class CreateRoutine(models.Model): createRoutineID = models.AutoField(default = None, max_length=20, primary_key = True, verbose_name='createRoutine ID') dpt_code = models.ForeignKey('Department',default=None,on_delete=models.CASCADE, verbose_name='dpt_code', db_column="dpt_code") fac_shortName = models.ForeignKey('Faculty',default=None,on_delete=models.CASCADE, verbose_name='fac_shortName', db_column="fac_shortName") batch = models.ForeignKey('Batch',default=None,on_delete=models.CASCADE, verbose_name='batch', db_column="batch") section = models.ForeignKey('Batch',default=None,on_delete=models.CASCADE, related_name='section', verbose_name='section', db_column="section") roomCode = models.ForeignKey('Room',default=None,on_delete=models.CASCADE, verbose_name='roomCode', db_column="room") crs_title = models.ForeignKey('Course',default=None,on_delete=models.CASCADE, verbose_name='crs_title', db_column="crs_title") courseCode = models.ForeignKey('Course',default=None,on_delete=models.CASCADE, related_name='Code', verbose_name='courseCode', db_column="courseCode") day = models.ForeignKey('TimeSlot',default=None,on_delete=models.CASCADE,verbose_name='day', db_column="day") duration = models.ForeignKey('TimeSlot',default=None,on_delete=models.CASCADE,related_name='duration', verbose_name='duration', db_column="duration") class Meta: db_table = '"tbl_createRoutine"' verbose_name = "CreateRoutine" verbose_name_plural = "CreateRoutine" -
AttributeError at /profiles/user-profile/2/ 'int' object has no attribute '_meta'
Here I am using an api of notifications. here is the reference of that api link. I have follow the instructions given on the github read me file. But when i try to send an email by actor to recipient .it shows me the error 'int' object has no attribute '_meta'. The actor field and recipient both accept user_ids and I have put them manually. But still didn't work. profiles/Views.py class UserProfileFollowToggle(LoginRequiredMixin,View): login_url = '/accounts/login/' def post(self, request, *args, **kwargs): user_to_toggle_pk=kwargs.get('pk') username_to_toggle = request.POST.get("username") profile_, is_following = UserProfile.objects.toggle_follow(request.user, request.user.id, user_to_toggle_pk ,username_to_toggle) return redirect(f'/profiles/{username_to_toggle}') profiles/models.py class ProfileManager(models.Manager): def toggle_follow(self, request_user,user_id,user_to_toggle_pk, username_to_toggle): profile_ = UserProfile.objects.get(user__username__iexact=request_user.username) is_following = False follower = profile_.follower.filter(username__iexact=username_to_toggle).first() if follower: profile_.follower.remove(follower.id) notify.send(user_id, recipient=user_to_toggle_pk, verb='unfollow you') else: new_follower = User.objects.get(username__iexact=username_to_toggle) profile_.follower.add(new_follower.id) notify.send(user_id, recipient=user_to_toggle_pk, verb='follow you') is_following = True return profile_, is_following traceback: Traceback (most recent call last): File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch return super().dispatch(request, *args, **kwargs) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "C:\Users\AHMED\grapPub\grabpublic\profiles\views.py", line … -
How to create a login pop up model in django-rest-framework in user is not authenticated
Am having simple django blog with a like button on it, but i want to have a login pop up model if user is not authenticated ##MODEL class Song(models.Model): name = models.CharField(max_length=120) like = models.ManyToManyField(User, blank=True, related_name="like") ##Like Api View class SongLikeApiToggle(APIView): authentication_classes = [authentication.SessionAuthentication] permission_classes = [permissions.IsAuthenticated] def get(self, request, slug=None, format=None): obj = get_object_or_404(Song, slug=slug) updated = False liked = False if obj.like.filter(id=request.user.id).exists(): obj.like.remove(request.user.id) liked = False else: liked = True obj.like.add(request.user.id) updated = True data = { 'updated':updated, 'liked': liked } return Response(data) ### TEMPLATE WITH JQUERY I want to have a login popup model if user clicks the like button bellow <a data-href="{% url 'music:like' object.slug %}" class="like_btn" > Like button here </a> function update(btn, verb){ btn.html(verb); } $(".like_btn").click(function(e){ e.preventDefault() var this_ = $(this); var likeUrl = this_.attr("data-href"); $.ajax({ url:likeUrl, method: "GET", data: {}, success: function(data){ console.log(data); var newLikes; if (data.liked){ //add like update(this_, "<i class='fa fa-thumbs-up'></i>"); }else{ //remove like update(this_, "<i class='fa fa-thumbs-o-up'></i>"); } },error: function(error){ console.log(error); console.log("error") } }) } ) below is a Loin model i want to pop up if user is now authenticated <!-- Modal HTML --> <div id="myModal" class="modal fade"> <div class="modal-dialog modal-login"> <div class="modal-content"> <form action="/examples/actions/confirmation.php" method="post"> <div class="modal-header"> … -
html template show me empty page
when i try to run server th project th 1st pg which content a list of names after i check one of them its suppose to show me details for this name but actually its not work the pg was empty can you pleas tell me whr is my mistak thank u project urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('new2/', include('new2.urls')), ] app (new2) urls.py: from django.contrib import admin from django.urls import path,re_path from new2 import views urlpatterns = ( # path('admin/', admin.site.urls), path('', views.index, name='index'), re_path(r'(?P<task_id>[0-9]+)/$', views.details, name='details') ) views.py: from django.shortcuts import render from django.http import HttpResponse from .models import Task from django.template import loader, RequestContext from django.template.response import TemplateResponse def index(request): list_task = Task.objects.all() template = loader.get_template('new2/index.html') RequestContext = { 'list_task': list_task } return HttpResponse(template.render(RequestContext,request)) def details(request, task_id): detail = Task.objects.get(pk=task_id) RequestContext = { 'detail' : detail } return render(request,'new2/details.html',RequestContext) models.py: from django.db import models class Task(models.Model): def __str__ (self): return self.Name_task Name_task = models.CharField(max_length=200) Age_task = models.CharField(max_length=200) details.html: {{Task.Name_task}}</br> {{Task.Age_task}} -
how to save the value in the database in django?
this is my models.py class Profile(models.Model): name=models.CharField(max_length=30) choices = ( ('C', 'C'), ('C++', 'C++'), ('Java', 'Java'), ('Python', 'Python'), ) intrest = models.CharField(max_length=6, choices=choices) this is my views.py if request.method=="POST": choice=request.POST['choice'] this choice has the value which i want to add to my database.how to add this choice in my database? -
Containerize Django Fullstack application with Reactjs frontend served as a django app with webpack and babel
I'm building a fullstack Django app with react js , webpack and babel. My django backend is serving my react frontend as an app via port 8000 with webpack bundling my reactjs. I want to be able to containerize my app so that i will have independent services that ie frontend as container, backend as a container and probably postgresql as a container. Now the major challenge i'm facing is how best can i separate these two main service frontend and backend considering that my Django backend is serving my frontend reactjs app via port 8000. I dont want to use create react app to serve my frontend at its own port 3000, i want to go the webpack and babel route, where i create a frontend app in Django that will host my react js app and its static files. Ultimately my folder structure looks something similar to this -django-app -fontend-app -src-react -components -actions -reducers App.js -static -templates index.html urls.py -another-app -django-app settings.py Dockerfile manage.py package.json webpack.config.js .babelrc Also consider a solution that will be able to make the application scalable ie, providing scaling functionality for the frontend app and backend app services repsectively. -
Django : This field is required on POST request
I'm trying to create a serializer which outputs the Report and also the User information. My task is accomplished by this serializer: class ReportSerializer(serializers.ModelSerializer): latitude = serializers.CharField() longitude = serializers.CharField() city = serializers.IntegerField() type = serializers.IntegerField() # We have created a field which returns a value from get_marker_icon_url marker_icon = serializers.SerializerMethodField('get_marker_icon_url') status_str = serializers.SerializerMethodField('convert_status_toStr') type_str = serializers.SerializerMethodField('convert_type_toStr') status_color = serializers.SerializerMethodField('get_status_color') likes = serializers.SerializerMethodField('random_likes') user = ReportUserSerializer() class Meta: model = Reports fields = [ 'user', 'id', 'type', 'city', 'latitude', 'longitude', 'likes', 'type_str', 'status_str', 'status_color', 'attached_message', 'marker_icon', 'attached_photo', 'date_created' ] ... With this code my serializer returns a response like this: [ { "user": { "id": 1, "username": "3nematix", "profile_pic": "http://192.168.0.29:8000/frontend/static/frontend/images/reports/user_profile_pic.jpg", "verified": false }, "id": 1, "type": 9, "city": 0, "latitude": "6.5123333", "longitude": "51.512586", "likes": 27, "type_str": "OTHER", "status_str": "PENDING", "status_color": "orange", "attached_message": "test", "marker_icon": "OTHER", "attached_photo": "http://192.168.0.29:8000/frontend/static/frontend/images/reports/user_profile_pic_VRjIYTs.jpg", "date_created": "2020-10-21T23:19:06.899302Z" }, ...... ] And this is exactly what I need, but the problem is that when I'm trying to create a new object by a POST request, I get this response: { "user": [ "This field is required." ] } If I would remove 'user' from Meta and user = ReportUserSerializer() from the ReportSerializer class, then I can create a new … -
Filtering form fields
Is it possible to filter the values in the form, exactly what I mean is that only the names of tournament groups created for a given tournament are displayed in the form window and not, as in the present case, that all. this is my models.py file class TournamentUsers(models.Model): user_first_name = models.CharField(max_length=256) user_last_name = models.CharField(max_length=256) user_tournament = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True) user_group = models.ForeignKey(TournamentGroup, on_delete=models.SET_NULL, null=True) def __str__(self): return self.user_last_name + ' ' + self.user_first_name class Tournament(models.Model): data = models.DateField(null=True) tournament_name = models.CharField(max_length=256, null=True) tournament_creator = models.ForeignKey(Judges, on_delete=models.SET_NULL, null=True) def __str__(self): return self.tournament_name class TournamentGroup(models.Model): group_name = models.CharField(max_length=256, null=True) tournament_name = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True) def __str__(self): return self.group_name my forms.py file class TournamentUsersForm(forms.ModelForm): user_first_name = forms.CharField(required=True) user_last_name = forms.CharField(required=True) class Meta: model = TournamentUsers fields = ['user_last_name', 'user_first_name', 'user_tournament', 'user_group'] my views.py file def content(request, pk): tournament = get_object_or_404(Tournament, pk=pk) tournament_groups = TournamentGroup.objects.filter(tournament_name=tournament) users = TournamentUsers.objects.filter(user_tournament=tournament) form = TournamentUsersForm() if request.method == "POST": form = TournamentUsersForm(request.POST) if form.is_valid(): form.save() form = TournamentUsersForm() return render(request, 'ksm_app2/content.html', {'tournament': tournament, 'users': users, 'form': form, 'tournament_groups': tournament_groups}) all I wants is for the user to be able to choose only the team assigned to a given tournament