Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where is gunicorn config file likely to be located in a redhat server?
And no this is not a duplicate of Where is the Gunicorn config file?. While the title is, none of the answers answer the question of where this file is located in the file system or how to find it. I'm having difficulty getting a fully working and functional django site deployed. -
How to use dates in Django model?
When using DateField, I keep getting this error after running migrate: django.db.utils.ProgrammingError: cannot cast type date to time without time zone LINE 1: ...TER COLUMN "create_time" TYPE time USING "create_time"::time I tried to use create_time = models.DateField(auto_now_add=True) I've also tried create_time = models.DateField(default=datetime.date.today()) And get the same error. Some answers I've read suggest editing my postgres database. However I did not get this error before - I originally had auto_now=True instead of auto_now_add=True. This error only came up after I changed that. I tried to change it back to auto_now=True, and I still get this error upon running migrate. I also removed the DateField entirely from my model, and when running migrate I STILL get the error. Is it possible I need to reset something, so that I'm migrating the most updated model? Thanks for any tips. -
Trying to understand Model relationships in Django
I am fairly new to Django and am working on a project that will do the following: Employee will fill out form to create a ticket That ticket will be assigned to the employee and other team members The ticket is associated with a specific person or persons within the organization (I'll call them customers) Once the ticket is complete, we will run reports to show how many tickets a specific person with the organization has created tickets as well as other stats related to the tickets themselves My multi-part question is as follows: What is the best way for me structure my Django models in this scenario? Should I have one app created for employees, one app created for the customer database and one app created for the tickets themselves? Which then is the master ID holder? Is it the employee or the customer? Is there a boilerplate template for a system like this already created that I should be utilizing? Thanks for your time! -
Django looking for index.html after deploying to server
I have just deployed new code to server after upgrading all the relevant packages on the server to match what I have on my development server. I know that the models.py file has changed and that the migration files won't match, but I can trash the current database as it's not needed and doesn't need to be archived on this occasion. Server was running previous website fine, so I am hoping that Gunicorn and Nginx configs should hopefully not be part of this issue (I'm mentioning this explicitly in case it is). So now my site which ran fine on my laptop with django's dev server has now been deployed to the server using git pull, which worked fine, the code on the server is now what matches the master branch. I'm running a virtual environment (virtualenv) which has python 3.6 on it, but for an unknown reason there is python 2.7 on there as well which I am not aware of installing on the environment (I have never programmed in python2.7 so never install it, though I know it is part of the OS so expect it there, just not in the virtual env. but now when I click … -
How to redirect a user based on his choice in drop down?
I've made a form that has a gander Dropdown with two options, how can I redirect a user based on his option if he choices (1) and submit the form will redirect him to a URL and if his choices (2) will redirect him to a different URL. i want to solve it in views or form not in template. forms.py class UserForm(forms.ModelForm): class Meta: model = User fields = ('first_name', 'second_name', 'E_mail', 'country', 'phone', 'phone_code','birthday', 'Gander',) widgets = { 'first_name': forms.TextInput(attrs={'placeholder': 'الاسم الاول'}), 'second_name': forms.TextInput(attrs={'placeholder': 'الاسم الثاني'}), 'E_mail': forms.EmailInput(attrs={'placeholder': 'joe@schmoe.com'}), } views.py def form_page(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): form.save() return redirect('LandingPage:thank_you') else: form = UserForm() posts = Article.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'LandingPage/form_page.html', {'form': form, 'posts': posts,}) -
Django on heroku not showing images on the website that are in media folder after second git push
the website shows all the images that i upload after my first push of creating a app on heroku but when i make any change to the django app and guit push it then the images that were uploaded by user are not showing up on the app but it is still showing the images that i have already saved in my static folder import django_heroku import os Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) this my settings.py # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account.apps.AccountConfig', 'users.apps.UsersConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'XIIILegion.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'XIIILegion.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ … -
Django markdown show_preview feature throws an error
I am new using markdown. I tried to use the show_preview = False to implement preview using jQuery instead. class PostForm(forms.ModelForm): content = forms.CharField(widget=PagedownWidget(show_preview=False)) publish = forms.DateField(widget = forms.SelectDateWidget) class Meta: model = Post fields = [ "title", "content", "image", "draft", "publish", ] unfortunately, it throws an error: line 9, in PostForm content = forms.CharField(widget=PagedownWidget(show_preview=False)) TypeError: __init__() got an unexpected keyword argument 'show_preview' I did look into the markdown files and could not find show_preview using except here: 4 <textarea {{ attrs|safe }}>{{ body }}</textarea> 5 </div> 6 {% if show_preview %} 7 <p class="wmd-preview-title"> 8 <small>HTML Preview:</small> I am running: Django==2.2.6 django-markdown-deux==1.0.5 django-pagedown==2.0.3 -
the JSON object must be str, bytes or bytearray, not 'generator'
I have made a program of scraping data from two url : { "url" : "https://forecast.weather.gov/MapClick.php?lat=37.7772&lon=-122.4168#.XaA9cEZKiUk" , "svgurl":"https://www.amcharts.com/wp-content/themes/amcharts4/css/img/icons/weather/animated/cloudy.svg" } the first one just information text and the seconde one to store the svg data so i want to execute two function in the same time without using thread using instead asyncio My Goal is to transform synchronous python code to Asynchronous code this is what i have made for that : from django.shortcuts import render import requests import json from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from django.http import JsonResponse from django.core.serializers import serialize import urllib.parse as urlparse import base64 from cairosvg import svg2png from rest_framework.decorators import api_view requests.packages.urllib3.disable_warnings() # Create your views here. from bs4 import BeautifulSoup import asyncio @api_view(["POST"]) def Post(request): global srcsnapcodeimg,soup,tonight,sourcesvg body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) url = body['url'] urlsvg=body['svgurl'] source = requests.get(url).text sourcesvg=requests.get(urlsvg).text soup = BeautifulSoup(source, "html.parser") seven_day = soup.find(id="seven-day-forecast") forecast_items = seven_day.find_all(class_="tombstone-container") tonight = forecast_items[0] loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) tasks = [ asyncio.ensure_future(Getvalues()), asyncio.ensure_future(Get_bin_img())] loop.run_until_complete(asyncio.wait(tasks)) print(Get_bin_img()) Getvalues_dict = json.loads(asyncio.wait(Getvalues())) data={"period":Getvalues_dict['period'] ,"short_desc":Getvalues_dict['short_desc'],"temp":Getvalues_dict['temp']} #print(data) return JsonResponse(data) @asyncio.coroutine def Getvalues(): period = tonight.find(class_="period-name").get_text() short_desc = tonight.find(class_="short-desc").get_text() temp = tonight.find(class_="temp").get_text() datanameboxandprice={"period":period,"short_desc":short_desc,"temp":temp} return json.dumps(datanameboxandprice) @asyncio.coroutine def Get_bin_img(): svg2png(bytestring=sourcesvg,write_to='output.png') with … -
JavaScript - How to print http response on stdout?
Django backend setting has # CORS Settings CORS_ORIGIN_ALLOW_ALL = True mocha is running acceptance tests for Django backend, where one of the test case is: describe('Cross Origin Requests', function(){ var result; before(function() { result = request('OPTIONS', url) .set('Origin', 'http://someplace.com') .end(); }); it('should return the correct CORS headers', function(){ return assert(result, "header").to.contain.all.keys([ 'access-control-allow-origin', 'access-control-allow-methods', 'access-control-allow-headers' ]); }); it('should allow all origins', function(){ return assert(result, "header.access-control-allow-origin").to.equal('*'); }); }); function assert(result, prop){ return expect(result).to.eventually.have.deep.property(prop) } Test case should allow all origins fails with below error: should allow all origins: AssertionError: expected { Object (_events, _eventsCount, ...) } to have deep property 'header.access-control-allow-origin' at /home/mohet01-ubuntu/git/CDelivery/todobackend-specs/node_modules/chai-as-promised/lib/chai-as-promised.js:302:22 at tryCatcher (node_modules/bluebird/js/release/util.js:16:23) at Promise._settlePromiseFromHandler (node_modules/bluebird/js/release/promise.js:547:31) at Promise._settlePromise (node_modules/bluebird/js/release/promise.js:604:18) at Promise._settlePromise0 (node_modules/bluebird/js/release/promise.js:649:10) at Promise._settlePromises (node_modules/bluebird/js/release/promise.js:729:18) at _drainQueueStep (node_modules/bluebird/js/release/async.js:93:12) at _drainQueue (node_modules/bluebird/js/release/async.js:86:9) at Async._drainQueues (node_modules/bluebird/js/release/async.js:102:5) at Immediate.Async.drainQueues [as _onImmediate] (node_modules/bluebird/js/release/async.js:15:14) at processImmediate (internal/timers.js:439:21) http://someplace.com is a dummy origin header value 1) How to print result on stdout? to verify the error... 2) Why expect(result).to.eventually.have.deep.property(prop) fails? for this test case should allow all origins -
Django redirect if User has created object
in my model the USER will create the object startup_name, however, i want to carry out a check when user click the button again that of he has created the object so he will be redirected to another page. class Startup ( models.Model ) : author = models.OneToOneField ( User , on_delete = models.CASCADE ) startup_name = models.CharField ( 'Startup Name' , max_length = 32 , null = False , blank = False ) class startupform(forms.ModelForm): class Meta: model = Startup fields = ('startup_name',) widgets = { 'startup_name': forms.TextInput(attrs = {'class':'form-control'}), } def clean(self): super ( ).clean ( ) startup_name = self.cleaned_data.get ( 'startup_name' ) startup_qs = Startup.objects.filter ( startup_name = startup_name ) if startup_qs.exists ( ): raise forms.ValidationError ( 'This Startup Already Exist!' ) @login_required def create_startupform(request) : if request.method == 'POST' : form = startupform ( request.POST ) if form.is_valid ( ) : result = form.save ( commit = False ) result.author = request.user result.save ( ) return redirect ( 'test', startup_id = result.pk) else : form = startupform ( ) return render ( request , 'str_name.html' , { 'form' : form } ) -
Graphene-Django and many to many relationship lookup
I have two Django models - Teacher and Student and have a many-to-many relationship. Teachers can have multiple students and students can have multiple teachers. There is 'through' model called 'Remarks' where a teacher can mark a student as favourite. I am new to GraphQL. I am trying to implement two queries: 1. Teachers and all of their students 2. Teachers and their favourite students I am having difficulty in implementing the second query and have been unable to do so. models.py SUBJECTS = ( ("Maths", "Maths"), ("Chemistry", "Chemistry"), ("Physics", "Physics") ) class Student(models.Model): name = models.CharField(max_length=100) age = models.IntegerField(default=0) def __str__(self): return self.name class Teacher(models.Model): name = models.CharField(max_length=100) subject = models.CharField(max_length=100, choices=SUBJECTS) students = models.ManyToManyField(Student, through="Remarks") def __str__(self): return self.name class Remarks(models.Model): student = models.ForeignKey(Student, related_name="student", on_delete=models.DO_NOTHING) teacher = models.ForeignKey(Teacher, related_name="teacher", on_delete=models.DO_NOTHING) favorite = models.BooleanField(default=False, choices=( (True, "Yes"), (False, "No") )) schema.py import graphene from graphene import relay, ObjectType from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from .models import Teacher, Student, Remarks class RemarkNode(DjangoObjectType): class Meta: model = Remarks filter_fields = ['favorite'] interfaces = (relay.Node, ) class TeacherNode(DjangoObjectType): favorite = graphene.Field(RemarkNode) class Meta: model = Teacher filter_fields = ['name', 'subject'] interfaces = (relay.Node, ) class StudentNode(DjangoObjectType): class Meta: … -
Django unittest assertRedirects explanation of work
I need explanation of work assertRedirects function. My view: def login_view(request): if request.user.is_authenticated: return redirect('account:profile') else: form = UserLoginForm(request.POST or None) if request.method == 'POST': if form.is_valid(): cd = form.cleaned_data user = authenticate(username=cd['username'], password=cd['password']) if user is None: messages.error(request, 'something.') else: if user.is_active: login(request, user) next_url = request.POST.get('next', reverse('account:profile')) return HttpResponseRedirect(next_url) else: messages.error(request, 'something') else: messages.error(request, 'something.') context = {'form': form, 'next': request.GET.get('next')} return render(request, 'account/login.html', context) Now I wrote 2 tests. def test_login_view_valid_data_username(self): path = reverse('account:login') response = self.client.post(path=path, data={'username': 'test123', 'password': 'everything123'}) # is logged self.assertTrue(self.user.is_authenticated) # is redirect and good redirected self.assertRedirects(response, reverse('account:profile')) My view pass this test. My second test: def test_redirect_url_if_not_login(self): path = '{}?next={}'.format(reverse('account:login'), reverse('orders:create')) response = self.client.post(path=path, data={'username': 'test123', 'password': 'everything123', 'next': reverse('orders:create')}) print('RESPONSE CODE', response.status_code) print('RESPONSE URL', response.url) self.assertRedirects(response, reverse('orders:create')) And here I have problem. I get error: AssertionError: 302 != 200 : Couldn't retrieve redirection page '/orders/create/': response code was 302 (expected 200) but my response code and response url is correct to reverse path. I'm little bit confusion, because is not the first case like this. Is there any formal explanation of this? Thanks for any answer Magnus -
Date type field in Django template
I have custom form in template file. [form] input type="date" value={{info.from_date|date:'Y-m-d'}} [/form] Here info.from_date is context data. In this case in FORM on page, date is always showing in format 'dd-mm-yyyy' But i want in 'mm-dd-yyyy'. So how to change this format. Please any body share any idea ! -
Issue with UTC Datetime conversion
I am gathering appointment times from clients in a Django application and creating a combined date using datetime. I pass the timezone name through a hidden field on the form and convert my naive time to the client's correct timezone so I can then convert it to UTC (which is what my DB uses). However, something is going wrong, extra time is randomly added to the final time, and it seems the actual days are getting messed up as well. What am I doing incorrect? combined_time = datetime.combine( make_aware(datetime.strptime(str(dict_to_update['appointment_date']), '%Y-%m-%d')), # set time to utc so timezone conversion still works make_aware(datetime.strptime(str(dict_to_update['appointment_time']), '%H:%M')).time(), tzinfo=timezone(request.POST.get('tz')), ) print(1, combined_time.tzinfo) # 1 America/New_York print(2, combined_time) # 2 2019-10-21 09:00:00-04:56 --correct time selected print(3, combined_time.utcnow()) # 3 2019-10-11 13:44:47.393057 -
How to merge queryset into a single result without any repetation?
I have the following queries: group_debit_positive = GroupBase.objects.filter(base_group__group_ledger__company=company,is_debit__exact='Yes',base_group__group_ledger__closing_balance__gt=0).annotate( total_debit_positive=Coalesce(Sum('base_group__group_ledger__closing_balance'), Value(0)), total_debit_negative=Sum(0,output_field=FloatField()), total_credit_positive=Sum(0,output_field=FloatField()), total_credit_negative=Sum(0,output_field=FloatField())) group_debit_negative = GroupBase.objects.filter(base_group__group_ledger__company=company,is_debit__exact='Yes',base_group__group_ledger__closing_balance__lt=0).annotate( total_debit_positive=Sum(0,output_field=FloatField()), total_debit_negative=Coalesce(Sum('base_group__group_ledger__closing_balance'), Value(0)), total_credit_positive=Sum(0,output_field=FloatField()), total_credit_negative=Sum(0,output_field=FloatField())) group_credit_positive = GroupBase.objects.filter(base_group__group_ledger__company=company,is_debit__exact='No',base_group__group_ledger__closing_balance__gt=0).annotate( total_debit_positive=Sum(0,output_field=FloatField()), total_debit_negative=Sum(0,output_field=FloatField()), total_credit_positive=Coalesce(Sum('base_group__group_ledger__closing_balance'), Value(0)), total_credit_negative=Sum(0,output_field=FloatField())) group_credit_negative = GroupBase.objects.filter(base_group__group_ledger__company=company,is_debit__exact='No',base_group__group_ledger__closing_balance__lt=0).annotate( total_debit_positive=Sum(0,output_field=FloatField()), total_debit_negative=Sum(0,output_field=FloatField()), total_credit_positive=Sum(0,output_field=FloatField()), total_credit_negative=Coalesce(Sum('base_group__group_ledger__closing_balance'), Value(0))) I have performed union of all the queries: final_set = group_debit_positive.union(group_debit_negative,group_credit_positive,group_credit_negative) I want to get a single result rather then getting repetation in my union queryset. For example: whenever I am trying to print the resulted queryset for g in final_set: print(g.name,'-',g.total_credit_positive,'-',g.total_credit_negative) I am getting results like this: Sundry Creditors - 0.0 - -213075 Purchase Accounts - 0.0 - 0.0 Sundry Creditors - 95751.72 - 0. Sales Accounts - 844100.0 - 0.0 Sales Accounts - 0.0 - -14000.0 As you can see Sales Account is repeated twice. I want something like the following: Sundry Creditors - 0.0 - -213075 Purchase Accounts - 0.0 - 0.0 Sundry Creditors - 95751.72 - 0. Sales Accounts - 844100.0 - -14000.0 How to stop the repetition of results and make it into a single result. Any idea anyone how to perform this? Thank you -
How to implement create and update in one API view.?
I have a model called CarDetailsAdd and VehicleDetails (field - description), VehicleDetails is a Foreignkey to CarDetailsAdd. I am using Nested Relationship in this serializer. Using this update function, I can update existing vehicle details. Add and update runs on the same screen, depending on the UI. If the user has updated the field, it should be updated or user has added a new field, it should be added. How do I do that if the user updates and adds at the same time.? # Serializer class CarDetailsSerializer(serializers.ModelSerializer): vehicle_details = VehicleDetailsSerializer(many=True) class Meta: model = CarDetailsAdd fields = ( 'id', 'name', 'year', 'color', 'fuel_type', 'vehicle_details', ) read_only_fields = ['id'] def update(self, instance, validated_data): vehicle_data = validated_data.pop('vehicle_details') vehicle = (instance.vehicle_details).all() vehicle = list(vehicle) instance.name = validated_data.get('name', instance.name) instance.year = validated_data.get('year', instance.year) instance.color = validated_data.get('color', instance.color) instance.fuel_type = validated_data.get('fuel_type', instance.fuel_type) instance.save() for vehicle_data in vehicle_data: vehicle = vehicle.pop(0) vehicle.description = vehicle_data.get('description', vehicle.description) vehicle.save() return instance # View class CarDetailsView(APIView): permission_classes = [IsAuthenticated] def put(self, request, pk, format=None): try: car = self.get_object(pk) serializer = CarDetailsSerializer(car, data=request.data) if serializer.is_valid(): serializer.save() return Response({'response': 'Update Success', 'result': serializer.data}) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except: return Response({'response': 'Oops! Something Went Wrong'}, status=status.HTTP_400_BAD_REQUEST) -
Bootstrap lines are not working in case of Ubantu 18.4
I used to make django forms by using Bootstrap lines in Windows os but after switching in to Ubantu those bootstrap codes do not affect my code <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> Please help me with this. -
Url looks okay, but doesn't match?
urls.py in objects app: from django.urls import path from . import views urlpatterns = [ path('<str:category>/<int:pk>/', views.show_object, name='show-object'), ] views.py (show_object method): def show_object(request, category, pk): URL which I hit: http://localhost:8000/objects/restaurants/23/ Response: NoReverseMatch at /objects/restaurants/23/ Reverse for 'show-object' with keyword arguments '{'pk': 23}' not found. 1 pattern(s) tried: ['objects/(?P[^/]+)/(?P[0-9]+)/$'] -
Can't work modal form with method POST in Django
Thats my first project in Django. I want to make table and add items with modal form. I use Mysql database. items which addes manually from phpmyadmin already exist on table but when i try add from modal form it cant added. views.py from django.shortcuts import render from django.http import HttpResponse from .models import Client def viewpost(request): post_list = Client.objects.all() context = { 'posts': post_list } return render(request, 'mysite/viewpost.html', context) def add_client(request):if request.method == 'POST': post = Client() post.name = request.POST.get('name') post.surname = request.POST.get('surname') post.address = request.POST.get('address') post.gender = request.POST.get('gender') post.age = request.POST.get('age') post.save() return render(request, 'mysite/viewpost.html') else: return render(request, 'mysite/viewpost.html') url.py: from django.urls import path from . import views urlpatterns = { path('', views.CiscoManager, name='CiscoManager'), path('test/', views.test, name='test'), path('viewpost/', views.viewpost, name='viewpost'), path('viewpost/#add_data_Modal', views.add_client, name='add_client'), } -
Using admin.RelatedOnlyFieldListFilter with content_type/generic relation
I have a model with a generic relation so includes these fields: content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") In my admin for this model I would like to use this: list_filter = ( ("content_type", admin.RelatedOnlyFieldListFilter), ... ) But this doesn't work... I get this exception: django.contrib.admin.utils.NotRelationField Is there a way of using a list_filter to show the app_label of the related model? -
How to install a server at home with django&postgre
Please help me to set my home PC as a server (Windows 10 + Python + Django + Postgre SQL + Anaconda) There are several instructions on how to set the server on the Internet, and surprisingly, many instructions differ from each other. I have absolutely no experience in setting a server. Probably, I’m making a stupid mistake somewhere that I can’t identify for 3 days. I am lost. I believe that most useful instructions are these (they are complete and new): https://www.codementor.io/aswinmurugesh/deploying-a-django-application-in-windows-with-apache-and-mod_wsgi-uhl2xq09e https://ostrokach.gitlab.io/post/apache-django-anaconda/ I followed the instructions and successfully downloaded the necessary modules, installed Wamp, made the changes as displayed in the guide and started it. What I see now: the Wamp icon glows green. When I load a localhost, the page loads endlessly but does not load. Wamp error log shows following: [Fri Oct 11 14:50:33.823752 2019] [core:notice] [pid 1364:tid 808] AH00094: Command line: 'c:\wamp64\bin\apache\apache2.4.39\bin\httpd.exe -d C:/wamp64/bin/apache/apache2.4.39' [Fri Oct 11 14:50:33.840681 2019] [mpm_winnt:notice] [pid 1364:tid 808] AH00418: Parent: Created child process 15052 [Fri Oct 11 14:50:34.981629 2019] [mpm_winnt:notice] [pid 15052:tid 800] AH00354: Child: Starting 64 worker threads. Project name: turiumasina path D:/Users/PycharmProjects/turiumasina/ path to wsgi: D:/Users/PycharmProjects/turiumasina/turiumasina/wsgi_windows.py (I renamed wsgi to wsgi_windows, settings file is in turiumasina/turiumasina/) I copied … -
int() argument must be a string, a bytes-like object or a number, not 'ForwardManyToOneDescriptor'
how to correct this error? int() argument must be a string, a bytes-like object or a number, not 'ForwardManyToOneDescriptor' def enrollmentform(request): id = request.GET.get('StudentID') if StudentsEnrollmentRecord.objects.filter(Student_Users=id).exists(): studentenroll = StudentsEnrollmentRecord.objects.filter(Student_Users=id) FeesType = SchoolFeesMasterList.objects.filter(Education_Levels=StudentsEnrollmentRecord.Education_Levels) #payment = StudentsPaymentSchedule.objects.filter(Students_Enrollment_Records__in=studentenroll)"payment":payment, return render(request, 'Homepage/enrollmentrecords.html',{"studentenroll":studentenroll,"SchoolFeesType":FeesType}) else: id = request.GET.get('StudentID') students = StudentProfile.objects.all().filter(id=id) edulevel = EducationLevel.objects.all().order_by('Sequence') payment = PaymentType.objects.all() year = SchoolYear.objects.all() gradelevel = request.POST.get('gradelevel') subj = Subject.objects.all().filter(Education_Levels=gradelevel) paymentID = request.POST.get('paymentID') sched = ScheduleOfPayment.objects.all().filter(Payment_Type=paymentID).filter(Education_Levels=gradelevel) doc = DocumentRequirement.objects.all() education = EducationLevel.objects.all().filter(id=gradelevel) payments = PaymentType.objects.all().filter(id=paymentID) return render(request, 'Homepage/EnrollmentForm.html', {"students": students, "edulevel": edulevel, "payment": payment, 'sched': sched, 'subj': subj, "year": year, "doc": doc,"education":education,"payments":payments}) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='+', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='paymenttype', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='gradelevel', on_delete=models.CASCADE,null=True) Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE,null=True) Remarks = models.TextField(max_length=500,null=True) def __str__(self): suser = '{0.Student_Users} {0.Education_Levels}' return suser.format(self) class SchoolFeesMasterList(models.Model): Education_Levels= models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,blank=True) Payment_Types = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE,blank=True) Display_Sequence = models.IntegerField(blank=True, null=True) School_Fees_Type= models.ForeignKey(SchoolFeesType, related_name='+', on_delete=models.CASCADE,blank=True) Amount = models.FloatField() Amount_Per_Unit = models.FloatField() Effectivity_Date_From = models.DateField(null=True,blank=True) Effectivity_Date_To = models.DateField(null=True,blank=True) Remark = models.TextField(max_length=500,blank=True) def __str__(self): suser = '{0.Education_Levels} {0.Courses}' return suser.format(self) This error is new to me , … -
Run StaticLiveServerTestCase on local pc and selenium in docker
For development I want to run my tests locally and selenium using selenium hub. hub: image: selenium/hub environment: GRID_BROWSER_TIMEOUT: '300' ports: - "4444:4444" firefox_node_1: image: selenium/node-firefox-debug depends_on: - hub environment: HUB_HOST: hub ports: - "5900:5900" In my test I use: class SimpleTestCase(StaticLiveServerTestCase): def setUp(self): super(SimpleTestCase, self).setUp() self.browser = webdriver.Remote(command_executor=f'http://localhost:4444/wd/hub', desired_capabilities=DesiredCapabilities.FIREFOX) def tearDown(self): self.browser.quit() super(SimpleTestCase, self).tearDown() def test_mainpage(self): self.browser.get(self.live_server_url) But in this case I get an error: selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=connectionFailure&u=http%3A//localhost%3A51325/&c=UTF-8&f=regular&d=Firefox%20can%E2%80%99t%20establish%20a%20connection%20to%20the%20server%20at%20localhost%3A51325. because firefox node do not see localhost I tried to set host to 0.0.0.0 class SimpleTestCase(StaticLiveServerTestCase): host = '0.0.0.0' And of course container do not see my pc, is there a way to do this without dockerize my Django app -
How to add destination and next parameters to the url
I am trying to execute the url with @login_required(login_url="url_address") in django views. Is this proper way to mention destination and next parameters in url. url_address = http://dev-address/user/login?destination=apps/member/change-password&next=http%3A//app.dev-address.abcvso.org/member/change-password/``` -
Celery - Memory Leak (Memory doesn't get free even after worker completed the task)
I have a atomic transaction running on celery server which consumes lot of memory but memory doesn't get free after task is completed. Solution which worked for me is to kill the celery worker after N tasks i.e. to use - CELERYD_MAX_TASKS_PER_CHILD. Is there any other solution to this problem? what should be good number to set for CELERYD_MAX_TASKS_PER_CHILD, If celery receives around 10,000 tasks per day