Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DRF - update profile using serializer + json
I've been bashing my head against the wall on this for about 3 full days now and probably read every thread on SO. Warning = I am not very good with Django REST or indeed Python. To summarise, each user profile has 11 football players they have initially selected. I now want to update/change these players by POSTing json info. views.py elif request.method == 'POST': jsondata = dict(request.data) profile = Profile.objects.get(user=request.user) serializer = ProfileSerializer(profile, data=jsondata, partial=True) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) Serializers.py class ProfileSerializer(serializers.ModelSerializer): """ Serializing all the Players """ #user = serializers.StringRelatedField() GK1 = PlayerSerializer() DF1 = PlayerSerializer() DF2 = PlayerSerializer() DF3 = PlayerSerializer() DF4 = PlayerSerializer() MF1 = PlayerSerializer() MF2 = PlayerSerializer() MF3 = PlayerSerializer() MF4 = PlayerSerializer() FW1 = PlayerSerializer() FW2 = PlayerSerializer() def create(self, validated_data): return Profile.objects.create(**validated_data) class Meta: model = Profile fields = ( "GK1", "DF1", "DF2", "DF3", "DF4", "MF1", "MF2", "MF3", "MF4", "MF5", "FW1", "FW2",) Right now as a test I am trying to update simply GK1. I know that I am getting correct json data via POST. I also know the instance data is the original data. However it just will not save/update!!! I have overridden the update method as a test: … -
Django loop over list from view in html template
I'm asking how I can pick up a for loop in my django class based view to my HTML template. User can check one or multiple checkboxe(s) and I would like to display informations for each checked checkboxes. In my view I have : checkbox_list = self.request.GET.getlist('PUBSDChoice') #Get object id checked by user context_data['checkbox_list'] = checkbox_list for checkbox in checkbox_list: pubsd = Publication.objects.get(id=checkbox) get_request = Download.objects.filter(pub__publication__id=pubsd.id).count() context_data['pubsd'] = pubsd context_data['get_request'] = get_request Now, in my template I have : <table> <tbody> <tr> <th>{% trans 'Publication ID' %}</th> <th>{% trans 'Requests' %}</th> </tr> {% for item in checkbox_list %} # I'm not sure for this loop <tr> <td>{{ pubsd.pub_id }}</td> #Do I have to add item.?? <td>{{ get_request }}</td> </tr> {% endfor %} </tbody> </table> Thank you very much -
Django: How to annotate based on a condition with When/Case?
I have the following models: class Article(BaseModel): """ represents an article fetched """ internal_id = models.IntegerField(unique=True) title = models.CharField(max_length=500) short_title = models.CharField(max_length=500) picture_url = models.URLField(null=True) published_date = models.DateTimeField() update_date = models.DateTimeField(null=True) clip_link = models.URLField() reports = models.ManyToManyField( "Report", through="ArticleInReport", related_name="articles" ) class ArticleInReport(BaseModel): """ represents an article fetched & present in a Report object """ article = models.ForeignKey("core.Article", on_delete=models.CASCADE, related_name='articleinreports') report = models.ForeignKey("core.Report", on_delete=models.CASCADE, related_name='articleinreports') ios_views = models.IntegerField() android_views = models.IntegerField() And I'm trying to do the following in my view (relevant code only): reports_in_time_range = Report.objects.filter(created_date__range=[starting_range, right_now]) last_report = reports_in_time_range.order_by('created_date').last() articles = Article.objects.filter(id__in=unique_articles).distinct('id').annotate( total_views=Case( When(articleinreports__report=last_report, then=F("articleinreports__ios_views") + F("articleinreports__android_views")), default=0, output_field=IntegerField(), )) Basically, I want to annotate all articles with total_views, which should have the following value: 0 if the article does not appear in the latest report through ArticleInReport F("articleinreports__ios_views") + F("articleinreports__android_views") if it does. However, I'm getting mostly 0s for most objects. I've narrowed down the problematic part to this clause: total_views=Case(When(articleinreports__report=last_report,.... This is because when I do this for an article that is 100% in articles: ArticleInReport.objects.get(article=article, report=last_report) I don't get a DoesNotExistError, meaning that the article does have an ArticleInReport associated with it in last_report. I'm assuming this is either a problem with my Case/When clause … -
How can I record a instance's create, edit, destroy in the convenient place?
I have a Machine model: class Machine(models.Model): name = models.CharField(max_length=12) type = models.ForeignKey(to=TypeModel) using = models.BooleanField(default=False) I want to record the Machine instance's create, update, and destroy records. So, I have a MachineRecord model: class MachineRecord(models.Model): editor = models.ForeignKey(to=User) machine = models.ForeignKey(to=Machine) old_content = models.CharField(max_length=1024, null=True, blank=True) new_content = models.CharField(max_length=1024, null=True, blank=True) ctime = models.DateTimeField(auto_now_add=True) But, my problem is there are many place for creating and updating the Machine instance. Whether I can create the MachineRecord instance for Machine instance in a centralized place, such as in the Machine class? I mean, if a instance create, update, destroy anywhere, I just pay attention to the centralized place for recording data. -
leaflet getfeatureinformation not working
I'm trying to create a map in django using leaflet and geoserver. After creating the map I wanted to set up the getfeatureinformation function. After setting it up I had to install a plugin on chrom cors in order for this function to work. But this didn't seem a solution. After reading some stuff I thought that my problem is on django cors headers and followed the instructions of other people I tried everything but it didn't work. I also tried to set up a proxy and modify the httpd.conf file under apache/bin and followed these instructions on this question https://gis.stackexchange.com/questions/89172/how-to-configure-proxy-cgi-in-windows-using-apache-and-geoserver but I think this problem may be not related to my problem since the proxy is set up for openlayers. I see that when I refresh the page jquery-3.3.1.min.js and js_vendor_popper.min.js don't run. Can these be the problem why cors headers are not working, I was trying to import tham at my index.html file but still doesn't work. This is my code: index.html {% extends 'workorders/base.html' %} {% block jumbotron2 %} <div class="jumbotron"> <h1>Navbar example</h1> <p class="lead">This example is a quick exercise to illustrate how the top-aligned navbar works. As you scroll, this navbar remains in its original position … -
Jinja doesn´t render Django view
I´m working on a Django application but jinja doesn´t render the view. I need to separate those templates because I want to include specific content. When I open data.html and data2.html I can see the values "1" respectively "4". But when I open test.html I don´t see the values. And multiple {% extends %} don´t work. How can I load data.html and data2.html into test.html with the rendered data? My views in Django: def data1(request): return render(request, 'user_backend/pages/data.html',{'a':1, "b":2, "c":3}) def data2(request): return render(request, 'user_backend/pages/data2.html',{'d':4, "e":5, "f":6}) def test_temp(request): return render(request,"user_backend/pages/test.html") My templates: test.html {% load staticfiles %} <h1>Data from data.html</h1> {% include "user_backend/pages/data.html" %} {% include "user_backend/pages/data2.html" %} data.html <p>Data = {{a}} </p> data2.html <p>Data2 = {{d}} </p> -
Django Password Reset
I am very new to Django and trying to build an authentication framework for my Django app and its falling over when I try and build the password_reset and password_reset_done apps. I am using Django builtin framework and have not customized to any extent These are my urls url(r'^change-password/$', views.change_password, name='change_password'), url(r'^password_reset/$', auth_views.PasswordResetView.as_view(template_name="registration/password_reset.html"), name='password_reset'), url(r'^password_reset_done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), url(r'^password_reset_confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), url(r'^password_reset_complete/$',auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete"), This is the error message I get NoReverseMatch at /partners/password_reset/ Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. Request Method: POST Request URL: http://127.0.0.1:8000/partners/password_reset/ Django Version: 2.1.1 Exception Type: NoReverseMatch Exception Value: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. Exception Location: C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.1-py3.7.egg\django\urls\resolvers.py in _reverse_with_prefix, line 622 Python Executable: C:\Users\User\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.0 Python Path: ['C:\\Users\\User\\Desktop\\protectandserve', 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32', 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages', 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\django-2.1.1-py3.7.egg', 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\pytz-2018.5-py3.7.egg'] Server time: Thu, 4 Oct 2018 07:49:46 +0000 Error during template rendering In template C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django-2.1.1-py3.7.egg\django\contrib\admin\templates\registration\password_reset_email.html, error at line 6 Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. 1 {% load i18n %}{% autoescape off %} 2 {% blocktrans %}You're receiving this email because you requested a password reset for your user account at {{ … -
How to get current app when user is in Django admin?
I need to get from which admin page(app) current request is from in django admin. Currently request.resolver_match.app_name only returns "admin" which is not what I want. I have noticed that my app name is in 'view_name' and 'url_name' but is it reliable to parse these variables to access current app name? Django 1.11 LTS Thanks -
Django : Get the higher queryset attribute in my template
I'm beginning with Django and I would like to know how I can get attributs from my Django queryset. I have this queryset : get_country = Download.objects.filter(pub__publication__id=pubsd.id).values('country__name').order_by('country__name').annotate(count_country=Count('country__name')) It returns : <QuerySet [{'country__name': 'France', 'count_country': 1}, {'country__name': 'Germany', 'count_country': 2}]> So I would like to display in my template the country name with the higher count_country I would like to know how I can do that ? Thank you so much -
How to avoid combinatorial explosion in unit testing Django views
I have a rather complicated Django (Rest Framework) view which updates an object in the database. In order to update the object, some conditions need to be met (these aren't the real conditions, but they're similar): The user has to be logged in The username needs to begin with admin The update data needs to be valid according to some rules A separate expensive function is_moon_phase_ok needs to return True I'm trying to write a solid set of unit tests for this view and the scenarios that I've come up with are the following: when not logged in, return 401 when not logged in, return {"fail": "login"} when not logged in, don't touch database when not logged in, don't check moon phase when username is not admin_*, return 401 when username is not admin_*, return {"fail": "username"} when username is not admin_*, don't touch database when username is not admin_*, don't check moon phase when invalid data, return 400 when invalid data, return {"fail": "data"} when invalid data, don't touch database when invalid data, don't check moon phase when logged in, return 200 when logged in, return updated data when logged in, check moon phase when logged in, update database … -
django How to Retrieve Data using POST and returned the data with serializer
How to use POST to retreive single data on models. My idea, at the beginning, was to pass a map of parameters. Then The View, on the server side, would take care of reading the needed parameters in the map and return the response. when i test this on postman, i send request body with username and password, but then its return 'name is required', i want this api work like generics.Retrieve but not with url, but with POST instead Models.py class Member(models.Model): name = models.CharField(max_length=100) password = models.CharField(max_length=100) email = models.EmailField(unique=True) phone = models.IntegerField(default=9999) serializer.py class LoginMemberSerializer(serializers.ModelSerializer): class Meta: model = Member fields =[ 'name', 'password', 'email', 'phone', ] view.py class LoginMemberAPI(APIView): def get_queryset(self): return Member.objects.all() def post(self, request, format=None): serializer = LoginMemberSerializer(data=request.data) if serializer.is_valid(): print(serializer.validated_data['email']) member = Member.objects.get(name = str(serializer.validated_data['name'])) # serializer.save() return Response(serializer.data) return Response(serializer.errors) -
Append in two for loop dajngo
I have two albums in 1st loop abc and abc123 and two images in abc album and 3 images in abc123 album but my response is returning 5 images in each album i'm not able to create proper response models.py class Upload(models.Model): image=models.ImageField(upload_to='upload/', blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) # url= models.CharField(max_length=500) def __str__(self): return str(self.id) class Album(models.Model): name = models.CharField(max_length=128) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.name) class AlbumImage(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) image = models.ForeignKey(Upload, on_delete=models.CASCADE) views.py def getalbum(self,request): albums=Album.objects.filter(user=request.user) album={} image_list={} all_results=[] all_images=[] for a in albums: album_images=AlbumImage.objects.filter(album=a) for i in album_images: image_object=Upload.objects.get(id=str(i.image)) image_list=str(image_object.image) all_images.append(image_list) album[a.name]=all_images all_results.append(album) return Response(all_results) response [ { "abc": [ "upload/images_aPWBEcp.jpeg", "upload/images.jpeg", "upload/ic_id_card_placeholder_N0x2KP9.png", "upload/images_jocZcBu.jpeg", "upload/ic_id_card_placeholder_N0x2KP9.png" ], "abc123": [ "upload/images_aPWBEcp.jpeg", "upload/images.jpeg", "upload/ic_id_card_placeholder_N0x2KP9.png", "upload/images_jocZcBu.jpeg", "upload/ic_id_card_placeholder_N0x2KP9.png" ] } ] abc album upload/images_aPWBEcp.jpeg upload/images.jpeg abc123 album upload/ic_id_card_placeholder_N0x2KP9.png upload/images_jocZcBu.jpeg upload/ic_id_card_placeholder_N0x2KP9.png -
Format to save value in DurationField in Django
I am unable to find that how I can set value of Duration Field in AdminPanel Lets say that I want to set that value to 1 year So that latter I can get DurationField value and add it to datetime.datetime.now() -
AWS Elastic BeanStalk SignatureDoesNotMatch
I created an Elastic Beanstalk Environment using windows Power shell and i followed this deployment document Deploying a Django Application to Elastic Beanstalk I done these steps: Python Virtual Environment with Django, created django project, create IAM user i got Access Key ID and Secret Access Key ID failing this step environment and deploy your Django application when ever i try eb init it asking access key, secret access key and region aws application auto generated names after done these steps i am getting this error SignatureDoesNotMatch. The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details I am new to deployment please help me any one Thanks in advance ... -
How to make Django form Field Unique?
I have a Signup form Where I want to make data of email and mobile Number Field to be Unique.... class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.', unique=True) mobile_no = forms.CharField(validators=[max_length=17, initial='+91', unique=True) I am Currently using unique=True but it raise Error as... TypeError: __init__() got an unexpected keyword argument 'unique' -
loanform() got an unexpected keyword argument 'cname'
I am trying to submit the form after entering the details but after submitting, it shows a TypeError msg like unexpected keywords arguments 'cname' in loanform(cname = name, email = email, mobile = mobile, scheme = scheme, city = city, msg = msg) method. My Model.Py File class loanform(models.Model): cname = models.CharField(max_length=50) email = models.CharField(max_length=30) mobile = models.CharField(max_length=15) scheme = models.CharField(max_length=20) city = models.CharField(max_length=20) msg = models.CharField(max_length=200) def __str__(self): return self.cname My View.Py File def loan_form(request): print("Form is Submitted.") name = request.POST.get("name",False) email = request.POST.get("email",False) mobile = request.POST.get("mobile",False) scheme = request.POST.get("scheme",False) city = request.POST.get("city",False) msg = request.POST.get("msg",False) lnform = loanform(cname = name, email = email, mobile = mobile, scheme = scheme, city = city, msg=msg) lnform.save() return render(request, 'loanform.html') My Url.Py File path('loan_form/', views.loan_form, name='loan_form') -
Decoding JSON data from QueryDict
I am sending JSON data to my django program. I am facing problems decoding the data. In javascript, I convert an object which encapsulates two arrays into JSON, and read it back. Javascript: data = { "RegAvStart": reg_start, "RegAvStop": reg_end }; data = $(this).serialize() + "&" + $.param(data); console.log(data); var jsondata = JSON.stringify(data); console.log("JSON:" + jsondata); Here, both reg_start and reg_end are arrays of strings. In the console I get: JSON:"&RegAvStart%5B%5D=05%3A00%20AM&RegAvStart%5B%5D=05%3A30%20PM&RegAvStop%5B%5D=08%3A00%20AM&RegAvStop%5B%5D=09%3A30%20PM" My django(python) code: def save_doctorslots(request, cliniclabel, doctor_id): doctor_id=int(doctor_id) doc = get_object_or_404(doctor, docid=doctor_id) cl = Clinic.objects.get(label=cliniclabel) print("Clinic name", cl.name) if request.method == 'POST': msg ="Received SaveSlots data for doctor %d clinic %s" % (doctor_id, cliniclabel) print(msg) print(request.POST) regavst = request.POST.get('RegAvStart[]') print(type(regavst)) if not regavst is None: regular_available_start = json.loads(regavst) else: print("Didnt get regular available hours") Output: Received SaveSlots data for doctor 1 clinic joelent <QueryDict: {'RegAvStart[]': ['05:00 AM', '05:30 PM'], 'RegAvStop[]': ['08:00 AM', '09:30 PM']}> <class 'str'> 2018-10-04 10:45:53,000 django.request ERROR Internal Server Error: /clinic/joelent/doctor/save/slots/1 Traceback (most recent call last): File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/joel/.local/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) … -
Slow upload speed with Ajax call
I have an interesting problem - I have my own IIS 2016 server, that I use to host a website which allows the users to upload a variety of files - some in text format, the others zip'ed up together. Initially the website would return error 500 from the server when trying to upload something bigger, like ~50MB. I Googled up that IIS requires configuration of maxAllowedContentLength (changed default to 209715200, ~300MB) and FastCGI's parameters for IDLE, ACTIVITY and REQUEST (changed to 600) in order to allow bigger files upload without hitting the file size limit. However, now that the files are getting uploaded, the upload speed for these bigger files slowed down to a crawl. Previously I could upload ~20MB files in 10sec on a local network, while now 50MB takes like ~160sec. Not a linear increase I would expect. My website runs on Django, and my POST method file transfer is carried out by Ajax call in JS: $('#sn').on('submit', function(event) { event.preventDefault(); var post_data = new FormData($("#sn")[0]); $.ajax({ xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener("progress", function(evt) { var percent = Math.round(evt.loaded/evt.total * 100) console.log(percent) $('#query_button').attr('disabled', true) $('#query_button').get(0).innerText = "Upload status: " + percent + '%' }, … -
In django, pagination is not working for second page and thereafter ,the objects are not displayed
when i click on "next" the objects that should be displayed on the next page is not being displayed. but the objects are being displayed for the first page.(ie, the correct number of objects as well) Also what is 'page' in 5th line in views.py? views.py def search(request): context ={} search_list = Search.objects.all() paginator = Paginator(search_list, 4) # Show 4 contacts per page page = request.GET.get('page', 1) search = paginator.get_page(page) context['search'] = search return render(request, "main.html", context) main.html (template) {% for result in search %} <br> {{ forloop.counter }} <br> {{ result.Query }} <!-- {{ search.Result.name }} --> <br> {{ result.json }} <br> <br> {{ result.json.name }} <br> <br> {{ result.json.price }} <br> <br> {{ result.json.author }} <br> {% endfor %} <div class="pagination"> <span class="step-links"> {% if search.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ search.previous_page_number }}">previous</a> {% endif %} <span class="current"> {{ posts.paginator.count }} Page {{ search.number }} of {{ search.paginator.num_pages }}. </span> {% if search.has_next %} <a href="?page={{ search.next_page_number }">next</a> <a href="?page={{ search.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> -
How to get count with foreign key in django rest framework
Here is my models.py class Language(models.Model): language_id = models.BigAutoField(primary_key=True) language_name = models.CharField(max_length=255) created_on = models.DateTimeField(auto_now=True) latest_build_on = models.DateTimeField(auto_now_add=True) latest_version = models.DecimalField(max_digits=5, decimal_places=2) company = models.OneToOneField('Company',on_delete=models.CASCADE,related_name='language') def __str__(self): return self.language_name class Frameworks(models.Model): framework_id = models.BigAutoField(primary_key=True) framework_name = models.CharField(max_length=255) framework_logo = models.FileField() created_on = models.DateTimeField(auto_now=True) latest_build_on = models.DateTimeField(auto_now_add=True) latest_version = models.DecimalField(max_digits=5, decimal_places=2) language = models.ForeignKey('Language',on_delete=models.CASCADE,related_name='frameworks') def __str__(self): return self.framework_name Here is serializers.py class GetLanguageSerializer(serializers.ModelSerializer): technology = serializers.StringRelatedField(many=True) frameworks = serializers.StringRelatedField(many=True) class Meta: model = Language fields = ('language_name','created_on','latest_build_on','latest_version','company','technology','frameworks') depth = 1 class LanguageSerializer(serializers.ModelSerializer): class Meta: model = Language fields = ('language_name','created_on','latest_build_on','latest_version','company') class GetFrameworksSerializer(serializers.ModelSerializer): language = serializers.StringRelatedField() class Meta: model = Frameworks fields = '__all__' depth = 1 class FrameworksSerializer(serializers.ModelSerializer): class Meta: model = Frameworks fields = '__all__' Here is my views.py class LanguageView(viewsets.ModelViewSet): queryset = Language.objects.all() serializer_class = LanguageSerializer filter_backends = [SearchFilter,OrderingFilter] search_fields = ['language_name'] def get_serializer_class(self): serializer_class = self.serializer_class if self.request.method == 'GET': serializer_class = GetLanguageSerializer return serializer_class class FrameworksView(viewsets.ModelViewSet): queryset = Frameworks.objects.all() serializer_class = FrameworksSerializer filter_backends = [SearchFilter,OrderingFilter] search_fields = ['framework_name'] def get_serializer_class(self): serializer_class = self.serializer_class if self.request.method == 'GET': serializer_class = GetFrameworksSerializer return serializer_class Here I am getting api like this: [ { "language_name": "python", "created_on": "2018-10-03T04:59:37.407717Z", "latest_build_on": "2018-10-03T04:59:37.407801Z", "latest_version": "3.60", "company": { "company_id": 1, "company_name": "Guido van dom … -
Is there any way to get count and table data in single Query
The problem is, to get count and table data, I have to hit the database two times in Django. For example: count = queryset.count() # To get count data = queryset.values('columns') # To get data Is there any way to get data in the single query. One solution is to use len() function, but it is not good for a bigger table to load in RAM. In mysql, I got this, But how to execute through Django ORM SELECT t1.count, id FROM table1, (select count(*) as count FROM table1) as t1 limit 10; Any help will be appreciated. -
TreeNodeMultipleChoiceField in django forms using MPTT cannot display the parent and child category
I want to display the parent and child category similar to first image in the Add Article page. I am using django mtpp -
Can someone guide me why i keep getting these errors in venv pycharm?
I tried reinstalling python because i had 32 bit whereas my system is 64 bit. Had a missing python27.dll which i found online and replaced and some errors which i still have with psycopg2 which i tried to replace with psycopg from stickpeople but still keep getting errors..Any help is appreciated. python manage.py migrate Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 354, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 445, in execute output = self.handle(*args, **options) File "C:\Python27\lib\site- packages\django\core\management\commands\migrate.py", line 93, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 19, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Python27\lib\site-packages\django\db\migrations\loader.py", line 47, in __init__ self.build_graph() File "C:\Python27\lib\site-packages\django\db\migrations\loader.py", line 191, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 59, in applied_migrations self.ensure_schema() File "C:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 49, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "C:\Python27\lib\site-packages\django\db\backends\base\base.py", line 164, in cursor cursor = self.make_cursor(self._cursor()) File "C:\Python27\lib\site-packages\django\db\backends\base\base.py", line 135, in _cursor self.ensure_connection() File "C:\Python27\lib\site-packages\django\db\backends\base\base.py", line 130, in ensure_connection self.connect() File "C:\Python27\lib\site-packages\django\db\utils.py", line 98, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "C:\Python27\lib\site-packages\django\db\backends\base\base.py", line 130, in ensure_connection self.connect() File "C:\Python27\lib\site-packages\django\db\backends\base\base.py", line 119, in connect self.connection = self.get_new_connection(conn_params) File … -
ModuleNotFoundError: No module named 'mod_wsgi.server'; 'mod_wsgi' is not a package
I'm trying to run an Apache 2.4 server with mod_wsgi 4.5 and python 3.6/Django on my laptop running Ubuntu 18, but I'm getting a 500 error. The error is: [Wed Oct 03 20:17:10.146305 2018] [wsgi:error] [pid 15405:tid 140336693888768] [client 127.0.0.1:33306] mod_wsgi (pid=15405): Target WSGI script '/mnt/4e468d61-1820-41ad-8a44-8a356b024106/COP4331/server-side/webserver/mysite/mysite/wsgi.py' cannot be loaded as Python module. [Wed Oct 03 20:17:10.146362 2018] [wsgi:error] [pid 15405:tid 140336693888768] [client 127.0.0.1:33306] mod_wsgi (pid=15405): Exception occurred processing WSGI script '/mnt/4e468d61-1820-41ad-8a44-8a356b024106/COP4331/server-side/webserver/mysite/mysite/wsgi.py'. [Wed Oct 03 20:17:10.147188 2018] [wsgi:error] [pid 15405:tid 140336693888768] [client 127.0.0.1:33306] Traceback (most recent call last): [...] (for brevity's sake) [Wed Oct 03 20:17:33.631789 2018] [wsgi:error] [pid 15404:tid 140336685496064] [client 127.0.0.1:33312] import mod_wsgi.server [Wed Oct 03 20:17:33.631805 2018] [wsgi:error] [pid 15404:tid 140336685496064] [client 127.0.0.1:33312] ModuleNotFoundError: No module named 'mod_wsgi.server'; 'mod_wsgi' is not a package However, I definitely have mod_wsgi as a package- I've checked both my pip 2 and 3, and I've installed it for both. I'm not using a virtual environment, so that's not a factor. I'm really at my wit's end here, so I'd really appreciate if someone could help me. -
Custom command to create Django superuser as part of deployment
The best (or most cited) practice for creating Django superuser account is to create and execute a custom command like so: class Command(BaseCommand): def handle(self, *args, **options): if not User.objects.filter(username="admin").exists(): User.objects.create_superuser("admin", "admin@admin.com", "admin") I don't want to keep password and username in git, which is required for AWS beanstalk deployment. Are there any secure best practices for creating production site? A couple options I'm considering are: eb ssh into instance and create superuser interactively using manage.py. I'm thinking this should be OK since set / stored in remote database instance. Capture the username and password instance from os environment var set via beanstalk console. I.e., something like following instead: def handle(self, *args, **options): if not User.objects.filter(username="admin").exists(): User.objects.create_superuser(os.environ['SU_UNAME'], ... Any thoughts / suggestions appreciated. Thanks!