Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to turn a Page object to Json
I have this social network project for learning purposes, and I'm trying to add a pagination feature to it. I manage to successfully render all the posts in a page with JavaScript after I turn them into a JSON. The problem is that I get this error: Object of type Page is not JSON serializable when I try to paginate the posts like this: all_posts = Post.objects.all().order_by("-timestamp").all() serialized_posts = [post.serialize() for post in all_posts] paginator = Paginator(serialized_posts, 10) #every page displays up to 10 post page_obj = paginator.get_page(pagenumber) return JsonResponse(page_obj, safe=False) Here is the Post model: class Post(models.Model): autor = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, default="", related_name="user_post") content = models.TextField(max_length=240) likers = models.ManyToManyField(User, related_name="posts_liked") timestamp = models.DateTimeField(auto_now_add=True) def serialize(self): return { "id": self.id, "autor": self.autor.username, "content": self.content, "likers": [user.username for user in self.likers.all()], "timestamp": self.timestamp.strftime("%b. %d, %Y, %H:%M %p"), "autor_profile_pic": self.autor.profile_picture } Any ideas on how to work this out? -
django: Unable to get sorl-thumbnail working
I am making a django site where users can upload images and I want to use sorl-thumbnail for thumbnail generation and caching. I am using a container based workflow using podman on a fedora silverblue host. I have setup a memcached cache engine (using the memcached docker image), and can set and get values to and from the cache in django-shell with no issues. I have run the migrate command with sorl-thumbnail added to my installed-apps. I have run the ./manage.py createcachetable command and no errors. I am using pylibmc with: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', 'LOCATION': '127.0.0.1:11211', } } I have created a model which has the sorl.thumbnail ImageField, although I hope to use a standard imagefield eventually, which I believe is possible. I have checked my postgres database and the thumbnail_kvstore table is created but never populated with any data. I have the following model, view, and template: model... class Image(models.Model): image_file = ImageField(upload_to=user_directory_path) #thumbnail = models.ImageField(upload_to=str(user_directory_path) + '_thumb', null=True) userprofile = models.ForeignKey(ForumProfile, on_delete=models.CASCADE, related_name="images") view...(the get function is added during debugging this issue)... class ForumProfileUploadView(LoginRequiredMixin, FormView): form_class = ImageForm template_name = 'list.html' success_url = reverse_lazy('my-view') def get(self, request, *args, **kwargs): form = self.form_class() message = … -
Getting a KeyVault secret using a GitHub secret
I'm working on an Azure sample and want to use GitHub actions to deploy this Django solution. https://docs.microsoft.com/en-us/azure/app-service/tutorial-python-postgresql-app?tabs=powershell%2Cclone#1-set-up-your-initial-environment This YAML works: name: Build and deploy Django app to Azure App Service on: push: branches: - master env: WEBAPP_NAME: ${{ secrets.WebApp_Name }} # Set the WebApp name from GITHUB secrets SERVICE_PRINCIPAL: ${{ secrets.AZURE_SERVICE_PRINCIPAL }} KV_NAME: "xxdjangoDemo-KV" KV_SECRET: 'SECRET-KEY' . . . - name: Log in to Azure CLI uses: azure/login@v1 with: creds: ${{ env.SERVICE_PRINCIPAL }} - name: Get Key Vault values uses: Azure/get-keyvault-secrets@v1.0 with: keyvault: ${{ env.KV_NAME }} # Set the name of the KEY VAULT in Azure portal from GITHUB secrets secrets: ${{ env.KV_SECRET }} # comma separated list of secret keys to fetch from key vault id: myGetSecretAction # ID for secrets that you will reference This doesn't: name: Build and deploy Django app to Azure App Service on: push: branches: - master env: WEBAPP_NAME: ${{ secrets.WebApp_Name }} # Set the WebApp name from GITHUB secrets SERVICE_PRINCIPAL: ${{ secrets.AZURE_SERVICE_PRINCIPAL }} KV_NAME: ${{ secrets.KEY_VAULT_NAME }} KV_SECRET: ${{ secrets.KEY_VAULT_SECRET_NAME }} . . . . - name: Log in to Azure CLI uses: azure/login@v1 with: creds: ${{ env.SERVICE_PRINCIPAL }} - name: Get Key Vault values uses: Azure/get-keyvault-secrets@v1.0 with: keyvault: ${{ env.KV_NAME }} … -
Django Rest Framework does not filter after resetting queryset
My url will be something like: ... /? Search = modal. I want to replace the "modal" with empty "" to clean the filter and return all records. Views.py class AnexoExamesViewSet(viewsets.ModelViewSet): search_fields = ['descr'] filter_backends = (filters.SearchFilter,) queryset = AnexoExames.objects.all() serializer_class = AnexoExamesSerializer def get_queryset(self): queryset = AnexoExames.objects.all() search_descr = self.request.query_params.get('search',None) print(search_descr) if search_descr=='modal': queryset = AnexoExames.objects.filter(descr='') return queryset This way it is returning zero results -
django ModelForm extra field
i will like to have extra field in modelForm. From this extra field i will like to pass the value to field in model when save. this is example what i want to get will like to generate name in random name field, and save to database as name models.py from django.db import models class Test2App(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name forms.py from django import forms from .models import test2App class TestForm(forms.ModelForm): class Meta: model = Test2App fields = ['name'] Views.py def add_name(request): if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): form.save() return redirect('test_name') else: form = TestForm() return render(request, 'test/add.html', {'form': form}) html <form method="post"> {% csrf_token %} <label for="name">Random Name</label> <button>Generate</button> <input id="name" name="name_test"> {{ form}} <input type="submit" value="Submit"> </form> -
Django Admin Stack Inline Itself (Same Model) Indefinitely
Given the following models class File(models.Model): id = models.AutoField(primary_key=True) class Loop(models.Model): id = models.AutoField(primary_key=True) file = models.ForeignKey(File, on_delete=models.CASCADE, null=True, blank=True) loop = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True) class Segment(models.Model): id = models.AutoField(primary_key=True) file = models.ForeignKey(File, on_delete=models.CASCADE, null=True, blank=True) loop = models.ForeignKey(Loop, on_delete=models.CASCADE, null=True, blank=True) I want to build a nested admin where the user can: User adds a File After adding a File, the user can either directly add a Segment or a Loop If the user directly adds Segment, well it ends there. However, if the user happens to add a Loop, he/she should have an option to again add either the Loop or Segment Something like this: File Segment Loop Segment Loop Loop Segment Segment ..... ..... I have tried the following but it apparently doesn't work. class SegmentInline(nested_admin.NestedModelAdmin): model = Segment class LoopInline(nested_admin.NestedModelAdmin): model = Loop inlines = [SegmentInline, LoopInline] class FileAdmin(nested_admin.NestedModelAdmin): model = File inlines = [SegmentInline, LoopInline] It fails with the following error: NameError: name 'LoopInline' is not defined How do I achieve this in Django Admin? Any workarounds to this? -
Does Django Channels support a synchronous long-polling consumer?
I'm using Channels v2. I want to integrate long-polling into my project. The only consumer I see in the documentation for http long polling is the AsyncHttpConsumer. The code I need to run in my handle function is not asynchronous. It connects to another device on the network using a library that is not asynchronous. From what I understand, this will cause the event loop to block, which is bad. Can I run my handler synchronously, in a thread somehow? There's a SyncConsumer, but that seems to have something to do with Web Sockets. It doesn't seem applicable to Long Polling. -
django: object count dont work for other def
I have an odd issue, countAll doesn't work for def about(request), however, if I inserted it into def home(request) it's working fine. What could be the issue? Any suggestions on why it doesn't work? def home(request): featured = Oglas.objects.order_by('-list_date').filter(is_published=True).filter(is_featured = True)[:4] regularni = Oglas.objects.order_by('-list_date').filter(is_published = True).filter(kategorija = 'prodava').filter(is_featured = False)[:5] iznajmuva = Oglas.objects.order_by('-list_date').filter(is_published = True).filter(kategorija = 'iznajmuva').filter(is_featured = False)[:5] context = { 'featured' : featured, 'regularni': regularni, 'iznajmuva': iznajmuva, } return render(request, 'pages/home.html', context) def about(request): countAll = Oglas.objects.all().count() context = { 'countAll': countAll, } return render(request, 'pages/about.html', context) html {% if countAll %} <p>Total {{ countAll }}</p> {% else %} <p>None</p> {% endif %} -
Pandas/Django - Cannot convert csv saved as filefield into dataframe
I'm building a database that stores csv files and presents them when a user selects the csv he/she wants to visualize. The problem is, whenever I open the csv file from the database the resulting dataframe is garbage models.py class Csv(models.Model): file_name = models.FileField(upload_to='csvs', max_length = 100) public = models.BooleanField(default = False) user = models.ForeignKey(User, on_delete = models.CASCADE, null = True) name = models.CharField(max_length = 100) library = models.CharField(max_length = 100, null = True) def __str__(self): return "File id: {}".format(self.id) views.py def test(request): csv = Csv.objects.get(id = 5) df = pd.DataFrame(csv.file_name) print(df.head()) return render(request, 'mainproj/test.html', {'df' : df.dtypes}) Test_Data.csv A header Another header First row Second row The print statement in views.py returns the following output that I cannot even understand and the dataframe spits out odd values for things like columns, dtypes, ect... meanwhile import pandas as pd df = pd.DataFrame(pd.read_csv('Test_Data.csv')) print(df) returns the following as expected -
Django giving me an error for trying to load a static file
I am doing a simple Django website and I linked to css file in my html : <!DOCTYPE html> <html> <head> <title>Is it new year's</title> <link rel="stylesheet" href="{% static 'newyear/styles.css' %}"> </head> <body> {% if newyear %} <h1>YES</h1> {% else %} <h1>NO</h1> {% endif %} </body> </html> I created a folder called static inside my app and I created a folder called newyear inside of that one and then created my styles.css inside of it. But when I try to load the page python is giving me this error Invalid block tag on line 5: 'static'. Did you forget to register or load this tag? -
Django | Cannot access URLs without a trailing "/"
I have a Django application where, for some reason, I cannot load my URLs without a trailing "/" I have other Django applications I've made in practice where this hasn't been an issue, and I don't need one when I go to my Admin page, so I can't figure out what's setup wrong here. Here's my main URLs file: urlpatterns = [ path('app/', include('app.urls')), ] Here's my app's URLs file: urlpatterns = [ path('subapp/', views.subapp, name='subapp'), ] And my views file: def subapp(request): return render(request, 'app/subapp.html', {'title': 'subapp'}) When I enter my URL as "localhost:8000/app/subapp/" it takes me to the correct page. However, when I enter my URL as "localhost:8000/app/subapp" I get a 404 with the following debug error message: Directory indexes are not allowed here. What am I doing wrong? -
Showing value in views.py to html
So what I am trying to do is to show a value from my Views.py in my index.html. Views.py def index(request): the_uploaded_excel_file = excel_upload.objects.order_by('-id').first() excel_file_path_from_db = the_uploaded_excel_file.my_excel_file.path print(excel_file_path_from_db) wb = load_workbook(excel_file_path_from_db) ws = wb["Sheet1"] df = pd.read_excel(excel_file_path_from_db, engine='openpyxl', sheet_name='Sheet1', skiprows=1) max_date_column = ws.max_column last_date_entered = ws.cell(row=1, column=max_date_column).value todays_date = datetime.date.today() Date_difference = pd.date_range(start= last_date_entered, end=todays_date, freq='D') print("last date entered was ") print(last_date_entered) print("todays date is ") print(todays_date) print("the days not done is") print(Date_difference) for date in Date_difference: print(date) return render(request, "index.html", { 'Date_difference': Date_difference }) Index.html <h2> {{ for date in Date_difference }} {{ date }} {{ endfor }} </h2> the problem is that when I do just {{ Date_difference }} in my index.html it show an array of the dates i want. but When i try to put them in the for loop it the page wont load. when i do {{ Date_difference }} it gives me: DatetimeIndex(['2021-01-28', '2021-01-29', '2021-01-30', '2021-01-31', '2021-02-01', '2021-02-02', '2021-02-03', '2021-02-04'], dtype='datetime64[ns]', freq='D') But when I do the for loop i get the error: Could not parse the remainder: ' date in Date_difference' from 'for date in Date_difference' -
Error at Login page - TypeError: __init__() got an unexpected keyword argument 'request'
I've successfully created a custom user using AbstractBaseUser and I'm now trying to create the login page using CBV LoginView as follows: class UserLogin(LoginView): authentication_form = UserLoginForm template_name = 'registration/login.html' I have redirected LOGIN_REDIRECT_URL as required in settings. The form I am using is as follows: class UserLoginForm(forms.Form): username = forms.CharField(label='username') password = forms.CharField(widget=forms.PasswordInput) but I keep getting thrown the error: TypeError: __init__() got an unexpected keyword argument 'request' Any ideas? I would guess it's to do with the way I have implemented the CBV but a quick explanation of what I am doing wrong would be greatly appreciated. Cheers. -
http error 405, "save" button, ManyToMany | Django
I'm trying to create a "save" button for a post in Django, however, when clicking on "save" I get a HTTP ERROR 405. models.py class Post(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) description = TextField() some_value = models.CharField(max_length=100, null=True, blank=False, unique=True) saved = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="post_save") def total_saved(self): return self.saved.count() SAVE_OPTIONS = ( ('Save', 'Save'), ('Delete', 'Delete') ) class PostSave(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=SAVE_OPTIONS, max_length=8) edited = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) views.py class PostDetailView(LoginRequiredMixin, PermissionRequiredMixin, DetailView): slug_field = "some_value" slug_url_kwarg = "some_value" model = Post template_name = 'post.html' permission_required = 'post.view_post' def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) post = get_object_or_404(Post, some_value=self.kwargs['some_value']) total_saved = post.total_saved() context['total_saved '] = total_saved return context @login_required(login_url='login') def save_post_view(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if user in post_obj.saved.all(): post_obj.saved.remove(user) else: post_obj.saved.add(user) postsave, created = PostSaved.objects.get_or_create(user=user, post_id=post_id) if not created: if post_saved.value=='Save': postsave.value='Delete' else: postsave.value= 'Save' else: postsave.value='Save' licitacion_obj.save() licitacionguardada.save() return redirect('posts:search') urls.py app_name = 'posts' urlpatterns = [ path('search/', PostListView.as_view(), name='search'), path('<path:some_value>/', PostDetailView.as_view(), name='post'), path('save/', save_post_view, name='save'), ] post.html <form action="{% url 'licitacion:guardar' %}" method="POST"> {% csrf_token %} <input type="hidden" name="licitacion_id" value="{{ licitacion.id }}"> <button type="submit" class="nav-item btn btn-round btn-outline-dark" style="color: … -
python Django fill in auto-created Profile model with User registration form
I am creating an art marketplace with django. I have the registration and the auto-create signal set up for the profile. There are three types of Users who will register on this app: Artists, Patrons, and Brokers (I call these user_status.) I would like the User to choose one of these three fields on the registration form. I have gotten to the point where the reg form has the choicefield and the choices and the user can select one and the form saves to create the User and Profile, but the profile does not have a selected 'user_status' when I go in to admin. I am aware it is heavily discouraged to bundle up profile modelfields at registration, but I'd like for just this one field to be selectable since it will have a major effect on how the site will look for the user. I have read (here) that there would be a lot of annoying customization involved to properly fill profile fields at registration. Is this true? I think if there is a solution it'll be on Signals.py but am not sure. In signals.py when I type in: user_status='Patron', Can I replace the 'Patron' with something like instance.get('user_status')? … -
Get last few items and append to list with while loop
Hi I'm trying to get some data from an model with a while loop. So in the code shown below n is a number and orderMessage is the data I want to append to an list. So what the loop should do is get as many rows as the number n and append it to a list Full. orderMessage changes depending on the index i given to the filter statement. Now my question is, for ex. n = 12 so I want to get the last 12 entries from the MessageItem Model and append it to a list. How could I do that? n = CartQuantity.objects.filter(customer=customer).values_list('cquantity', flat=True).last() m = MessageItem.objects.filter(customer=customer).last() i = 0 while i <= n: orderMessage = MessageItem.objects.filter(customer=customer)[i] Full = [] aFull = Full.append(orderMessage) print(Full) send = aFull print(send) i += 1 message_to_send = str(message) + str(n) + str(m) Here are the models: class MessageItem(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) mItem = models.CharField(max_length=255, null=True) mQuantity = models.CharField(max_length=255, null=True) mOrderItem = models.CharField(max_length=255, null=True) class CartQuantity(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) cquantity = models.IntegerField(default=0, null=True, blank=True) I hope you guys understand my english and my question. I'm very thankful for any solutions -
Django nested html Forms
I have a template to create/modify a model, the way I do it is with one model form and three modelformset_factory, this is necessary because the original model has 3 many to many thorugh relationships. I have achivied the task previously mention, my problem is that I use a java script code that add formset dynamically by the user (still missing the dynamically remove). The javascript code only works by adding a new html form, and thats the main reason why i need to nest html forms, I know that it can't be achieved via html. So, what I'm asking is, if there is a work around? The next code gives an formset Validation Error: missing management form, I can fix it by combining all the forms into one, but I need the multiple forms to add dynamically the formsets my template: <body> <form class="main-form" method="POST" action="" id="main-form"> {% csrf_token %} {{dtCrearMbl.management_form}} <div class="main-form"> <table> {{dtCrearMbl.as_table}} </table> </div> <form id="form-container-panel" method="POST" > {% csrf_token %} {{dtCrearPnl.management_form}} {% for lpFormset in dtCrearPnl %} <div class="panel-form" form="main-form"> {{lpFormset.as_p}} </div> {% endfor %} <button id="add-form-panel" type="button">Add Another Panel</button> </form> <form id="form-container-panel" method="POST"> {% csrf_token %} {{dtCrearComp.management_form}} {% for lpFormset in dtCrearComp %} <div … -
Django find all model objects with more than x related foreign objects
So say I have two Django model objects with a one-to-many relationship like: class A(models.Model): id = models.AutoField(primary_key=True) attribute = models.CharField(max_length=30) related = models.ForeignKey(B, on_delete=models.CASCADE) class B(models.Model): id = models.AutoField(primary_key=True) username = models.CharField(max_length=30) year_created = models.IntegerField() and I need to find all the instances of B that were created after year x that have more than 3 instances of A How would I structure this filter? Something like: dealership.objects.filter(year_created__gte=1999) but only include objects with more than x related A's -
how to configure wsgi file properly with gunicorn
i can't recognise in whole scale what i am doing wrong nginx is working and bad gateway is not shown its been 30 day i am trying to fix main_website - is folder with django_project and manage.py static media django_project - is with settings.py and wsgi.py another_user-i make another user with password to upload by git and www/html/main_website/ user is another_user but i give group www-data thanks so much gunicorn.service /etc/systemd/system [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] Type=notify User=www-data Group=www-data WorkingDirectory=/var/www/html/main_website/ ExecStart=/home/another_user/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ django_project.wsgi:application [Install] WantedBy=multi-user.target gunicorn.socket /etc/systemd/system [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } default config /sites-available server { listen 80; listen [::]:80 default_server; server_name example.com; (i change here only example.com) charset utf-8; # max upload size client_max_body_size 75M; # Django media location /media { alias /var/www/html/main_website/media; } location /static { alias /var/www/html/main_website/home; } … -
Why does the images in Django are not rendering?
I'm trying to build a Stripe checkout, but the images on the preview are not rendering correctly. The images aren't appearing. settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/images/' urls.py: urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) payments.html: <div class="header"> <h1>Order Summary</h1> </div> {% for order in items %} <div id="order-items"><div class="line-item"> <img class="image" src="{{ order.image.url }}" alt="Stripe Pins"> <div class="label"> <p class="product">{{ order.item.title }}</p> <p class="sku">Collector Set</p> </div> {% if order.item.discount_price %} <p class="count">{{ order.quantity }} x {{ order.item.discount_price }}€</p> {% else %} <p class="count">{{ order.quantity }} x {{ order.item.price }}€</p> {% endif %} {% if order.item.discount_price %} <p class="price">{{ order.get_total_discount_item_price }}€</p></div> {% else %} <p class="price">{{ order.get_total_item_price }}€</p></div> {% endif %} {% endfor %} -
Update SerializerMethodField in Django REST Framework
I have a serializer+models like this: class Dates(models.Model): date: date = models.DateField(verbose_name='Datum') indicator: str = models.CharField(max_length=1, null=True, default=None, blank=True, verbose_name='Indikator') entry: Entry = models.ForeignKey(Entry, on_delete=models.PROTECT, related_name='dates') class Entry(models.Model): pass class EntrySerializer(serializers.ModelSerializer): bookings = SerializerMethodField() # implicitly `get_dates` class Meta: model = Entry fields = ( 'id', 'dates', ) read_only_fields = ('id',) def get_dates(self, instance): try: start = self.context.request.query_params.get('start') start = datetime.strptime(start, '%Y%m%d') except: start = None d = { date.strftime('%Y%m%d'): indicator for (date, indicator) in instance.dates.all().values_list("date", "indicator") } dates = start.date_range(start) # just returns a list of dates for date in dates: d.setdefault(date.strftime('%Y%m%d'), '') return d I am using SerializerMethodField to create empty "padding" dates, should an Entry not have a Date object assigned for a certain date within the given date range. The output JSON looks like this: [ { "id": 1, "bookings": { "20210203": "D", "20210204": "D", "20210205": "2", "20210201": "", "20210202": "", "20210206": "", "20210207": "", "20210208": "", "20210209": "", "20210210": "", "20210211": "", "20210212": "", "20210213": "", "20210214": "", "20210215": "", "20210216": "", "20210217": "", "20210218": "", "20210219": "", "20210220": "", "20210221": "", "20210222": "", "20210223": "", "20210224": "", "20210225": "", "20210226": "", "20210227": "", "20210228": "" }, }, ...] I am trying to now actually … -
Web Data Sync between multiple devices(PC, Laptop, Mobile, Tablet) for a same user using multiple browsers
I am looking for a working approach to sync data between different sessions that the user might use - (With different sessions or with multiple devices). Step 1. User1 logins to webapp from a PC1, Browser1 and starts to edit a form/file(F1). Step 2. User1 Logins to the same webapp from PC2, Browser2 and starts to edit a file(F1). Step 3. User1 goes back to edit the form from PC1. Step 4. User1 moves to PC2 to edit the form. For any of the step above, the user needs to always access the updated form. FrontEnd - React JS backend Node/Django Thanks, Garima -
How to automatically set a foreignkey that cannot be edit for users django
I would like an advice. I am creating a django application where users can register comments, what I want to do is that when a user registers a comment, the user is automatically registered as its author because it does not make sense that a user can register a comment in the name of another user, In order to do this, I have defined my model and views like this models.py from django.contrib.auth.models import User from django.forms import ModelForm, widgets class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) description = models.CharField(max_length=30) class my_form(ModelForm): class Meta: model = Comment fields = '__all__' widgets = {'author': widgets.Select(attrs={'disabled': True}),} views.py from django.shortcuts import HttpResponse from .models import Comment, my_form def my_view(request): user = User.objects.get(username=request.user) if request.method == 'POST': form = my_form(request.POST, request.FILES) request.POST._mutable = True form.data['author'] = user # As the form field is disabled the view has to complete it if form.is_valid(): form.save() return HttpResponee("Success") else: return HttpResponse("Fail") else: form = my_form(initial={'author':user}) return render(request, "my_app/my_template.html", {"form":form}) my_template.html <div class="container"> <section> <form enctype="multipart/form-data" action="/new_comment/" method="POST">{% csrf_token %} <div class="form-row"> <div class=" form-group col-md-4"> {{form.author|as_crispy_field}} </div> <div class=" form-group col-md-4"> {{form.description|as_crispy_field}} </div> </div> <br> <button type="submit" class="btn btn-outline-dark">Submit</button> </form> <br> </section> </div> So as the form´s … -
When i want to add a product to my cart i have a keyerror
When i click add to cart i have the following error in views.py: "In updateItem, productId = data['productId'] KeyError: 'productId' " views.py line 70 where i have my error: def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('productId:', productId) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order = order, product = product) if action == 'add': orderItem.quantity = (orderItem.quantity +1) elif action == 'remove': orderItem.quantity = (orderItem.quantity -1) orderItem.save() if orderItem.quantity <=0: orderItem.delete() return JsonResponse('El item fue agregado', safe=False) carrito.js: function updateUserOrder(productId, action){ console.log('Usuario logeado y enviando data...') var url = '/update_item/' fetch (url, { method: 'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'productId': productId, 'action':action}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log('data:', data) location.reload() }) } My template carrito.html: When i click on the button Add to cart i have the issue. {% extends 'tienda/index.html' %} {% load static %} {% block content %} </div> {% for item in items %} <div class="cart-row"> <div style="flex:2"><img class="row-image" src="{{item.product.imageURL}}"></div> <div style="flex:2"><p>{{item.product.name}}</p></div> <div style="flex:1"><p>{{item.product.price|floatformat:2}}</p></div> <div style="flex:1"> <p class="quantity">{{item.quantity}}</p> <div class="quantity"> <img data-product={{item.product.id}} data-action="add" class="chg-quantity update-cart" src="{% static 'images/arrow-up.png' %}"> <img data-product={{item.product.id}} data-action="remove" class="chg-quantity update-cart" src="{% static 'images/arrow-down.png' %}"> </div> … -
Django queryset join two or more models that use the same foreign key or have nested relationships
I want to get an aggregated data related to each Tree entry. from django.db import models class Tree(models.Model): tree_name = models.CharField(max_length=100, unique=True) class Branch(models.Model): tree = models.ForeignKey(Tree, on_delete=models.CASCADE) branch_type = models.ForeignKey(BranchType, on_delete=models.CASCADE) branch_health = models.ForeignKey(AppConfig, on_delete=models.CASCADE) last_checked = models.DateTimeField(null=False) class BranchType(models.Model): type_name = models.CharField(max_length=30, unique=True) class Stump(models.Model): tree = models.OneToOneField(Tree, on_delete=models.CASCADE) stump_info = models.ForeignKey(StumpInfo, on_delete=models.CASCADE) class StumpInfo(models.Model): scientific_term = models.CharField(max_length=100, unique=True) class AppConfig(models.Model): key = models.CharField(max_length=100, unique=True) value = models.CharField(max_length=100) The output I am looking for is something like this: [ { "tree": "ucxdfg", "branch": {// The tree can have a lot of branches, but I only target branches from past 24 hours. "branch_type_1": "average",// The health is coming from app_config ["good","average", "poor"] "branch_type_2": "good" }, "stump_info": { "scientific_term": "xyz" } }, { "tree": "awerdf", "branch": { "branch_type_1": "good" }, "stump_info": { "scientific_term": "xyz" } }, { "tree": "powejf", "branch": { "branch_type_2": "poor" }, "stump_info": { "scientific_term": "abc" } }, ... ] I am not sure how I would design the queryset to do this.