Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - on delete -> unhashable type: 'Highscore'
I made an simple webpage with Django. It stores highscores. I can't delete an highscore because it throws an exception. The exception says unhashable type: 'Highscore' (I don't think it makes an difference but i also got an foreign key but that shouldn't be the problem) So i already flushed the DB (Database) and reset it up (makemigrations, migrate, new inputs) but that doesn't work. I also can't delete it over the adminpage (127.0.0.1:8000/admin). def highscore_delete(request, h_id): try: h = Highscore.objects.get(id=h_id) h.delete() except Highscore.DoesNotExist: raise Http404('Highscore not found') except Exception as ex: return HttpResponseBadRequest(ex) return redirect('highscore_index_route') It throws the exception at h.delete(). More information under under: https://pastebin.com/9kaF4NBy (i will post noncritical code there) Of course the entry doesn't get deleted, even though this method work multiple times already. (There is no syntax error) -
Django url is not picking the updated django view
Use Case : When ever i am tryng to access my url e.g.http://127.0.0.1:8000/dashboard/ it always picks the old code from dashbaord/views.py Old view : def dashboard(request): context = {'data':[29,25,25]} template='dashboard.html' return render(request,template,context) Updated view def dashboard(request): abc='pankaj' context = {'data':[15,20,10]} template='dashboard.html' return render(request,template,context) When i am loading this page, it gives some error and shows the old view code not the latest one. What i have done. I am running server locally by command python manage.py runserver deleted all previous .pyc files But, the problem still remains the same . Any input in this direction would be a great help!! -
how to display checked checkbox items and date time field in django
I want to edit and update student information with this edit_student.html page.When i go to the edit page all the values stored appears except checkbox items and date field.image appears but does not update. how can i update image and display already checked items and already added date while editing models.py class Student(models.Model): name = models.CharField(max_length=100) courses = models.CharField(max_length=500) address = models.CharField(max_length=200) email = models.EmailField() phone = models.CharField(max_length=15) image = models.ImageField(upload_to='Students',blank=True) joined_date = models.DateTimeField() views.py def editstudent(request,id): student = Student.objects.get(id=id) courses = Course.objects.all() # for course in courses: # course.has_checked = what logic should i have to write here return render(request,'students/edit_student.html',{'student':student,'courses':courses}) edit_student.html <div class="form-group"> <h5>Joined Date <span class="text-danger">* </span></h5> #it doesnot display already added value <div class="controls"> <input type="date" name="joined_date" value=" {{student.joined_date|date:'m-d-Y'}}" data-validation-required-message="This field is required" class="form-control" required> </div> </div> <div class="form-group"> <h5>Courses <span class="text-danger">*</span></h5> <div class="controls"> {% for course in courses %} <input name ="courses" type="checkbox" id="course- {{course.id}}" value="{{course.title}}"># it doesnot display already checked courses <label for="course-{{course.id}}">{{course.title}} </label> {% endfor %} </div> </div> <div class="form-group"> <h5>Image <span class="text-danger">*</span></h5> <div class="controls"> # image displays but not updates while choosing new image Currently:<img src="/media/{{student.image}}" width="50" height="50"> <br> New:<input type="file" name="image" class="form- control" > </div> </div> -
Internal Server Error for url: https://api.linkedin.com/v1/people/
I'm getting 500 server error after oauth2 with LinkedIn url: https://api.linkedin.com/v1/people/~:(email-address,first-name,formatted-name,id,last-name,picture-url,public-profile-url)?format=json here I used python Django framework with below packages *python-social-auth *social-auth-app-django *social-auth-core how can I fix this issue? -
In django, how can I get detailed error information in ajax?
I'm learning web programming with Django. Currently I'm trying to build a webpage that users can update their user profile (such as e-mail, nickname). I'm using ajax to process this data. But I just came up with a question that how can I get detailed ajax error information? For example, an user wants to update his nickname or e-mail, but the nickname or e-mail he posts is already existing in the database. In ajax, I use error:function (XMLHttpRequest, textStatus, errorThrown) {} to get the error information. But I just get something like "500 Internal server error". However, in the browser console I can see whether "nickname" or "e-mail" is duplicated. So I wonder how I can get to know which one is duplicated? My view.py is: @login_required def edit_usr_profile(request): user = request.user objs = UserProfile.objects.filter(usr=user) usr_objs = UserProfile.objects.get(usr=user) if request.method == 'POST': if request.is_ajax(): usr_objs.nickname = request.POST.get('nickname') usr_objs.email = request.POST.get('email') usr_objs.save() return render(request, 'account/edit_profile.html', {'objs':objs}) my ajax code is: $.ajax({ type:'POST', url:'./', data:{ async: false, nickname:usr_nickname, email:usr_email, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function () { alert('New profile saved!') //window.location.reload() }, error:function (XMLHttpRequest, textStatus, errorThrown) { alert('Error! Please check your entry and try again!') } }) I'll be very appreciated if you can help … -
django deposit() missing 1 required positional argument: 'amount'
I am unable to access the deposit() method within the Account class from the views. Gives me the error: "deposit() missing 1 required positional argument: 'amount'" I am calling the method with: Account.deposit(amount) Views: def home(request): return render(request, 'automatedbankteller/home.html') def about(request): return render(request, 'automatedbankteller/about.html') @login_required def transactions(request): context = { 'transactions': Transaction.objects.filter(sender=request.user) } return render(request, 'automatedbankteller/transactions.html', context) @login_required def my_accounts(request): context = { 'accounts': Account.objects.filter(account_owner=request.user) } return render(request, 'automatedbankteller/my_accounts.html', context) @login_required def deposit(request): if request.method == 'POST': form = UserDepositForm(request.POST) if form.is_valid(): amount = request.POST['amount'] print(amount) Account.deposit(amount) #form.save() messages.success(request, f'The amount has been deposited into your account!') return redirect('ABT-my_accounts') else: form = UserDepositForm(instance=request.user) return render(request, 'automatedbankteller/deposit.html', {'form': form}) Models: class Account(models.Model): ACCOUNT_TYPES = ( ('SA', 'Savings'), ('CA', 'Checking'), ) accountID = models.IntegerField() account_amount = models.DecimalField(max_digits=20, decimal_places=2) account_type = models.CharField(max_length=2, choices=ACCOUNT_TYPES) account_owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.accountID) def get_balance(self): return self.account_amount def deposit(self, amount): self.account_amount = self.account_amount + amount return def withdraw(self, amount): self.account_amount = self.account_amount - amount return Urls: urlpatterns = [ path('', views.home, name='ABT-home'), path('about/', views.about, name='ABT-about'), path('my_accounts/', views.my_accounts, name='ABT-my_accounts'), path('account_history/', views.transactions, name='ABT-transactions'), path('deposit/', views.deposit, name='ABT-deposit'), ] Forms: class UserDepositForm(forms.ModelForm): amount = forms.DecimalField(max_digits=20, decimal_places=2) class Meta: model = Account fields = ['account_type', 'amount'] -
Django installation on Mac
I'm trying to install Django on Mac, python 3.7 already installed , here is the comment I have put in terminal- Django-admin startproject hello - command not found -
Django: Unable to configure handler 'console'
I have a simple logging definition in the settings.py file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '[%(asctime)s] %(levelname)s %(message)s', }, 'verbose': { 'format': '[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s', }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatters': 'simple', 'propagate': False } }, 'loggers': { 'myapp': { 'handlers': ['console'], 'level': 'DEBUG' }, } } When I run my program, I get the error: ValueError: Unable to configure handler 'console' What is going wrong? -
Genetic algorithm for timetable generation with Django
Steps needed to develop a web application / Python Django to solve the timetable generator with Genetic Algorithm? Please help me identify gene, chromosome, population, mutation etc. -
not able to send file from form to view
When i try to send data from form to view, All data is sent successfully except FileField Data.i am using CURD datatable screenshot of the template is also pasted below. I am also use ajax. I am beginner in Django please help i am not able to find error. screenshot view.py def list(request): certificatedata = certificateDb.objects.all() context = { 'certificatedata': certificatedata } return render(request, 'list.html',context) def save_all(request,form,template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True certificatedata = certificateDb.objects.all() data['list'] = render_to_string('list_2.html',{'certificatedata':certificatedata}) else: data['form_is_valid'] = False context = { 'form':form } data['html_form'] = render_to_string(template_name,context,request=request) return JsonResponse(data) def certificate_create(request): if request.method == 'POST': form = CertificateForm(request.POST, request.FILES ) print('request.FILES',request.FILES) else: form = CertificateForm() return save_all(request,form,'certificate_create.html') form.py from django import forms from SharedApps_Application.models import serviceDb from django.contrib.admin.widgets import AdminDateWidget from django.forms.fields import DateField class CertificateForm(forms.ModelForm): startdate = forms.DateField(widget = forms.SelectDateWidget(years=range(1995, 2100))) expiredate = forms.DateField(widget = forms.SelectDateWidget(years=range(1995, 2100))) class Meta: model = certificateDb fields = ('application', 'startdate', 'expiredate', 'environment_type','file' ) urls.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url urlpatterns=[ url(r'^list/$', views.list, name='list'), url(r'^list/create$', views.certificate_create, name='certificate_create'), url(r'^list/(?P<id>\d+)/update$', views.certificate_update, name='certificate_update'), url(r'^list/(?P<id>\d+)/delete$', views.certificate_delete, name='certificate_delete'), ] if settings.DEBUG: urlpatterns += … -
How to add child instance foreign key IDs as a serializer list field idiomatically?
I've got a many-to-many model like Request ← RequestItem → Item, and I want the response from the Request API endpoint to include a list of Item IDs. I've got a working serializer method like this: def to_representation(self, instance: Request) -> typing.Dict[str, Any]: representation: Dict = super().to_representation(instance) representation["items"] = [ item_id for item_id in instance.requestitems_set.values_list("item_id", flat=True) ] return representation As you can see, this is horrible. What would be an idiomatic way of getting the exact same output? -
Django how to custom inline error messages
I am trying to show a inline error messages when user update "location" field with same value to others people. But I have no idea how to custom it. Thanks! Here is my code: class LocationUpdateView(generic.UpdateView): ... def form_valid(self, form): form.instance.location = form.instance.cylinder.upper() condition = { 'location': form.instance.location, } item = Address.objects.filter(**condition) if item.count() > 0: # should I custom error message here? return super().form_invalid(form) return super().form_valid(form) -
Making the file_names unique with timestamp
Intro: I have a small piece of code that takes any image that is being added and makes it smaller and saves it. I am using a external library called Filepond for this. The Issue: If 2 users add same names to their images(different images). The second users image replaces the 1st users image and both users see the same image. What I want: Add unique image names. My tries are below. I need the best solution for this so the names are not too big but are unique Present Code: fields.py: class FilePondField(forms.FileField): widget = forms.TextInput(attrs={'class': 'fileid'}) def __init__(self, name, *args, **kwargs): super(FilePondField, self).__init__(*args, **kwargs) self.name = name def prepare_value(self, data): if not data: return None if isinstance(data, str): try: # It would have been nice to just use get_or_create but the requirement on the file field # will make it fail tu = TU.objects.get(upload_id=data) except TU.DoesNotExist: return None return tu.upload_id name = data.name base = os.path.basename(name) file_id = "%s_%s" % (self.name, data.instance.pk) try: # It would have been nice to just use get_or_create but the requirement on the file field # will make it fail tu = TU.objects.get(file_id=file_id) except TU.DoesNotExist: upload_id = uuid() tu = TU(upload_id=upload_id, file_id=file_id, # … -
Unable to install node in Heroku
I am trying to deploy a Django Application on Heroku with the node and npm installations, however, while deploying the application I get the following error on the Heroku console: npm ERR! node v11.13.0 npm ERR! npm v2.15.12 npm ERR! path /tmp/build_number/node_modules/.bin/grunt npm ERR! code ENOENT npm ERR! errno -2 npm ERR! syscall unlink npm ERR! enoent ENOENT: no such file or directory, unlink '/tmp/build_number/node_modules/.bin/grunt' npm ERR! enoent This is most likely not a problem with npm itself npm ERR! enoent and is related to npm not being able to find a file. npm ERR! enoent npm ERR! Please include the following file with any support request: npm ERR! /tmp/build_number/npm-debug.log -----> Build failed I am trying to build charts using Vue.js components that uses buildpacks. I would like to know how to install the npm on Heroku. Any help will be greatly appreciated. I have the following configuration for the website: Django version: 2.1.7 Node Version: 11.3.0 Python Version: 3.7.3 My package.json file looks as follows: { "name": "django", "private": true, "scripts": { "start": "node app", "poststart": "npm prune --production", "pretest": "eslint django/ js_tests/admin/ js_tests/gis/", "test": "grunt test --verbose" }, "engines": { "node": "11.13.0", "npm": ">=1.3.0 <3.0.0", "build": "bower install … -
Django Rest Framework : { "detail": "Not found." } using legacy database
rest-framework to build an api, when i send http://localhost:8888/api/v1/IxtUser/abcd@email.com using postman i get { "detail": "Not found." } abcd@email.com is primary key and im using legacy database. **ive already tried change 'user_id' to models.Emailfield() ,but i still got same error the odds In another endpoint i tried to send http://localhost:8888/api/v1/MCustomerData/celc/ and works like this { "cust_id": "celc", "cust_name": "Celcom", "cust_country": "Malaysia", "cu": "ECM" } my code models: class IxtUser(models.Model): user_id = models.CharField(max_length=70, primary_key=True, unique=True) user_uuid = models.CharField(max_length=50) user_passwd = models.CharField(max_length=50) user_fname = models.CharField(max_length=50) user_lname = models.CharField(max_length=50) user_contact = models.CharField(max_length=15) user_cu_id = models.CharField(max_length=30) user_cust_id = models.CharField(max_length=30) user_asp_id = models.CharField(max_length=30) user_join_date = models.DateTimeField(blank=True, null=True) user_status = models.SmallIntegerField() user_parent = models.SmallIntegerField() user_monitor = models.SmallIntegerField() role2monitor = models.SmallIntegerField(blank=True, null=True) pb_lower_counter = models.CharField(max_length=8) is_rootpanel_enable = models.SmallIntegerField() def __str__(self): return self.user_id class Meta: managed = False db_table = 'ixt_user' views: class IxtUserFilter(filters.FilterSet): class Meta: model = IxtUser fields = [ 'user_id', 'user_uuid', 'user_fname', 'user_lname', 'user_cu_id', 'user_cust_id', 'user_asp_id' ] class IxtUserView(viewsets.ModelViewSet): queryset = IxtUser.objects.all() serializer_class = IxtUserSerializer lookup_field = 'user_id' filter_backends = (filters.DjangoFilterBackend,) filterset_class = IxtUserFilter throttle_classes = (UserRateThrottle,) def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) urls: from rest_framework import routers ... from user.views import IxtUserView router = routers.DefaultRouter() router.register(r'api/v1/IxtUser', … -
When do inherited django models not set abstract = False by default?
I've read https://docs.djangoproject.com/en/2.2/topics/db/models/#meta-inheritance and see that Django does make one adjustment to the Meta class of an abstract base class: before installing the Meta attribute, it sets abstract=False. This means that children of abstract base classes don’t automatically become abstract classes themselves. Of course, you can make an abstract base class that inherits from another abstract base class. You just need to remember to explicitly set abstract=True each time. I'm running Django 2.2 and am finding that models inherited from abstract models are not defaulting abstract to False unless implicitly set. Sample code is attached. class Foo(models.Model): class Meta: app_label = 'foo' abstract = True class Bar(Foo): name = models.CharField(max_length=128) code = models.CharField(max_length=32, unique=True) url = models.URLField(max_length=256) Running makemigrations returns No changes detected. Adding class Meta: abstract = False to Bar and running makemigrations works. Known problem with 2.2 or user error? Thanks. -
Paginator with ListView- django
Views class ThreadListView(ListView): model = Thread template_name = 'forums/thread.html' paginate_by = 2 def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet of the Thread & Replies context['thread'] = Thread.objects.get(pk=self.kwargs['pk']) context['reply'] = Thread.objects.get(pk=self.kwargs['pk']).replies.all() HTML {% extends 'forums/base.html' %} {% block title %} Forum - {{ thread.title }} {% endblock title %} {% block content %} <!--Thread real--> <table class="table table-hover"> <thead> <tr class="table-primary"> <th class="col-2"><a href="{% url 'threadview' thread.id %}"> {{ thread.title }}</a></th> <th scope="col-10" id="content-col"></th> </tr> </thead> <tbody> <!--Thread Author and Content--> <tr class="table-info"> <td class="border-right text-center"> <span> <img class="rounded-circle" style="height: 100px;width: 100px;" src="{{ thread.author.profile.image.url }}"> <br /> Username:&emsp;<a href="#">{{ thread.author.username|capfirst }}</a> <br /> Ranks:&emsp; <!--Ranks Go Here--> <br /> <hr> Posts:&emsp; <!--Posts Go Here--> <br /> Badges:&emsp; <!--Badges Go Here--> <br /> <hr> Date Joined:&emsp;{{thread.author.date_joined| date:'Y-m-d'}} <br /> </span> </td> <td>{{ thread.content }}</td> </tr> <!--Reply Author and Content--> {% for rply in reply %} <tr class="table-secondary"> <td class="border-right text-center"> <span> <img class="rounded-circle" style="height: 100px;width: 100px;" src="{{ rply.author.profile.image.url }}"> <br /> Username:&emsp;<a href="#">{{ rply.author.username|capfirst }}</a> <br /> Ranks:&emsp; <!--Ranks Go Here--> <br /> <hr> Posts:&emsp; <!--Posts Go Here--> <br /> Badges:&emsp; <!--Badges Go Here--> <br /> <hr> Date … -
History in Proxy Django Model Django Admin
I'm currently using django admin but upon changing data in my proxy model when I switch to my parent model the history when the change of data did not appear. Any work around for this or any django libraries for this problem. Thanks in advance -
make a certain attribute be seen in the site
I am using the django-audiofield and successfully install it. I can now upload audio file in the admin site but what I want to do is that I wanna put the audio that I have uploaded in the admin be seen in the template -
Django/Python , How to bulk insert or create multiple data
Based on the given data object i have put below. I wanted to ask how to bulk insert in django or create multiple data. I have provided below including my serializer and python code. I wanted to create/insert every password from the data object which is in below. Dont worry about the other data. Also i want to do it with serializer. I did try to loop through data which is for each_employee_data in data: . Any problem with my code. Thank you. code def post(self, request, format=None): data = request.data print("Data::" , data) for each_employee_data in data: each_employee_data["verification_code"] = verification_code(self) password = hashers.make_password(each_employee_data["password"]) each_employee_data["password"] = password print("each_employee_data", each_employee_data) user_serializer = UserSerializer(data= each_employee_data) if user_serializer.is_valid(raise_exception=True): if not each_employee_data["is_applicant"]:#company company_serializer = CompanySerializer(data=data) if company_serializer.is_valid(raise_exception=True): user_ins = user_serializer.save(password=password) company_serializer.save(user=user_ins) else: applicant_serializer = ApplicantSerializer(data=each_employee_data) if applicant_serializer.is_valid(raise_exception=True): user_ins = user_serializer.save(password=password) applicant_serializer.save(user=user_ins) send_confirmation.delay(data) if not user_ins.is_applicant: send_business_confirmation.delay(data) Serializer class UserSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) is_staff = serializers.BooleanField(required=False) is_confirmed = serializers.BooleanField(required=False) is_applicant = serializers.BooleanField(required=False) email = serializers.EmailField(required=True,validators=[UniqueValidator(queryset=User.objects.all(), message="Email already exist.")]) verification_code = serializers.CharField(required=False) password_reset_code = serializers.CharField(required=False) def create(self, validated_data): """ Create and return a new `Snippet` instance, given the validated data. """ password = validated_data.pop("password") Data: [ { 'mname':'Tap', 'email':'helloworld@gmail.com', 'is_applicant':True, 'lname':'world', 'fname':'hello', 'password':'helloworld12345' }, { 'mname':'van', … -
Django Inlineformset_factory. I add more than one data to form. Only the latest data is saving
In my Problem I use inlineformset_factory for using 2 relational model on 1 form. In my ciranta model; class Ciranta(models.Model) cek=models.ForeignKey(cekler, on_delete=models.CASCADE)... The error is when I run this code, I add more than one ciranta model but the lastest one is saving. . How can I solve this? My form.py; class CekForm(ModelForm): class Meta: model =cekler exclude = () class CirantaForm(ModelForm): class Meta: model = ciranta exclude = () CirantaFormSet = inlineformset_factory(cekler, ciranta, form=CirantaForm, extra=1) My views.py; class CekCreate(CreateView): model = cekler fields = ['borclu', 'borcluAdres', 'borclu_mail', 'borcluTelefon','tutar','kur','banka','cek_tarih'] class CirantaCreate(CreateView): model = cekler fields = ['borclu', 'borcluAdres', 'borclu_mail', 'borcluTelefon','tutar','kur','banka','cek_tarih'] success_url = reverse_lazy('home') def get_context_data(self, **kwargs): data = super(CirantaCreate, self).get_context_data(**kwargs) if self.request.POST: data['cirantalar'] = CirantaFormSet(self.request.POST) else: data['cirantalar'] = CirantaFormSet() return data def form_valid(self, form): context = self.get_context_data() cirantalar = context['cirantalar'] with transaction.atomic(): self.object = form.save() if cirantalar.is_valid(): cirantalar.instance = self.object cirantalar.save() return super(CirantaCreate, self).form_valid(form) And my template; <table class="table"> <br> {{ cirantalar.management_form }} {% for form in cirantalar.forms %} {% if forloop.first %} <thead class="thead-light"> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle row1 row2 %} formset_row"> {% for field in form.visible_fields %} <td> {# Include the … -
href is not sending good link information
My code create a link that is like that:/peoplebook/users/list/%7B%%20url%20'people-users-detail'%20key which create an error don t know what to try differently my code in urls.pyfrom django.urls import path from . import views urlpatterns = [ path('users/', views.users_list), path('users/<str:display>/', views.users_list), path('users/<str:name>/detail/', views.users_detail, name='peoplebook-users-detail'), ] and in my html file {% block content %} <h2> Test Titre</h2> <ul> {% for key, user in users.items %} <li><a href="{% url 'peoplebook-users-detail' key %}">{{ user.name|title }}</a></li> {% endfor %} </ul> {% endblock content %}} should be like url : http.../peoplebook/userrs/han/detail han is users.name -
HTML textarea not posting with Django
I am trying to use textarea in the post form to send a comment back to Django, but my Django form is not receiving anything. HTML <form name='commentForm' method='post'> {% csrf_token %} <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label"> <textarea name="commentt"rows=1 class="mdl-textfield__input" id="comment" form="commentForm"></textarea> <label for="comment" class="mdl-textfield__label">Join the discussion</label> </div> <button type="submit" class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon"> <i class="material-icons" role="presentation">check</i><span class="visuallyhidden">add comment</span> </button> </form> Django forms.py class CommentForm(forms.ModelForm): comment = forms.CharField() class Meta: model = Comment fields = ('comment',) Django views.py class EntryView(TemplateView): template_name = 'post/entry.html' def get(self, request): commentq = Comment.objects.all() form = CommentForm() args = {'commentq' : commentq, 'form' : form } return render(request, self.template_name, args) def post(self, request): form = CommentForm(request.POST["commentt"]) if form.is_valid(): text = form.cleaned_data['comment'] new_comment = Comment(comment_id = 1, comment_text = text, user = 'hedgehog', comment_date = timezone.now()) new_comment.save() form = CommentForm() url = '/post/entry' return HttpResponseRedirect(url) args = {'form' : form } return render(request, self.template_name, args) -
Django - form_valid() variable undefined
I need to get the profile_id of the user who is trying to create a Review to store in the model. I can get the attributes for the User as they are built into django but when I try to use what's below to get profile_id I get "prof is not defined" error. views.py class ReviewCreateView(LoginRequiredMixin, CreateView): model = Review fields = ['rating', 'reviewtext'] def get_context_data(self, **kwargs): context = super(ReviewCreateView, self).get_context_data(**kwargs) context['prof'] = Profile.objects.values_list('id', flat=True).filter(user_id=self.request.user.id) return context def form_valid(self, form): form.instance.product = self.request.GET.get('pk') form.instance.author = self.request.user form.instance.profile = prof return super().form_valid(form) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) class Review(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.PositiveSmallIntegerField(default=1, validators = [MinValueValidator(1), MaxValueValidator(5)]) reviewtext = models.TextField() class Product(models.Model): name = models.CharField(max_length=100) -
How to fix " There is no current event loop in thread 'Thread-2' erro in django view
I use "insync" api on the Django rest framework But I get this error at runtime "There is no current event loop in thread 'Thread-2'" When I use from this code in the python file directly not a problem But when using in Django framework have this error Please anybody know about this error please help me about this problem Python 3.7 Django 2.2 djangorestframework 3.9.2 ib-insync 0.9.46 ibapi 9.73.7 from ib_insync import * .... def Sendorder(request, format=None): ..... ib = IB() ib.connect(host='127.0.0.1', port=7498, clientId=100, timeout=10) contract = ib.Stock(symbol, 'SMART', 'USD') ib.qualifyContracts(contract) ..... File "C:\newsystem\env\lib\site-packages\ib_insync\util.py", line 228, in loop = asyncio.get_event_loop() File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\Li ncio\events.py", line 644, in get_event_loop % threading.current_thread().name) RuntimeError: There is no current event loop in thread 'Thread-2'.