Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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' … -
Worker only running 1 task, not concurrency on heavy task
I set up my worker using gevent as worker pool options as Max concurrency 100 Prefetch Count 400 I've tried simulating the concurrency tasks with the code import time @app.task def sleep_task(self, timeout=5, **kwargs): time.sleep(timeout) Execute this multiple times and it's working OK with up to 100 concurrent tasks running. But with a heavy task @app.task(bind=True) def heavy_task(self, number_of_lines=5, **kwargs): generate_big_random_sentences(self.request.id, number_of_lines) def generate_big_random_sentences(filename, linecount): """ A helper to generate a random content file """ import random words = ("adorable", "clueless", "dirty", "odd", "stupid") with open(filename, 'w') as f: for i in range(linecount): f.writelines([' '.join([random.choice(i) for i in words]), '\n']) pass If I execute the task multiple times to generate files with around 1 million lines. Looks like the worker only handle 1 by 1 task. One new task will be received every time the running task completed. The heavy task here is just an I/O bounding task. May I ask why the worker doesn't run concurrency or even prefetch multiple tasks like the option we have in this case? Thanks! -
Django JsonResponse not returning serialized data
Why JsonResponce not able to serialized the data, i think I'm getting this error because of for x in cart_obj.products.all() Error: raise TypeError(f'Object of type {o.__class__.__name__} TypeError: Object of type method is not JSON serializable def cart_json_view(request): # defined for ajax cart_obj, new_obj = Cart.objects.create_cart_or_get_cart(request) products = [{ "id": x.id, "url": x.get_absolute_url(), "name": x.name, "price": x.price } for x in cart_obj.products.all()] cart_data = {"products": products, "subtotal": cart_obj.subtotal, "total": cart_obj.total} return JsonResponse(cart_data) -
How to use HTML input value in external python script (Django)
i have html code like: <form action="submit/" method="POST"> {% csrf_token %} <div class="tweets"> <input type="number" name="data_num" min="1" max="1000" placeholder="Jumlah Data" required> <input class="btn_unduh" type="submit" value="UNDUH"> <span style="position: absolute; left: 85%; top: 5%;">Total Tweets: {{count_tdata}}</span> </div> </form> this is some code in views.py def submit(request): i = request.POST.get('data_num') out = run( [sys.executable, 'C:\\Users\\alessandro\\Documents\\Django\\myweb\\tweets\\crawling.py', i], shell=False) out2 = run( [sys.executable, 'C:\\Users\\alessandro\\Documents\\Django\\myweb\\tweets\\import.py'], shell=False) view_tweet = tdata.objects.all().order_by('-date') count_tweet = tdata.objects.count() context = { 'title': 'Tweets | PPL', 'heading': 'Halaman Tweets', 'subheading': 'Analisis Sentimen Twitter', 'db_tdata': view_tweet, 'count_tdata': count_tweet, } return render(request, 'tweets2.html', context) i want to use the value from data_num in my external python script. this is a line from my external py script: crawling.py for tweet in tweepy.Cursor(api.search, q="kuliah online -filter:retweets", lang="id", tweet_mode='extended').items("%s" % (sys.argv[1])): what i want to do is when i input number in data_num, the i in views.py will get the value, and then in crawling.py the .items() will use that value. i tried using something like .items("%s" % (sys.argv[1])) but i get TypeError: '>' not supported between instances of 'str' and 'int' -
Django ignore view function because of auto cache?
In my Django app, I set some break points view functions and it run into view function in the first time. But sometimes it not run into view function since I have run it before and it cache the page, I think so. I know it didn't run into view function because it didn't check break point in function when I debug. So it made my app run wrong. I have tried @never_cache and it worked but I don't think that was a right method. Anyone have solution for this? Thanks you. -
How do I add a breakpoint to a JavaScriptCatalog view?
As per the documentation for JavaScriptCatalog, I added the following lines to the urlpatterns in one of my Django apps: from django.views.i18n import JavaScriptCatalog from django.conf.urls import url urlpatterns = [ # ... url(r"^jsi18n/?", JavaScriptCatalog.as_view(), name="javascript-catalog"), # ... ] But if I navigate to http://localhost/jsi18n, I see that it's not loading the catalog: // ... /* gettext library */ django.catalog = django.catalog || {}; if (!django.jsi18n_initialized) { // ... How do I go about debugging this? How can I insert a breakpoint() into the JavaScriptCatalog.as_view() value to see what it's doing and where it's looking? -
i want to get student last paid fees from fees table where student id = id
THIS IS MY StudentRegistration MODEL class StudentRegistration(models.Model): #joinId = models.CharField(max_length=20) name = models.CharField(max_length=30) phone = models.BigIntegerField() age = models.IntegerField() discription = models.CharField(max_length=200) address= models.CharField(max_length=100,null=True) joiningDate = models.DateField(default=datetime.now) plan = models.ForeignKey(Plan,on_delete = models.CASCADE) This is my student and fees models am trying to get the student details and fees deatils. student paid fees every month but i want to get his last payment . now its showing his all payment THIS IS MY fees MODEL class fees(models.Model): student = models.ForeignKey(StudentRegistration,on_delete=models.CASCADE) paidAmount = models.BigIntegerField() balance = models.BigIntegerField() lastFeePaid = models.DateField(default=datetime.now) feeStatus = models.BooleanField(default=False) -
Multiline {% blocktranslate %} translations not working
I've done makemessages and compilemessages and both files contain the translation that is inside a {% blocktranslate %}. I've even re-run makemessages to make sure nothing changed in the msgid and it did not make any change to my .po file except for the POT-Creation-Date. But these {% blocktranslate %} paragraphs are not translating. I'm stuck with the msgid instead of the msgstr. Is there some trick to very long msgid's? All the other translations seem to be working, but the two paragraph length translations just aren't being translated at runtime. I'm assuming the keys don't match, but not sure why they don't match since the tools don't change the values when re-run. -
JavaScript not found in Django
I am trying to use JavaScript within my Django project. I have made a static folder within my app containing css and js folders, and whilst my css is working my js files are not. Any help would be great, thanks. HTML: {% load static %} <link rel="stylesheet" href="/static/css/style.css?{% now "U" %}"/> <script type="module" src={% static "javascript/app.js" %}></script> settings.py: BASE_DIR = Path(__file__).resolve(strict=True).parent.parent INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'musicPlayer', ] STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", 'musicPlayer/static/javascript/app.js', ] -
How to add an extra false field in the Django REST framework serializer?
I am using django's inbuilt User model to create a registration api with Django REST framework (DRF). I want client to post a request like this { username:'user1', email:'email@email.com, password:'password123', confirm_password:'password123' } The trouble is In the django's built in 'User' database have no field as confirm_password. I dont want to add additional columns to the database and need this false field only to validate the two passwords and not to included it in the database. I wrote this model serializer class RegSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','username', 'email', 'password', 'confirm_password') extra_kwargs = {'password': {'write_only': True},'confirm_password': {'write_only': True}} and created user through User.objects.create_user(request.data['username'], request.data['email'], request.data['password']) But it shows this error django.core.exceptions.ImproperlyConfigured: Field name confirm_password is not valid for model User. How do we add an extra false field in the Django REST framework serilizer? -
ImportError: cannot import name 'EntryView' from 'entries.views'
/* I am getting this error and I don´t know how to solve it: from .views import HomeView, EntryView ImportError: cannot import name 'EntryView' from 'entries.views' (C:\Users\Kheri\dev\cfehome\blog\entries\views.py) */ views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Entry class HomeView(ListView): model = Entry template_name = 'entries/index.html' context_object_name = "blog_entries" class EntryView(DetailView): model = Entry template_name = 'entries/entry_detail.html' url.py from django.urls import path from .views import HomeView, EntryView urlpatterns = [ path('', HomeView.as_view(), name = 'blog-home'), path('entry/<int:pk>/', EntryView.as_view(), name = 'entry-detail') ] -
Django form problems import circular import form
I keep running into when I try to import the view in nav.url, there are already different views being imported from different apps, they do not cause an issue. enter image description here enter image description here enter image description here