Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rendering MPTT structure with open/close possibility in django template
I need to render my MPTT model as tree with dropdown (open/close every node that contains children) possibility and buttons that will open/close all the nodes in that tree in 1 click. I tried to find some ready-to-use examples, but best that I found is this: <ul class="navbar-nav mr-auto"> {% recursetree thecategories %} {% if node.level == 0 %} {% if not node.is_leaf_node %} <!-- Let op: <li> tag wordt steeds onderaan aangevuld, ander werkt het niet...--> <li class="dropdown nav-item"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> <span class="mainBarItem">{{ node.ctg_Title }}<span class="caret"></span> </span></a> {% else %} <li><a href="#" class="mainBarItem">{{ node.ctg_Title }}</a> {% endif %} {% else %} {% if not node.is_leaf_node %} <li class="dropdown-submenu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> <span class="nav-label">{{ node.ctg_Title }}<span class="caret"></span></span></a> {% else %} <li><a href="#">{{ node.ctg_Title }}</a> {% endif %} {% endif %} {% if not node.is_leaf_node %} <ul class="children dropdown-menu"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> with some CSS and JS, but it is not that I need. Actually I need to render just one tree at a time. I'm passing variable {{ product }} in my template that is just a root node. And for now … -
How to create json response from django orm annotate?
I want to create sales per month report and send it to the frontend. here is my serializers.py: from .models import Sale from rest_framework import serializers class SaleSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Sale fields = ['url', 'id', 'date', 'sku', 'product', 'quantity', 'price'] Here is the view from views.py: from django.db.models import Sum from rest_framework.decorators import api_view from rest_framework.response import Response from .serializers import SaleSerializer from .models import Sale @api_view() def monthly_sales(request): monthly_sales = Sale.objects.values( 'date__month').annotate(Sum('price')) serializer = SaleSerializer( monthly_sales, many=True, context={'request': request}) return Response(serializer.data) When I go to browser I get the Attribute error: 'dict' object has no attribute 'pk' What's the solution? -
adding multiple values in django path
I have the following paths set up: urlpatterns = [ path("", views.index, name="index"), path('entry/<str:title>', views.entry, name='entry'), ] my entry method is: def entry(request,title): entries = [] entry = util.get_entry(title) if entry != None: entries.append(entry) return render(request, "encyclopedia/entry.html", { "title": title, "entries": entries, }) and in my html we have: {% block body %} <h1>All Pages</h1> <ul> {% for entry in entries %} <li> a href = "{% url 'entry' title=entry %}" >{{ entry }}</a> </li> {% endfor %} </ul> {% endblock %} two questions: Is this the right way to pass parameters with a link? What would I need to change to pass multiple parameters? -
Create & Return Token in Serializer
Currently having difficulties returning a token in my registration view. How Can I fix this so that UserSerializer's create can return a token and username? View.py @permission_classes([AllowAny]) class UserCreate(generics.CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer Serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() token, _ = Token.objects.get_or_create(user=user) return Response( { 'username': validated_data['username'], 'token': token.key, }, status=HTTP_200_OK ) Error AttributeError: Got AttributeError when attempting to get a value for field `username` on serializer `UserSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Response` instance. Original exception text was: 'Response' object has no attribute 'username'. [13/Nov/2020 20:26:44] "POST /account/register HTTP/1.1" 500 120116 -
Django login error when using incorrect username and password on AWS
I've spent many hours trying to solve this error but I'm stuck. On my local server, when I try to log in with an incorrect email or password, I get the proper error message from the login view on my HTML template. However on my production server, when I try to sign in with an incorrect email and password I get this error in my browser. I feel like this has something to do with uwsgi. ValueError at /login/ invalid method signature Request Method: POST Request URL: http:// My Public IP Address :8000/login/ Django Version: 3.1.3 Exception Type: ValueError Exception Value: invalid method signature Exception Location: /usr/lib/python3.8/inspect.py, line 1808, in _signature_bound_method Python Executable: /usr/local/bin/uwsgi Python Version: 3.8.5 Python Path: ['.', '', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/ubuntu/startup/django/lib/python3.8/site-packages'] Server time: Fri, 13 Nov 2020 19:55:38 +0000 Code Login HTML <div class="login"> <form action="{% url 'login_new' %}" method="post"> {% csrf_token %} <div> <h1 class="heading_login_signup">Login</h1> {{ form.username.errors }} <label class="label_block_bold_colored_red">Email</label> {{ form.password.errors }} <label class="label_block_bold_colored_red">Password</label> </div> <input class="button" type="submit" value="Login"> </form> <div class="login_error"> {% if messages %} {% for message in messages %} {{ message }} {% endfor %} {% endif %} </div> <div> Login Views.py def login_new(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) … -
Django Insert With UUID Foreign Keys Issue
I've been building a Django model using UUIDs as foreign keys. When I try to perform an insert the foreign key constraint kicks in stating that the key doesn't exist in the table, which is not true. If I take the query that is trying to be executed from the Django logs it runs fine in my SQL client. I'm using Django 3.1 with Postgresql 12.4 and trying to run the insert via mutation thru Graphene-Django. The model I'm inserting into is: class Inventory(models.Model): class Meta: db_table = "inventory" id = models.UUIDField(db_column='inventory_id', primary_key=True, default=uuid.uuid4()) item = models.CharField(db_column="inventory_item", null=False, max_length=750) quantity = models.FloatField(db_column="inventory_quantity", null=False) org_id = models.ForeignKey("org.Organization", db_column="organization_id", null=False, on_delete=models.CASCADE) unit_of_measure = models.ForeignKey("InventoryUnitOfMeasure", db_column="inventory_uom", null=False, on_delete=models.CASCADE) The query that Django is executing is: INSERT INTO "inventory" ("inventory_id", "inventory_item", "inventory_quantity", "organization_id", "inventory_uom") VALUES ('453b5dd5-1a9c-462f-adff-c93274e45cfe'::uuid, 'test string', 2000.0, 'f119b93a-d3e1-4f2a-8187-0d3f0ff8d148'::uuid, 'cec0c6e1-a0cc-4b38-b4d8-2c00367b9a01'::uuid); Running that query via SQL client works fine, but the error I receive is: insert or update on table "inventory" violates foreign key constraint "inventory_organization_id_7514cdb8_fk_organizat"\nDETAIL: Key (organization_id)=(f119b93a-d3e1-4f2a-8187-0d3f0ff8d148) is not present in table "organization" That key is in the organization table. If the query wasn't running in my SQL client I'd suspect that it's something around translating the UUID string value, but I'm out … -
Are there any certifications associated with DJango?
Hello helpful programmers, I am here to ask one question. Is there any certification associated with DJango? I am learning DJango and want to do a certification to strengthen my resume. Any Ideas? Help is much appreciated! TIA -
manage.py makemessages doesn't work for project's urls.py file
I am running manage.py makemessages --ignore=venv/* -l fr which seems to be running correctly. Every gettext() call is present in the generated django.po files except the main urls.py file's, therefore showing only the English versions of the URLs. Other urls.py files' (within apps) gettext() calls are successfully found and present in django.po files. P.S.: I am aware of the fact that gettext does not support Python's new f-strings, however there is no f-string inside any gettext() call. My main urls.py file looks like this: from django.contrib import admin from django.urls import path, include from django.conf.urls.i18n import i18n_patterns from django.utils.translation import gettext_lazy as _ urlpatterns = i18n_patterns( path(f'{_("admin")}/', admin.site.urls), path(f'{_("narratives")}/', include('notebook.urls', namespace='narrative')), prefix_default_language=False, ) -
Java 3D ERROR : Canvas3D_createNewContext: Failed in SetPixelFormat
I have the following code in java and I run it in eclipse 2020-09 package pkg3dtest; import java.util.logging.Level; import java.util.logging.Logger; import javax.media.j3d.BranchGroup; import javax.media.j3d.Transform3D; import javax.media.j3d.TransformGroup; import com.sun.j3d.utils.geometry.ColorCube; import com.sun.j3d.utils.universe.SimpleUniverse; public class Cube3D implements Runnable { SimpleUniverse universe = new SimpleUniverse(); BranchGroup group = new BranchGroup(); ColorCube cube = new ColorCube(0.3); TransformGroup GT = new TransformGroup(); Transform3D transform = new Transform3D(); double Y = 0; Thread hilo1 = new Thread(this); //Se declara el hilo public Cube3D() { GT.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); //se setea el grupo de transformación // como un elemento modificable en tiempo de ejecución hilo1.start(); //se inicia el hilo GT.setTransform(transform); GT.addChild(cube); group.addChild(GT); universe.getViewingPlatform().setNominalViewingTransform(); universe.addBranchGraph(group); } public static void main(String[] args) { new Cube3D(); } //@Override public void run() { Thread ct = Thread.currentThread(); while (ct == hilo1) { try { Y = Y + 0.1; //Variable global declarada como double transform.rotY(Y); //Se rota en base al eje Y GT.setTransform(transform); //Se actualiza el gráfico Thread.sleep(100); //Se espera un tiempo antes de seguir la ejecución } catch (InterruptedException ex) { Logger.getLogger(Cube3D.class.getName()).log(Level.SEVERE, null, ex); } } } } When I give save no error appears but when I run in console the following message appears; DefaultRenderingErrorListener.errorOccurred: CONTEXT_CREATION_ERROR: Renderer: Error creating Canvas3D graphics context graphicsDevice … -
Django Form - Why is the django Multiselect widget used in Admin page rendering in the same line as another field?
In my Django project, I have a form that looks like this: class SpecificPriceForm(forms.ModelForm): tanks = forms.ModelMultipleChoiceField(queryset=AutoTank.objects.all(), widget=FilteredSelectMultiple(verbose_name='Tanques', is_stacked=False)) price = forms.FloatField(label='Precio', required=True, min_value=0.0, max_value=100000.0, widget=forms.TextInput(attrs={'type': 'number'})) initial_date = forms.DateField(widget=DateInput( attrs={'class': 'form-control', 'value': datetime.datetime.now().date()}), label="Fecha inicial") final_date = forms.DateField(widget=DateInput( attrs={'class': 'form-control', 'value': datetime.datetime.now().date() + datetime.timedelta(days=7)}), label="Fecha final") class Media: css = { 'all': ('/static/admin/css/widgets.css',), } js = ('/admin/jsi18n',) class Meta: model = SpecificPrice fields = ('tanks', 'price', 'initial_date', 'final_date',) def __init__(self, *args, **kwargs): warehouse_type = kwargs.pop('warehouse_type', None) super(SpecificPriceForm, self).__init__(*args, **kwargs) if warehouse_type == 1: self.fields['tanks'].queryset = Station.objects.all() The problem is that in my view, such form displays like this: I don't know why that field is displayed there, and not under the MultiSelect field. It happens when I just include the form as {{ form|crispy }}, and it keeps happening now that I tried to render the fields individually and in different divs, ,with this code: {% block form %} <div class="form-group" style="display: block"> {{ form.media }} {{ form.tanks }} </div> <div class="form-group" style="display: block"> {{ form.price }} {{ form.initial_date }} {{ form.final_date }} </div> {# {{ form|crispy }}#} {% endblock %} Do you know why would be making in render like that? -
How can i show post in django homepage based on post owner
i make a blogger website, every user has their own post that the other can't see it. i want to show the user last post in the homepage(index.html). what i have tried is if the user already had a post it work well, but if the user doesnt have any post yet, when go to homepage it show other user's last post. how to prevent it? what i want is if the user doesnt have any post yet the homepage show some text that tell the user he doesnt have any post yet. here is my code index.html {% extends "blogs/base.html" %} {% block content %} <div class="container jumbotron p-3 p-md-5 text-white rounded bg-dark"> <div class="col-md-6 px-0"> {% if user.is_authenticated %} <h1 class="display-4 font-italic">{{ post_title }}</h1> <p class="lead my-3">{{texts|truncatewords:20}}</p> <p class="lead mb-0"><a href="#" class="text-white font-weight-bold">Continue reading...</a></p> <small><a href="{% url 'blogs:posts' %}" class="text-white ">See all your posts &raquo;</a></small> {%else%} <h1 class="display-4 font-italic">Welcome To Bogger</h1> <p class="lead my-3">This site is used to post your daily stories without having to worry about other people reading them.</p> <a class="btn-lg btn-primary" href="{% url 'users:register' %}" role="button">Register &raquo;</a> {% endif %} </div> </div> {% endblock content %} views.py def index(request): """The Home Page""" post = BlogPost.objects.all() … -
Need help in query set
I am asking this question second time because last time I didn't get proper answer of this question. Well I think its hard to explain that what I am actually trying to do but let me try to explain briefly so you guys can understand better. . Here in a picture you can see there is a list of followers and we can also see the list of followers and following of each follower. I want run this kind to query. I am trying with the following code views.py def get_context_data(self, *args, **kwargs): context = super(FollowerView,self).get_context_data(*args, **kwargs) user = context['user'] user_com = User.objects.get(username=user) myfollowers = user_com.is_following.all() followers_Array =[] followerings_Array =[] for target_list in myfollowers: user_obj = User.objects.get(username=target_list) followers_obj = user_obj.is_following.all() print(followers_obj,'name o ki line') followerings_Array.append(followerings_Array) print(followers_obj,user_obj) followerings_obj = user_obj.userprofile.follower.all() followerings_Array.append(followerings_obj) print(followerings_obj,user_obj) print(followerings_Array,'arry one one one ') context['myfollowers_data']= followers_Array context['myfollowerings_data']= followerings_Array return context Well I am using two arrays in the code but i don't want to use them,right now i am not getting right output by returning arrays in context. If arrays are unnecessary than tell me the other way and tell me how can i show data the way i show you in the picture, I am sharing followers … -
Updated the UserCreationForm and now cannot register
I needed the change the language of the user registration form in Django and created my own but now when I try to register a random person I am getting the http://127.0.0.1:8180/register/submit error. forms.py class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] class ContactForm(forms.Form): Isim = forms.CharField(max_length=100) Email = forms.EmailField() Mesaj = forms.CharField(widget=forms.Textarea) class CustomUserCreationForm(forms.ModelForm): error_messages = { 'password_mismatch': _("Şifreler aynı değil"), } email = forms.EmailField(label="E-Posta Adresi") password1 = forms.CharField(label=_("Şifre"), widget=forms.PasswordInput) password2 = forms.CharField(label=_("Tekrar şifre"), widget=forms.PasswordInput, help_text=_("Lütfen aynı şifreyi girin")) class Meta: model = User fields = ['email', 'password1', 'password2'] def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) return password2 def clean_email(self): if User.objects.filter(email=self.cleaned_data['email']).exists(): raise forms.ValidationError("Vermiş olduğunuz mail adresiyle bir kayıt bulunmaktadır.") return self.cleaned_data['email'] def save(self, commit=True): user = super(CustomUserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user views.py def register(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') messages.success(request, f'{email} adına hesap oluşturulmuştur! Giriş yapabilirsiniz!') return redirect('login') else: form = CustomUserCreationForm() context = { "footer": Footer.objects.filter(name="Generic").first(), 'form': form } return render(request, 'member/register.html', context) urls. py from django.urls … -
django not adding element to list
here's what I have: from django.shortcuts import render from django import forms from django.http import HttpResponseRedirect from django.urls import reverse class NewTaskForm(forms.Form): task = forms.CharField(label=‘New Task’) priority = forms.IntegerField(label =‘priority’, min_value=1,max_value=5) Create your views here. def index(request): if "tasks" not in request.session: request.session['tasks'] = [] return render(request, "tasks/index.html", { "tasks": request.session['tasks'] }) def add(request): if request.method == “POST”: task = request.POST.get(‘task’) form = NewTaskForm(request.POST) if form.is_valid(): task = form.cleaned_data[“task”] request.session['tasks'] += [task] # or we can try doing it this way # request.session['tasks'] += task return HttpResponseRedirect(reverse("tasks:index")) else: return render(request, "tasks/add.html",{ "form": form }) return render(request, "tasks/add.html",{ "form": NewTaskForm() }) and then in index.html we have: {% extends ‘tasks/layout.html’ %} {% block body %} <h1>Tasks</h1> <ul> {% for task in tasks %} <li>{{task}}</li> {% empty %} <li>No tasks</li> {% endfor %} </ul> <a href="{% url 'tasks:add' %}">Add a new task</a> {% endblock %} HERE’S THE PROBLEM: if we use request.session[‘tasks’] += [task] where task = ‘abc’ we get in the html abc but if we use: request.session[‘tasks’] += ‘abc’ we get in the html : a b c -
How to select the suitable deployment plan
I'm planning to deploy a web api build with django rest api and it will be hosted in a digitalOcean droplet. It's frontend will be in a heroku dyno and frontend is developed in react js. Monthly 6000+ users will use this web application so my question is which plans should I use in heroku as well as digitalOcean to satisfy 6000 users without a downtime . Thank you! -
who can i edit image in the django database?
I have a model of image with them name in Django. my model: class images(models.Model): name = models.CharField(max_length=150) image = models.ImageField() in my template I show the users a list of image name. I want when user click on the name of image, in the image detail template show hem the edited image. my model manager is: def get_by_id(self, product_id): qs = self.get_queryset().filter(id=product_id) if qs.count() == 1: return qs.first() else: return None and my views is: def image_detail(request, *args, **kwargs): img_id= kwargs['image_id'] im = images.objects.get_chart(ch_id) if MineralSpectrum is None: raise Http404 reach_image = im.image.path 'my code for edit image' context = {} return render(request, 'image_detail.html', context) but line 6 is wrong. how can I access the image to edit then render it to image_detail template? I have a model that has two fields, a photo, and a photo name. I created a template(image.html) that showed a list of photo names. When the user clicks on the image name, I want to take the corresponding image in the model from the database, edit it and render the edited image to the image_detail.html template -
Filtering accounts from two different OUs in django-python3-ldap
We have a django project, where users get to login using their local AD access using django-python3-ldap. This has worked fine, since we have been using only one OU until now. However, we now need to get users from other OU, which is at the same level as the current OU. How can we do this? We have setup following: settings.py # The LDAP search base for looking up users. LDAP_AUTH_SEARCH_BASE = 'DC=ypn,DC=local' # Custom setting LDAP_AUTH_FORMAT_SEARCH_FILTERS = 'project.ldap.custom_format_search_filters' ldap.py: from django_python3_ldap.utils import format_search_filters def custom_format_search_filters(ldap_fields): # Call the base format callable. search_filters = format_search_filters(ldap_fields) # Advanced: apply custom LDAP filter logic. search_filters.append('(|(OU=office1)(OU=office2))') # All done! return search_filters And when we run python .\manage.py ldap_sync_users, it just gives us nothing. I know the filtering works, because I can search by names, for example (sn=name), and it will give me correct results. Running search without any filters just results on lots of "junk" accounts, people that have left, computers, etc. and we don't want to bring all that junk onboard. -
How do you get queryset objects related to queryset passed to templates in Django
I have these two models and as you can see they have a relationship. class Post(models.Model): text = models.TextField() class PostImage(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) image = models.FileField(upload_to = 'media/',blank=True, null=True) As far as I understand if I query posts and push them to a template and post, I would expect to use something like this in my templates to retrieve the images URL attached to the posts but it doesn't seem to work. {% for post in posts %} {% for post_image in post.post_image_set.all %} {{post_image.image.url}} {% endfor %} {% endfor %} What am I doing wrong? -
How to save and use timezones in Django
I have an important question. I understand Django saves data in "localtime", that is, UTC for my international app. So, if a user creates an "Event" with startdate (datetime object) 18:00, it will be 18:00 UTC. However, the user lives in Spain (UTC+1), so I store the timezone ("Europe/Madrid") in a different field. When I render it in the html, it will show the UTC time (but the user lives in UTC+1). Then, if I want to convert the time to a visiting user from Spain, I use the timezone tag to convert the datetime to Spain ... and now it will show 17:00. {% if logged_user_profile.timezone %} {% timezone logged_user_profile.timezone %} <p class="text-muted font-weight-bold"> {{ event.date_start|date:"h:i A" }} ({{ logged_user_profile.timezone }} </p> {% endtimezone %} {% else %} <p class="text-muted font-weight-bold"> {{ event.date_start|date:"h:i A" }} ({{ owner_profile.timezone }}) </p> {% endif %} The Spain case is only an example. I guess my question is broad, which is the best way to deal with timezones in django. I need to store the datetime of an event and show it to visiting users in their localtime, if the stored datetime is in UTC, it will not reflect the datetime the user … -
Django stripe subscription Forbidden: issue
Hi I'm trying to implement stripe subscription in django. I have been following a guide from guide link I am facing an issue which gives me the error: Forbidden: /create-sub [13/Nov/2020 23:33:40] "POST /create-sub HTTP/1.1" 403 150 here's my code for the sub part: @login_required def create_sub(request): if request.method == 'POST': # Reads application/json and returns a response data = json.loads(request.body) payment_method = data['payment_method'] stripe.api_key = djstripe.settings.STRIPE_SECRET_KEY payment_method_obj = stripe.PaymentMethod.retrieve(payment_method) djstripe.models.PaymentMethod.sync_from_stripe_data(payment_method_obj) try: print("h-1") # This creates a new Customer and attaches the PaymentMethod in one API call. customer = stripe.Customer.create( payment_method=payment_method, email=request.user.email, invoice_settings={ 'default_payment_method': payment_method } ) print("h1") djstripe_customer = djstripe.models.Customer.sync_from_stripe_data( customer) request.user.customer = djstripe_customer print("h2", customer.id) # At this point, associate the ID of the Customer object with your # own internal representation of a customer, if you have one. # print(customer) # Subscribe the user to the subscription created subscription = stripe.Subscription.create( customer=customer.id, items=[ { "price": data["price_id"], }, ], expand=["latest_invoice.payment_intent"] ) print("h3") djstripe_subscription = djstripe.models.Subscription.sync_from_stripe_data( subscription) request.user.subscription = djstripe_subscription request.user.save() print("h4") return JsonResponse(subscription) except Exception as e: print("sorry") return JsonResponse({'error': (e.args[0])}, status=403) else: return HttpResponse('requet method not allowed') I tried various sources but could solve it. I believe the issue lies somewhere in stripe.Customer.create. Any help would be … -
Displaying Data from 2nd Table into 1st Table automatically as Pre-Filled for SuperAdmin (Foreignkey)
Using Django, i have 2 Tables. 1 Table is for the list of questions that User answers, the user would enter numbers. The 2nd Table is for the total Calculation, it simply just shows the total calculated number. I want to show the Total Calculated Number also in the 1st Table. So i have created a Foreign Key to do this. I have placed the Foreign Key inside the 1st Table. But when the User answers and submit the form, when i got to the 1st Table, the foreign key column/row is blank. It is forcing me as the SuperAdmin to open up the entry in the table, and manually select the value for the foreignkey. Also it is not showing in the interface of the table value of Total Calculated Number, it is just showing the 2nd table which is a class and entry number. first picture below displays the two tables in the super admin side, 1st table-"ansquestionss" 2nd table -"resultss" 2nd picture below shows after opening the 1st table "ansquetionss", you can see the foreign key column, which as the column "Results" is blank. (if working correctly This should be automatically pre-filled) 3rd picture below, displays that … -
Django redirect with parameter - NoReverseMatch at
After executing create_goal(), I want to redirect to customer_info(): def create_goal(request, savingsGoalUid): # do stuff customer_id = "43debcf7-8477-4d96-91e6-c3fb0291ea87" return redirect('customer_info_id', customer_id=customer_id) def customer_info(request, customer_id=None): if customer_id is None: # do stuff else: # do more stuff context = {"foo": customer_id} return render(request, "starling/show_details.html", context) I get: NoReverseMatch at /create_goal Reverse for 'customer_info' with keyword arguments '{'customer_id': '43debcf7-8477-4d96-91e6-c3fb0291ea87'}' not found. My urls.py looks like this: urlpatterns = [ path("", views.index, name="index"), path("customer_info", views.customer_info, name="customer_info"), path("create_goal", views.create_goal, name="create_goal"), path("customer_info/<customer_id>", views.create_goal, name="customer_info_id"), path("delete/<savingsGoalUid>", views.delete, name="delete") ] I tried all sorts of variations including customer_info_id, customer_info, formatting a whole new url+query string, but nothing works. All I want is to just pass customer_id as parameter to customer_info() when I redirect to customer_info() after create_goal(). Thanks for any help! -
access picture in django rest framework in views for picture operations
I am using Django Rest framework to create an OpenCV API for face detection. I want to do operation on post image using OpenCV but I am not able to access the image. How can I access the image in views.py here is my code and thanks for your help. #models.py from django.db import models # Create your models here. class MyFile(models.Model): file = models.FileField(blank=False, null=False) description = models.CharField(max_length=255) uploaded_at = models.DateTimeField(auto_now_add=True) from PIL import Image from django.core.files.storage import FileSystemStorage from django.core.files.base import ContentFile from django.conf import settings from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response import Response from rest_framework import status from api.face_detection import face_detect from .serializers import MyFileSerializer class MyFileView(APIView): parser_classes = (MultiPartParser, FormParser) def get(self, request, *args, **kwargs): return Response( {'title': 'Opencv RestAPI for face detection'}) def post(self, request, *args, **kwargs): file_serializer = MyFileSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How i can display a list instead of choicelist in django
Each time i want to add an invoice, i want to have a unique invoice_id which is an increment number (+1), but the problem is that i have a multiple users app, so i get the error that this invoice_id already exist. how can i customize the ids so each user can have its ids following the latest of same user. class Company(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=64) class Invoice(models.Model): company = models.ForeignKey('Company', on_delete=models.CASCADE) invoice_id = models.CharField(max_length=20, unique=True) name = models.CharField(max_length=256) -
how can i edit multiple objects/row atonce in django html template
i facing an problem on my django project . i try to edit and update an objects . but it's showing an error which is name is MultipleObjectsReturned . hear is my issue screenshots . when i was clicked this update button ( user can update which he went ) . than showing next 2nd image 1st img showing this error 2nd image Views.py def purchase_order_item_update(request,order_id): purchase_item_list = Purchase_order_item.objects.filter(order_id=order_id) # porder = Purchase_order_item.objects.get(order_id=order_id) # this is the form for getting data from html if request.method == 'POST': for bt in Purchase_order_item.objects.filter(order_id=order_id): pu_id = bt.puid # product Id quantity = request.POST.get('asqty') unit_price = request.POST.get('uprice') # itemid = pk type total = int(quantity) * float(unit_price) cv = Purchase_order_item.objects.get(puid=pu_id) cv.quantity = quantity cv.unit_price = unit_price cv.total_price = total cv.save() return redirect('purchase_order_item',order_id= order_id) return render(request,'back/purchase/assign_purchas_item.html', {'purchase_item_list':purchase_item_list, }) Actually i went to edit and update this list of entries and update also if user making any typing mistake then he can update . thank you