Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django allow anonymous ajax request to access a Generic View
This is what I've got so far: from django.views.generic import View from django.views.decorators.csrf import csrf_exempt class ConfigurationView(View): @csrf_exempt def dispatch(self, *args, **kwargs): return super(ConfigurationView, self).dispatch(*args, **kwargs) def get(self, request): ... However, when I make an ajax get request to this view I am not able to access the get method function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } $.ajax({ url: "https://{{ domain }}/configure", headers: { 'X-CSRFToken': getCookie('csrftoken') }, crossDomain: true, data: { email: "{{ email }}", }, dataType: "json" }) I think I am sending the csrftoken correctly and I shouldn't really need the csrf_exempt, but either way the request gets a redirection to the login page. Any help would be highly appreciated. -
Autocomplete search in Django
I am using autocomplete function to filter data, from this site: https://api.jqueryui.com/autocomplete/ First I am using Django. everything work perfectly with this method if it is in page with no extends. but if I use it in page which is inside a block extends it doesn't work!?? {% extends 'Home/base.html' %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'Home/plugins/jquery-ui/jquery-ui.css' %}"> <script src="{% static 'Home/plugins/jquery/jquery.js' %}"></script> <script src="{% static 'Home/plugins/jquery-ui/jquery-ui.js' %}"></script> So it works when I delete {% extends 'Home/base.html' %}? what is the problem? -
django-filters multiple related fields: filter down the fields
I am using django-filters module to filter my table. I can filter the data but can not bind the fields. After I filter by one field, another field should contain only related values. Table I am filtering As you can see in the picture when I filter by the field "Şube", I can see the related values that should be contained by "Kaynak" field on top but "Kaynak" dropdown still contains all its values. My models: class Subeler(models.Model): subeadi = models.CharField(max_length=200) class AltKaynaklar(models.Model): tali_adi_x = models.CharField(max_length=200) subeadi = models.ForeignKey(Subeler, null=True, on_delete=models.SET_NULL, related_name="bagli_kaynaklar") class AKMutabakat(models.Model): tali_adi_x = models.ForeignKey(AltKaynaklar, null=True, on_delete=models.SET_NULL) subeadi = models.ForeignKey(Subeler, null=True, on_delete=models.SET_NULL) ..... My filter: class UretimFiltre(django_filters.FilterSet): class Meta: model = AKMutabakat fields = ['subeadi', 'tali_adi_x', 'trafik_mi', 'yil', 'ay'] My views.py: def mutabakat(request): context = {} kaynaklar = AltKaynaklar.objects.filter(subeadi=request.GET.get('subeadi')) sources = AKMutabakat.objects.all() myFilter = UretimFiltre( request.GET, queryset=sources, ) context['myFilter'] = myFilter I can query related "Kaynak" values like in the picture but can't put it inside the filter. Can anybody help? -
The proper way of getting the value of a TimeField in Django
Imagine that in a Educational Management System I have created a form for entering the details for a ,let say, course. After I save it to the database(in my case postgres) I want to provide the user with the opportunity to edit the previously saved form. So I have to initialise a form with the initial values that user has previously entered. Everything is Alright but the problem is that I cannot format the the TIME input (let say the time that course starts) received from the database into a proper shape to be suitable for in my html. So the initial value is not shown in the time input.How can I solve this problem? -
how to prevent user from going back to form (all forms login, edit post, etc.) after submission in django?
I'm new to django and I'm stuck with a problem. Please help me solve it. Problem: Whenever I fill a form, be it a login form, edit post form, create post form, etc..If I press browser's back button, It takes me back to it. What I want: Redirect the user to somewhere else rather than taking them back to form. Is there any way to perform it in django ? I want to use CBVs only "and yes, I don't wanna disable browser back button !" Code: views.py class CreatePost(LoginRequiredMixin, UserPassesTestMixin, CreateView): model = Post template_name = 'blog/create_post.html' fields = ('category', 'title', 'meta_title', 'meta_description', 'content', 'image', 'image_alt_text') user_check_failure_path = 'blog-home' def test_func(self): return self.request.user.is_superuser def handle_no_permission(self): if self.request.user.is_authenticated: messages.error(self.request, 'Permission Denied ! Only SUPERUSER can access this page', 'danger h4') return redirect('blog:blog-home') else: return redirect('accounts:login') class Login(views.LoginView): template_name = 'accounts/login.html' redirect_authenticated_user = True -
i have an issue in djangorest profile_data = validated_data.pop('profile') KeyError: 'profile'
class UserSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('first_name', 'last_name', 'phone_number', 'age', 'gender') class UserRegistrationSerializer(serializers.ModelSerializer): profile = UserSerializer(required=False) class Meta: model = User fields = ('email', 'password', 'profile') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): profile_data = validated_data.pop('profile') user = User.objects.create_user(**validated_data) UserProfile.objects.create( user=user, first_name=profile_data['first_name'], last_name=profile_data['last_name'], phone_number=profile_data['phone_number'], age=profile_data['age'], gender=profile_data['gender'] ) return user -
Using Django F expression with Case, When expression
I have a Django model like # app/models.py class tbl_invoice(models.Model): invoice_id = models.IntegerField(blank=True, null=True) client_id = models.ForeignKey(tbl_customer, on_delete=models.CASCADE) invoice_number = models.IntegerField(blank=True, null=True) date = models.DateField(blank=True, null=True) amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) paid_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) balance = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) date_of_payment = models.DateField(blank=True, null=True) status = models.CharField(max_length=50, default='', blank=True, null=True) I have another view in which I am saving payment record, I want to update status as Paid or Unpaid depending on if the difference between the user-entered amount and balance is 0 or not currently, this is what I have done #app/views.py if form.is_valid(): post = form.save(commit=False) # rest of the logic goes here post.save() # this data is saved in another model, after that I update invoice model tbl_invoice.objects.filter(invoice_id=someIdHere).update(paid_amount=F('paid_amount')+post.amount, date_of_payment=post.date, balance=F('balance')-post.amount, status=Case( When(balance=F('balance')-post.amount==0, then=Value("Paid")), When(balance=F('balance')-post.amount!=0, then=Value("Unpaid")), )) this query is updating status as blank. however, using only the F expression to update amount and balance is working fine tbl_invoice.objects.filter(invoice_id=someIdHere).update(paid_amount=F('paid_amount')+post.amount, date_of_payment=post.date, balance=F('balance')-post.amount the above statement is working fine surely I am making some obvious mistake that I can't figure out. How can I use the F expression with Case?? -
Python - \x characters while reading from an uploaded file
I am using python3.6 and django 2.2.6 in the backend. I am uploading a .odt file without any encoding. When I do this print(type(request.FILES['labfile'])) print(request.FILES['labfile'].read()) It gives me <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> And this: https://pastebin.com/4WiueuMb The original contents of the odt file is https://pastebin.com/6qT1XWJR I tried doing request.FILES['labfile'].read().decode("utf-8") and I got 'utf-8' codec can't decode byte 0xd2 in position 12: invalid continuation byte I thought \x could mean hex and tried decoding using .decode("hex") and codecs.decode() but that didn't work either. Now it seems like the data is somehow related to xml, but I am not having any idea of how to decode. Any leads are highly appreciated and thankful. Thanks in advance. -
I want to show cateogory wise product
I am trying to make an e-commerce project for that reason I want to show category wise product but I am really confused have no faith in me that I will able to do that so I need some guide or help for this I just created a view I ama giving this below: cart = request.session.get('cart') if not cart: request.session['cart'] = {} #products = None cats = Category.get_categories() brands = Brand.get_brands() sliders = Slider.objects.all() offers = Offer.objects.all() categoryID = request.GET.get('category') brandID = request.GET.get('brand') if categoryID: products = Product.get_products_by_category(categoryID) else: products = Product.get_all_products() if brandID: proucts = Product.get_brands_by_products(brandID) else: products = Product.get_all_products() products = [] catprods = Product.objects.values('category', 'id') cats = {item['category'] for item in catprods} for cat in cats: product = Product.objects.filter(category=cat) products.append(['products']) args = { 'products':products, 'cats': cats, 'brands': brands, 'sliders':sliders, 'offers':offers } return render(request, 'Home/index.html', args) Its giving me an error. don't know what to do please help -
Need help in resolving the error 'The QuerySet value for an exact lookup must be limited to one result using slicing'
I am relatively new to django and I have got an error which I am unable to understand. I have 3 models namely customer, services and uses. I want to fetch the services used by a customer. I am doing this via the uses model by querying the models(specifically using the filter method). However I am getting the following error ValueError at /employee/view_customer/ The QuerySet value for an exact lookup must be limited to one result using slicing. Here are my models Customer class Customer(models.Model): firstname = models.CharField(max_length=15) lastname = models.CharField(max_length=15) age = models.IntegerField() sex = models.CharField(max_length=10) phoneno = models.IntegerField() emailid = models.CharField(max_length=25) address = models.CharField(max_length=50) children = models.IntegerField() adults = models.IntegerField() roomtype = models.CharField(max_length=10) aadharno = models.CharField(max_length=15) daysstayed = models.IntegerField() date_visited = models.DateTimeField(default=timezone.localtime()) def __str__(self): if self.firstname == None: return '' else: return str(self.id) Services class Services(models.Model): service_name = models.CharField(max_length=15) price = models.IntegerField() def __str__(self): if self.service_name == None: return '' else: return str(self.service_name) Uses class Uses(models.Model): customer = models.ForeignKey(Customer,on_delete=CASCADE) service_id = models.ForeignKey(Services,on_delete=CASCADE) time_used = models.TimeField(default=timezone.localtime()) def __str__(self): if self.customer == None: return '' else: return str(self.customer) The function at employee/view_customer def view_customer(request): if request.method == 'POST': customer = Customer.objects.all() uses = Uses.objects.filter(customer_id=customer) services = Services.objects.filter(id=uses) print(services) return render(request,'employee/cust-info.html',{'customer':customer,'services':services}) … -
DB design and ideas for a webserver management system
I'm working on a "(web)server management system" for my local webserver, to learn django on something useful. (Maybe when it's done and other people will be interested, I'll release that as an open source project.) My problem is, I'd like a real-time graphs for CPU/RAM usage and CPU temperature and also history graphs. For the real-time I'd get the data every second, saved it and send it via websockets to clients. But, I dont want one big table of values per second, cos in one year it would have 31.5M rows, that's too much :) So for the history data I probably need just average,max and min values per day (?) But also when I reach some percentage (for example 70%), I should have a log of processes that were consuming the cpu/ram. So I'd have probably a per_sec table, which I'd truncate at midnight after I saved the average,max,min values to a per_day table. Plus I'd have a peaks and peaks_processes tables. Also I'd use some in-memory db for the last 10seconds values - to faster serve the websockets. Or does anybody have any better ideas for the db design? And what else might a real server admin be … -
How To install the redis on windows
I want the run the django channels in production.so i want to use the redis but I try to install that using pip install redis it is not working for me -
Added more fields to a form but the changes aren't showing up
Title pretty much sums it up. I added some new fields to a form that a group member created, but when I runserver I can't see the changes. I render it in the view, changed the form in forms.py, added the view to urls.py, tried linking it to a model (idk why this would work, but a TA suggested it). In the template I use form.as_p to display it. Right now only the volunteer_hours char input field is displaying. Does anyone know what I might have done wrong? forms.py: class VolunteerForm(forms.Form): volunteer_title = forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter event name'}) day = forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Day (DD)'}) month = forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Month (MM)'}) year = forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Year (YYYY)'}) volunteer_hours = forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter the number of hours'}) views.py: class VolunteerView(CreateView): form_class = VolunteerForm template_name = 'volunteer.html' def get(self, request, *args, **kwargs): form = VolunteerForm() render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = VolunteerForm(request.POST) if form.is_valid(): pass args = {'form': form} return render(request, self.template_name, args) urls.py: urlpatterns = [ path('', views.donate, name='donate'), path('payment', PaymentView.as_view(), name='payment'), path('payment/thanks', ThanksView.as_view(), name='thanks'), path('volunteer', VolunteerView.as_view(), name='volunteer') ] volunteer.html: <!DOCTYPE html> <html lang="en"> <!-- Bootstrap and starter template … -
Fetch field Details for a login use in Django REST Framework with foreignkeyfield Relationship
I am trying to add Value into InstantInvestment Model in Django REST Framework which is working. but, only want to show the shipping that is specifically for the login user in. which means, the present situation is giving all the shipping not for this user. models.py class Shipping(models.Model): investor = models.ForeignKey(User, related_name='shipping', on_delete=models.CASCADE) beneficiary = models.CharField("Beneficiary Name", max_length=150) bank = models.ForeignKey(Bank, related_name="bank", on_delete=models.CASCADE) account = models.CharField(max_length=10) address = models.TextField("Shipping Adresss") created_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.beneficiary class Meta: verbose_name = 'Shipping' verbose_name_plural = 'Shippings' class InstantInvestment(models.Model): investor = models.ForeignKey(User, related_name='instantivestment', on_delete=models.CASCADE) ref_code = models.CharField(max_length=200, blank=True, null=True) investment = models.FloatField("Investment in dollar") rate = models.FloatField("Exchange Rate") transferable = models.FloatField("Money Transferable") conversion = models.FloatField("Rate in Naira") product = models.ForeignKey(Product, related_name='instant_product', on_delete=models.CASCADE) shipping = models.ForeignKey(Shipping, related_name='shipping', on_delete=models.CASCADE) done = models.BooleanField("Completed Transaction", default=False) created_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.investor.get_full_name()} - Transaction Code: {self.ref_code}' class Meta: verbose_name = 'InstantInvestment' verbose_name_plural = 'InstantInvestments' serializers.py class ShippingSerializer(serializers.ModelSerializer): class Meta: model = Shipping fields = ('beneficiary', 'bank', 'account', 'address') class QucikPaymentSerializer(serializers.ModelSerializer): class Meta: model = InstantInvestment fields = ('url', 'id','investment', 'rate', 'transferable', 'conversion', 'product', 'shipping') views.py class QuickPaymentView(viewsets.ModelViewSet): queryset = InstantInvestment.objects.all() serializer_class = QucikPaymentSerializer permission_classes = [ permissions.IsAuthenticated ] def … -
Django: Form ValidationError: ['“” value has an invalid date format. It must be in YYYY-MM-DD format.']
I have a form which has few fields which will be date. The user will enter those dates in DD/MM/YYYY format. First I was using the forms.DateField() to store the value which was throwing error becuase of the date format. So changed them to CharField & try to re-format those dates to store it in the DB in YYYY-MM-DD format inside the clean methods but some weird reason it keeps raising the above error & has no information of the field which causing the error. I have spent hours trying to debug that but no luck. dob, doj, confirmation_date, exit_date are the date fields in the Model & form My Model: class Employee(models.Model): class Meta: db_table = 'employees' # emp types TRAINEE = 1 CONTRACTUAL = 2 PERMANENT = 3 EMP_TYPES = ( (TRAINEE, 'Trainee'), (CONTRACTUAL, 'Contractual'), (PERMANENT, 'Permanent'), ) # active status ACTIVE = 1 RESINGED = 2 TERMINATED = 3 ABSCOND = 4 LONG_LEAVE = 5 TRN_TO_EMP = 6 EMP_STATUS = ( (ACTIVE, 'ACTIVE'), (RESINGED, 'RESINGED'), (TERMINATED, 'TERMINATED'), (ABSCOND, 'ABSCOND'), (LONG_LEAVE, 'Active'), (TRN_TO_EMP, 'TRAINEE TO EMPPLOYEE'), ) # probation/confirm status PROBATION = 'p' CONFIRMED = 'c' # genders MALE = 'm' FEMALE = 'f' TRASNGENDER = 't' GENDERS … -
Pop up message in Django
I have a form in Django where I upload many files and then perform some data processing on those files. I want to display a loader message while it's still processing in the backend. I know we can use messages in django but it only shows after the processing is complete, I want to display a little animation while data is being processed. Is there any other way to achieve this? Forms.py class UploadFileForm(forms.Form): file_A = forms.FileField(label= "Upload File-A ") file_B = forms.FileField(label= "Upload File-B ") year = forms.IntegerField() Views.py def display_uploadpage(request): if request.method == 'POST': form = BudgetForm(request.POST, request.FILES) if form.is_valid(): file_A = form.cleaned_data["file_A"] file_B = form.cleaned_data["file_B"] year = form.cleaned_data["year"] fs = FileSystemStorage() file_A_name = fs.save(file_A.name, file_A) file_B_name = fs.save(file_B.name, file_B) p = ProcessData(year, file_A,file_A_name, file_B, file_B_name) msg = p.process() messages.info(request, msg ) return render(request, 'website/upload.html') else: form = UploadFileForm() context = {'form': form} return render(request, 'website/upload.html', context) upload.html <form method="post" enctype="multipart/form-data"> <!-- form method --> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-danger" id="upload">Upload</button> </form> I wanted to add this animation in the page while it's still processing. -
How to insert data to Django database from python file periodically
can anyone please help me I have created a model, like so class TickerOHLC(models.Model): date = models.DateField() open = models.FloatField() close = models.FloatField() low = models.FloatField() high = models.FloatField() volume = models.FloatField() def __str__(self): return str(self.date), str(self.open) and I can insert data into the database by uploading a file in the admin panel using import-export, like so Screenshot of admin panel Here are the admin.py content from django.contrib import admin from .models import * from import_export.admin import ImportExportModelAdmin @admin.register(Task, TickerOHLC) class ViewAdmin(ImportExportModelAdmin): pass How can I import data to the database from a .py file? I have tried this from tasks.models import TickerOHLC #This import gives an error: No module named 'tasks' dataframe = generateDataframe() #function that returns a dataframe datas = [ TickerOHLC( date = dataframe.iloc[row]['Date'], open = dataframe.iloc[row]['Open'], close = dataframe.iloc[row]['Close'], low = dataframe.iloc[row]['Low'], high = dataframe.iloc[row]['High'], volume = dataframe.iloc[row]['Volume'], ) for row in dataframe.iterrows() ] TickerOHLC.objects.bulk_create(datas) Here are my folder structure Screenshot of folder structure I am new to Django and I don't even know if my approach is possible My goal is to be able to run a script periodically that inserts into the database Any kind of help is greatly appreciated, thank you -
How to fix "django.db.utils.DatabaseError: DPI-1047: 64-bit Oracle Client library cannot be loaded: "libclntsh.so"?
I have error like this : web_1 | django.db.utils.DatabaseError: DPI-1047: 64-bit Oracle Client library cannot be loaded: "libclntsh.so: cannot open shared object file: No such file or directory". See https://oracle.github.io/odpi/doc/installation.html#linux for help how to solve this problem? -
How to pass request.user with a ManyToMany Field in Django
I have two models Exercise and Area, Area has a manytomanyfield back to Exercise: class Exercise(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) name = models.CharField(max_length=100) class Area(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) name = models.CharField(max_length=100) exercise = models.ManyToManyField(Exercise, blank=True) I want the user to be able to create a new exercise that automatically attaches to its specific area, and also passes in request.user. Here is my view: from .forms import ExerciseForm as e_form class ExerciseFormView(CreateView): form_class = e_form success_url = '/' def form_valid(self, form): form.save() area = Area.objects.get(pk=self.kwargs["area_id"]) new_ex = Exercise.objects.latest('id') new_ex.user = self.request.user area.exercise.add(new_ex) form.instance.user = self.request.user return JsonResponse({'exercise': model_to_dict(new_ex)}, status=200) And its registered url: path('exercise-add-new/<int:area_id>/', ExerciseFormView.as_view(), name='exercise_add_new'), I should add that this used to work until I recently added user as a field to the Exercise model, and new_ex.user = self.request.user to the view. Now when I try to submit the form nothing happens. No errors, and no objects are created. I have tried new_ex.user = self.request.user and form.instance.user = self.request.user and still nothing happens. Btw my user attributes are a ForeignKey to the auth user model: from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) -
django-reversion - Add django admin filter for at least one changed version
I am using django-reversion which works great. I wonder how I can build the following feature without slowing down my system too much: I want a filter in the django admin which shows all objects of the given class which habe at least one change (amount versions > 1 because the initial one is always there). I thought about overwriting the queryset and annotating something like this: @admin.register(MyModel) class MyModelAdmin(VersionAdmin): list_filter = ('has_changes') def get_queryset(self, request): return super().get_queryset(request).annotate(...) # here would need to go some magic But how would I get the annotated property to my filtering logic? Thanks in advance! Ronny -
How to print post data on the same web page?
I am trying to print the POST data from django form on my webpage, right under my form. I am able to print it by HttpResponse on a different page, but I want it on the same page when the user presses submit button. Views.py from django.views.generic import TemplateView from django.shortcuts import render from django import forms from django.http import HttpResponseRedirect, HttpResponse from home.forms import HomeForm def home(request): def get(request): form = HomeForm() return render(request, 'home/home.html', {'form':form}) if request.method=='GET': response=get(request) return response elif request.method == 'POST': form = HomeForm(request.POST) if form.is_valid(): text = HomeForm('post') return HttpResponse('post') else: form = HomeForm() return render(request, 'home/home.html', {'form':form}) Forms.py from django import forms class HomeForm(forms.Form): post = forms.CharField( widget= forms.TextInput() ) Html template <div class="container"> <form method='post'> {% csrf_token %} {{ form.as_p }} <input type="submit" value="submit" class="btn btn-danger"> </form> <h2>{{ text }}</h2> </div> I want the post field input to be displayed in the 'text' mentioned in the h2 tag of the webpage as soon as the user presses the submit button, and not on a separate page like HttpResponse does. -
Opening an existing Django project with VS Code through Anaconda
I installed Django and started a project via cmd yesterday. Today I installed Anaconda with VS Code and I now want to open my Django project in VS Code through Anaconda. Is this possible? Id like Anaconda to be my interface for all my projects regardless of what they are. Is this possible? thanks V -
Django - How can I render the "new note" text field so the user can update their notes?
Currently I can only figure out how to update them by passing in a string using "note.text". Here is what it looks like when the user creates a new note: https://imgur.com/a/XvSujlQ Here is my current code (Full application at - https://github.com/claraj/lmn/tree/master/lmn): path('notes/latest/', views_notes.latest_notes, name='latest_notes'), path('notes/detail/<int:note_pk>/', views_notes.note_detail, name='note_detail'), path('notes/for_show/<int:show_pk>/', views_notes.notes_for_show, name='notes_for_show'), path('notes/add/<int:show_pk>/', views_notes.new_note, name='new_note'), path('notes/detail/<int:note_pk>/delete', views_notes.delete_note, name='delete_note'), path('notes/detail/<int:note_pk>/update', views_notes.update_note, name='update_note'), @login_required def new_note(request, show_pk): show = get_object_or_404(Show, pk=show_pk) if request.method == 'POST' : form = NewNoteForm(request.POST) if form.is_valid(): note = form.save(commit=False) note.user = request.user note.show = show note.save() return redirect('note_detail', note_pk=note.pk) else : form = NewNoteForm() return render(request, 'lmn/notes/new_note.html' , { 'form': form , 'show': show }) @login_required def update_note(request, note_pk): note = get_object_or_404(Note, pk=note_pk) if note.user == request.user: note.text = "Note text changed" note.save() return redirect('note_detail', note_pk=note.pk) else: return HttpResponseForbidden <form action="{% url 'update_note' note.pk %}" method="POST"> {% csrf_token %} <button type="submit" class="update">Update</button> </form> -
How to retrieve data from url using django urls
this is the call back URL which am getting from the payment gateway I am integrating with http://127.0.0.1:8000/checkout/mfsuccess/?paymentId=060630091021527961&Id=060630091021527961 I want to extract the paymentId int from this URL so I can use it in my function this is the URL line am using path('checkout/mfsuccess/?<str:paymentId>', gateway_Success, name='mf_success'), and this is my function def gateway_Success(request, id): payment_id = request.GET.get('id') print(payment_id) context = { "payment_id": payment_id } return render(request, "carts/checkout-mf-success.html") How I do that since the way am doing not working -
Django send errors to angular
For my backend in django I have it set to the email and username fields must be unique. If they aren't unique I want it to send back to angular saying which one isn't unique how would I go about doing this. Currently it just gives me 400 bad request. This is my register.component.ts import { Component, OnInit } from '@angular/core'; import {FormBuilder, FormGroup, Validators} from '@angular/forms'; import {RegisterService} from './account.service' import {Router} from '@angular/router' @Component({ templateUrl: 'register.component.html', styleUrls: ['register.component.css'] }) export class RegisterComponent implements OnInit { form: FormGroup; loading = false; submitted = false; constructor( private formBuilder: FormBuilder, private registerService: RegisterService, private router: Router, ) { } ngOnInit() { this.form = this.formBuilder.group({ username: ['', Validators.maxLength(15)], password: ['', Validators.maxLength(20)], email: ['', Validators.email], first_name: ['' , Validators.maxLength(15)], last_name: ['', Validators.maxLength(15)] }); } // convenience getter for easy access to form fields get f() { return this.form.controls; } emailError : string = ''; usernameError : string = ''; onSubmit() { this.submitted = true; // stop here if form is invalid if (this.form.invalid) { return; } this.registerService.register(this.form.value).subscribe( response => { alert('User Created') }, (error: any) => { console.log(error) } ); } This is my account.service.ts import {Injectable} from '@angular/core' import {HttpClient} from '@angular/common/http' …