Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Raw SQL & Pagination
I have a view where by default, I am displaying 'today's' transactions, with a form for the user to select other dates to/from. Those values are being passed into a stored procedure on my MSSQL server, being called with pyodbc. However, if I am using OFFSET and FETCH ONLY, it doesn't allow for the pagination option. If I try to use the 'GET' method statement of the Class then it just reloads my original dates. My code is below - Any assistance is appreciated :) def adm_landing_page(request): print(request.method) form = SummaryDataForm(request.POST or None) if request.method == 'POST' and form.is_valid(): page = request.GET.get('page', 1) offset = page * 10 formFromDate = form.cleaned_data.get('formFromDate').strftime('%m-%d-%Y') formToDate = form.cleaned_data.get('formToDate').strftime('%m-%d-%Y') raw_sql = f"EXEC EasyTrade20.dbo.spGetDashSummaryData @formFromDate = '{from_date}', @formToDate = '{to_date}', @offset='{offset}' " with connections['default'].cursor() as cursor: cursor.execute(raw_sql) summary_rows = cursor.fetchall() paginator = Paginator(summary_rows, 10) try: summary_rows = paginator.page(1) except EmptyPage: summary_rows = paginator.page(paginator.num_pages) elif request.method == 'GET': page = request.GET.get('page', 1) offset = page * 10 with connections['default'].cursor() as cursor: # below is for testing only with hard coded date to confirm there is information raw_sql = f"EXEC EasyTrade20.dbo.spGetDashSummaryData @formFromDate = '05/29/2020', @formToDate = '05/29" \ f"/2020', @offset = '{offset}' " cursor.execute(raw_sql) summary_rows = cursor.fetchall() paginator … -
Automatically set ContentType S3 put_object
I am using this code to upload a file to s3: First, I get the file in Django in request.FILES: file = request.FILES['file_name'] Then I upload it to s3: s3.Bucket('my-bucket').put_object(Key=f'file_name.???', Body=file, ContentType='???') As indicated, I don't know what kind of file is going to be uploaded. Could be .pdf, .png, .jpg, even .py. How can I set the ContentType depending on what file is uploaded? Thanks! -
I am getting this error from 2 days ,Not able to fix.i am trying to do unit testing using pytest,
E django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
how to implement and customize multiselcect box that resembles djangos's group selectbox
I am using generic CVB(CreateView and UpdateView) that uses a customized form and consists of a couple of multiselect dropdowns from the model.But the multiselect django provides is not user friendly.and i have to questions. I want to implement the same technique as Django uses in its admin page for groups and permissions,where the user would add his/her choices to an different select box and so that the CVB can get all that is found on the new select box. My code is : class TeacherAssignment(models.Model): teacher = models.OneToOneField(EmployeeStatus, on_delete=models.CASCADE, related_name='teachers' ) subject = models.ManyToManyField(Subject, related_name='subjects') Section = models.ManyToManyField(Section, related_name='classes') class TeacherAssignmentForm(forms.ModelForm): chosen_sections = forms.ModelMultipleChoiceField(queryset=Section.objects.all(), required=False, widget=forms.SelectMultiple( attrs={'class': 'form-control novalidate', 'value': 'teme', 'id': 'selectedSections'})) chosen_subjects = forms.ModelMultipleChoiceField(queryset=Section.objects.all(), required=False, widget=forms.SelectMultiple( attrs={'class': 'form-control novalidate', 'value': 'bara', 'id': 'selectedSubjects'})) class Meta: model = TeacherAssignment fields =fields = ('teacher', 'Section', 'subject') def __init__(self, *args, **kwargs): super(TeacherAssignmentForm, self).__init__(*args, **kwargs) if kwargs.get('instance'): initial = kwargs.setdefault('initial', {}) initial['chosen_subjects'] = kwargs['instance'].Section.all()[:3] self.fields['teacher'].queryset = EmployeeStatus.objects.filter(employee_role='teacher') I googled and found a javascript to do the add/remove and it works fine and but i got stuck on the Django side for bothe CreateView and UpdateView. $().ready(function() { $('#add').click(function() { return !$('#select1 option:selected').remove().appendTo('#id_Section'); }); $('#remove').click(function() { return !$('#id_Section option:selected').remove().appendTo('#select1'); }); }); i … -
Django: How do I automatically fill form input with logged in users email?
I have made a contact form and want the from_email field to be pre filled if the user is logged in. views.py of homepage (where the form is displayed) def home(request): if request.method == 'GET': form = ContactForm(request=request) else: form = ContactForm(request.POST,request=request) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "home/home.html",{'form':form}) forms.py from django.shortcuts import render from django.contrib.auth.models import User class ContactForm(forms.Form): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(ContactForm, self).__init__(*args, **kwargs) if self.request.user.is_authenticated: email=self.request.user.email #self.fields["from_email"] = email from_email = forms.EmailField(initial=email,required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) -
Django Rest Framework API for Large Dataset Won't Load?
I'm using the Django Rest Framework to serve up some data as an API for making charts. I have a dataset that is about 500,000 rows x 20 columns. The Rest API works well for my smaller datasets, but for this one, if I navigate to the dataset (http://localhost:8000/api/data-list/) it just hangs and will not finish loading. Below is the code. The data I am referring to comes from the model Data: serializers.py: from rest_framework import serializers from data_platform.models import Indicator, Data, City class IndicatorSerializer(serializers.ModelSerializer): class Meta: model = Indicator fields = '__all__' class DataSerializer(serializers.ModelSerializer): class Meta: model = Data fields = '__all__' class CitySerializer(serializers.ModelSerializer): class Meta: model = City fields = '__all__' views.py: from django.shortcuts import render from django.http import JsonResponse import django_filters.rest_framework from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import generics from .serializers import IndicatorSerializer, DataSerializer, CitySerializer from data_platform.models import Indicator, Data, City from .pagination import CustomPagination @api_view(['GET']) def apiOverview(request): api_urls = { 'Indicator List':'/indicator-list/', 'Indicator Detail':'/indicator-detail/<int:pk>/', 'Data':'/data-list/', 'City':'/city-list/' } return Response(api_urls) @api_view(['GET']) def indicatorDetail(request, pk): indicators = Indicator.objects.get(id=pk) serializer = IndicatorSerializer(indicators, many=False) return Response(serializer.data) class indicatorList(generics.ListAPIView): queryset = Indicator.objects.all() serializer_class = IndicatorSerializer filter_backends = [django_filters.rest_framework.DjangoFilterBackend] filter_fields = ('id',) class cityList(generics.ListAPIView): queryset = City.objects.all() serializer_class … -
how to perform mathematical operations in django template
i want to print the value of current item in list(which is a integer) and its successor(not the list item) but the actual integer successor) at the same time..i am using {% for i in hour %}{{ i }}-{{i+1}}{% endfor %} but this gives me an error of "Could not parse the remainder: '+1' from 'i+1'" -
How to use bootstrap table extended with django?
I have a dataframe in my django and i want to have it into my template in the form of this table The data is not stored in model ,this dataframe is in views and its just stored in a variable called matrix. Can any one help me in doing so ? a b c d e f g h i j k l 0 30 84 7 53 79 41 45 48 95 52 8 15 1 55 11 12 36 44 97 7 91 78 88 5 84 2 64 28 29 12 24 19 42 47 16 61 73 33 3 20 9 34 1 59 86 84 57 99 30 97 86 4 99 64 97 88 71 3 41 74 50 40 39 56 .. .. .. .. .. .. .. .. .. .. .. .. .. 115 83 68 92 8 68 13 81 66 57 73 15 76 116 37 19 37 89 54 17 89 2 53 9 4 25 117 18 17 53 29 68 10 71 83 57 94 66 58 118 84 25 48 89 90 51 37 12 90 78 19 85 119 48 5 70 53 68 … -
ValueError: The given username must be set. Error Occured Using Django for registering User
raise ValueError('The given username must be set') using django python ... I have been trying to register a user using from django.contrib.auth.models import user Views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth.models import User # Create your views here. def register(request): if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('email') password1 = request.POST.get('password1') password2 = request.POST.get('password2') if password1 == password2: if User.objects.filter(username = username).exists(): return redirect('register') elif User.objects.filter(email = email).exists(): return redirect('register') else: user=User.objects.create_user(username = username,password =password1, email = email) user.save() return redirect('login') else: return redirect('/') else: return render(request, 'register.html') def login(request): return render(request, 'login.html') register.html <form method="POST" action="{% url 'register' %}"> {% csrf_token %} <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" id="username"> </div> <div class="form-group"> <label for="password1">Password</label> <input type="password" class="form-control" id="password1"> </div> <div class="form-group"> <label for="password2">AGAIN Password</label> <input type="password" class="form-control" id="password2"> </div> <div class="form-group"> <label for="email">Email address</label> <input type="email" class="form-control" id="email" placeholder="name@example.com"> </div> <div class="form-group form-check"> <input type="checkbox" class="form-check-input" id="check"> <label class="form-check-label" for="check">Check me out</label> </div> <button type="submit" class="btn btn-primary">Register</button> </form> user=User.objects.create_superuser(username = username,password =password1, email = email) I want to know that why it is just sending that The given username is must be set but instead I have set super_user already. How … -
Render Element HTML as plain text
I'm building a template tag in Django that returns HTML, I'm using the Element object to build the tree. Is there a way to render the tree as plain HTML? in my template i have something like {% build foo=bar %} build returns an Element, i cant find a way to render it and insert that Element into my HTML doc. -
Why does a ManyToMany relationship created in setUpTestData cause a duplicate key error?
I am using postgreSQL 12. I have the following models: class Publication(models.Model): title = models.CharField(max_length=30) class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) ...and the following TestCase classes: class TestA(TestCase): @classmethod def setUpTestData(cls): p = Publication.objects.create() for _ in range(5): m = Article.objects.create() m.publications.add(p) def test_1(self): self.assertEqual(True, True) class TestB(TestCase): @classmethod def setUpTestData(cls): print(Article.objects.all()) for _ in range(5): a = Article.objects.create() print(a.pk) def test_2(self): self.assertEqual(True, True) When I run these tests independently, the tests pass. When I run them together, I get the following error for the setUpTestData method under TestB: psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "article_pkey" DETAIL: Key (id)=(1) already exists. Further trial and error has led me to discover that this error only occurs when I include the ManyToMany relationship for TestA: m.publications.add(p) The first print() statement shows an empty queryset, so the tearDownClass method for TestA appears to have worked, however the pk of the first Article is 1, which is odd as I thought because Postgres PKs are generated from Sequence objects they should never roll back. What is happening here? shouldnt the first Article pk for TestB start with 6? Why does a duplicate error occur? How is this linked to the ManyToMany … -
Iterare through background images
I'm trying to make a dinamicaly background that changes images every x seconds. But i want the images to be sourced from a directory in a django project. I have this piece of code but is hardcoded and limited. var header = $('body'); var backgrounds = new Array( 'url(static/media/backgrounds/1.jpg)' , 'url(static/media/backgrounds/2.jpg)' , 'url(static/media/backgrounds/3.jpg)' , 'url(static/media/backgrounds/4.jpg)' , 'url(static/media/backgrounds/5.jpg)' , 'url(static/media/backgrounds/6.jpg)' , 'url(static/media/backgrounds/7.jpg)' , 'url(static/media/backgrounds/8.jpg)' , 'url(static/media/backgrounds/9.jpg)' , 'url(static/media/backgrounds/10.jpg)' ); var current = 0; function nextBackground() { current++; current = current % backgrounds.length; header.css('background-image', backgrounds[current]); } setInterval(nextBackground, 5000); header.css('background-image', backgrounds[0]); -
Why did the order of URL paths cause this Django bug?
I am setting up my views in Django so that a "POST" from my homepage (index) search form will redirect either (1) to the page that the user wanted, or (2) to a results list, if that page couldn't be found. The choice is conditional on a utility function called in the index view. Path 1 works fine. With path 2, I was getting a Not Found: (option 2 path - what I want) followed by Value Error - The (option 1 view path - not what I want) didn't return an HttpResponseObject. I fixed this bug, it seems, only by changing the order of the URL patterns in my urls.py. My question is, why would this happen if I'm not using regexs in my URLs? If my project is trying to redirect to the correct view (option 2) FIRST, why does the order of URL patterns matter? I was even getting the ValueError from the option 2 path URL. Views: def index(request): if request.method == "POST": form = SearchForm(request.POST) if form.is_valid(): query = form.cleaned_data['Search'] request.session['query'] = query if util.get_entry(query): return HttpResponseRedirect(reverse("article", kwargs={'article': query})) else: return HttpResponseRedirect(reverse("search_list")) else: return render(request, 'encyclopedia/index.html', {'form': form}) else: form = SearchForm() return render(request, "encyclopedia/index.html", … -
Wagtail: Change list_display for wagtailmenus
I'm using the wagtailmenus library with some custom models as described here. Nothing major, it just adds a language field: class TranslatableFlatMenu(AbstractFlatMenu): language = models.CharField(choices=TRANSLATION_CHOICES, help_text='For what language the menu should be used', max_length=13) content_panels = ( MultiFieldPanel( heading=_("Menu Details"), children=( FieldPanel("title"), FieldPanel("site"), FieldPanel("handle"), FieldPanel("heading"), FieldPanel("language"), ) ), FlatMenuItemsInlinePanel(), ) class TranslatableFlatMenuItem(AbstractFlatMenuItem): menu = ParentalKey( TranslatableFlatMenu, on_delete=models.CASCADE, related_name=settings.FLAT_MENU_ITEMS_RELATED_NAME, ) This works great, however I would like to display the field here: Now for regular models I can use ModelAdmin and pass list_display, but wagtailmenus seems to already register the menus itself. Is it possible to still change the list_display property somehow so I can display the language in the list? -
Elastic Beanstalk, Djamgo deployment error, Could not find a version that satisfies the requirement pkg-resources==0.0.0
I am trying to deploy my django project on Elastic Beanstalk. I am following the official document and this article and I think I have done most of the things asked in those resources correctly. But my deployment is failing every time. On eb logs I found this error No matching distribution found for pkg-resources==0.0.0 (from -r /opt/python/ondeck/app/requirements.txt (line 27)) You are using pip version 9.0.1, however version 20.1.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. 2020-07-07 18:19:51,388 ERROR Error installing dependencies: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 Traceback (most recent call last): File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 22, in main install_dependencies() File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 18, in install_dependencies check_call('%s install -r %s' % (os.path.join(APP_VIRTUAL_ENV, 'bin', 'pip'), requirements_file), shell=True) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 (Executor::NonZeroExitStatus) So far my problem seems very similar to this stackoverflow question but it is not. I removed the pkg-resources==0.0.0 from requirements.txt but it is still giving me the same error. My requirements.txt asgiref==3.2.10 attrs==19.3.0 awsebcli==3.18.1 bcrypt==3.1.7 blessed==1.17.8 botocore==1.15.49 cached-property==1.5.1 cement==2.8.2 certifi==2020.6.20 cffi==1.14.0 chardet==3.0.4 colorama==0.4.3 cryptography==2.9.2 Django==3.0.8 django-cors-headers==3.3.0 djangorestframework==3.11.0 djangorestframework-simplejwt==4.4.0 docker==4.2.2 docker-compose==1.25.5 dockerpty==0.4.1 docopt==0.6.2 … -
Im having problems with backennd [closed]
Im making a website. I have done the front end but i have no experience in backend. Its a earning website. People do offers and earn real money. Im using adgate for the offers. Which im using it as a irframe. I have the front end setup but not backend. I will pay someone for backend if needed. But theres a github link for the api. I dont know how to use apis. Please help me. I also have a withdraw page where they can withdraw there money. Please help. Thanks -
docker build ERROR: Could not install packages due to an EnvironmentError: [Errno 2]
I'm getting this error when I run docker build . ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: '/tmp/build/80754af9/idna_1593446292537/work' This comes while it's processing the requirements.txt file. > Collecting Django<3.1.0,>=3.0.7 Downloading > Django-3.0.8-py3-none-any.whl (7.5 MB) Collecting > djangorestframework<3.12.0,>=3.11.0 Downloading > djangorestframework-3.11.0-py3-none-any.whl (911 kB) Collecting > asgiref==3.2.10 Downloading asgiref-3.2.10-py3-none-any.whl (19 kB) > Collecting certifi==2020.6.20 Downloading > certifi-2020.6.20-py2.py3-none-any.whl (156 kB) Collecting > cffi==1.14.0 Downloading cffi-1.14.0.tar.gz (463 kB) Collecting > chardet==3.0.4 Downloading chardet-3.0.4-py2.py3-none-any.whl (133 > kB) Collecting click==7.1.2 Downloading > click-7.1.2-py2.py3-none-any.whl (82 kB) Collecting cymem==1.31.2 > Downloading cymem-1.31.2.tar.gz (33 kB) Collecting cytoolz==0.9.0.1 > Downloading cytoolz-0.9.0.1.tar.gz (443 kB) Collecting dill==0.2.9 > Downloading dill-0.2.9.tar.gz (150 kB) Collecting en-core-web-sm@ > https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.0.0/en_core_web_sm-2.0.0.tar.gz > Downloading > https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.0.0/en_core_web_sm-2.0.0.tar.gz > (37.4 MB) Processing /tmp/build/80754af9/idna_1593446292537/work Suggestions? -
How to use ManyToManyField in Django serializer?
I have created one model where I am using ManyToMany for one field: class Hospitals(models.Model): name = models.CharField(max_length=100, blank=False, null=False) class HealthProduct(models.Model): hospital_list = models.ManyToManyField(Hospitals) .. .. serializer hospital_field = serializers.SlugRelatedField(slug_field='id', queryset=Hospitals.objects.all(), many=True) class HealthProductSerializers(serializers.ModelSerializer): hospital_list = hospital_field class Meta: model = HealthProduct exclude = ("created_at", "updated_at") Here I am passing a list of Hospital_object id to my serializer { "hospital_list": [1, 2], .. } and when I saved serializer data getting a response { "hospital_list": [ 1, 2 ] ... } but I want to get saved response either like: { "hospital_list": [ { "id": 1, "name": "Apollo Bangalore Cradle Ltd." }, { "id": 2, "name": "Greenview Healthcare Pvt. Ltd." } ] ... } or { "hospital_list": [ "Apollo Bangalore Cradle Ltd.", "Greenview Healthcare Pvt. Ltd." ] ... } How should I use the ManyToMany field in my serializer, to save and a get response in desire format? -
Django app works on localhost but not Heroku
Right now I have a very basic app then simply displays some text. This works on both localhost and heroku. The problem is with the admin page. I am able to sign in to the admin page on localhost, but if I try to sign in on heroku, I get the following error: ProgrammingError at /admin/login/ relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... The only difference between the script running on localhost and on heroku is that the one running on heroku uses django-heroku. I can't find any solution anywhere to this problem. Thanks in advance. -
Adding paginations to comments of a post in Django using Waypoint and Infinite.js
I am trying to add pagination to the comments of an article in the article details view page. However, when I scroll the comments are not being displayed, and if I use regular Django-pagination without infinite scrolling the page reloads again. My intention is just to paginate the comments of the post only. Currently, in my view I have: def post_detail(request, guid_url): data = dict() post = get_object_or_404(Post, guid_url=guid_url) comment_list = post.comments.filter(reply=None) if request.method == 'POST': form = CommentForm(request.POST or None) if form.is_valid(): comment = form.save(False) reply_id = request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment.name = request.user comment.post = post comment.reply = comment_qs comment.save() else: data['is_valid'] = False else: form = CommentForm() guid_url = post.guid_url comment_count = post.comment_count() page = request.GET.get('page', 1) paginator = Paginator(comment_list, 10) try: comments = paginator.page(page) except PageNotAnInteger: comments = paginator.page(1) except EmptyPage: comments = paginator.page(paginator.num_pages) context = {'post':post, 'form':form, 'comments':comments, 'comment_count':comment_count, 'guid_url':guid_url, } if request.is_ajax(): #changed from Comments.objects/filter(post=post, reply=None) comment_new_list = post.comments.filter(reply=None) page = request.GET.get('page', 1) paginator = Paginator(comment_new_list, 10) try: comments_new = paginator.page(page) except PageNotAnInteger: comments_new = paginator.page(1) except EmptyPage: comments_new = paginator.page(paginator.num_pages) comment_count_new = post.comment_count() context_new = {'post':post, 'comments':comments_new, 'comment_count':comment_count_new, 'guid_url':guid_url, 'form':form, } data['comments'] = render_to_string('home/posts/post_comment.html',context_new,request=request) data['likes'] = render_to_string('home/posts/likes.html',context_new,request=request) return … -
Django search returns "Page not found (404) error
Like many other questions on here (Writing a very basic search form in Django, django search page not found error), I am using Django and I have a search bar in a form that when submitted, returns a "Page not found" error. Getting the urls correct tends to be my achilles and I am hoping an extra set of eyes can spot my error. Here are excerpts of my code: models.py class Tool(models.Model): tool_name = models.CharField(max_length=200) release_date = models.DateField('release_date', null=True, blank=False) views.py def search_results(request): if request.GET: search_term = request.GET['search_box'] results = Tools.objects.filter(tool_name__icontains=search_term) return render(request, 'search_results.html', {'results': results}) return render(request, 'search_results.html') urls.py urlpatterns = [ ... path('search_results/', views.search_results, name='search_results'), ] templates/base_generic.html <form name="search_form" method="GET" action="{ % url 'search_results' %}"> <input id="search_box" type="text" name="search_box" placeholder="Search tools..." > <button id="search_submit" type="submit" >Submit</button> </form> templates/search_results.html {% extends "base_generic.html" %} ... {% if results %} <table style="width:100%"> <tr> <th>Tool</th> <th>Release Date</th> </tr> {% for t in results %} <tr> <td><a href="{% url 'tool-detail' t.tool_name.pk %}">{{ t.tool_name }}</a> </td> <td>{{ t.release_date }}</p> </tr> {% endfor %} </table> <hr><p> {% else %} <h3 class='error'>Your search term returned no items, please try again.</h3> {% endif %} {% endblock %} file structure ├── models.py ├── templates │ ├── base_generic.html … -
Django with Virtualenv raises an error with nonetype in the ntpath.py
I have installed django 2.0 to this virtualenv, however, when I try to run a website, it returns this error TypeError: expected str, bytes or os.PathLike object, not NoneType . I've had a look online for a solution and all though there are similar questions, they were for pyinstaller, not what I'm working with, Django. I have python3.7 django 2.0, running in pyinstaller inside an Anaconda virtualenv, which is a full anaconda install. Could anyone help out, here is the full error self.check_migrations() File "C:\ProgramData\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\base.py", line 427, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\ProgramData\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\ProgramData\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\ProgramData\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\migrations\loader.py", line 200, in build_graph self.load_disk() File "C:\ProgramData\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\migrations\loader.py", line 99, in load_disk directory = os.path.dirname(module.__file__) File "C:\ProgramData\Anaconda3\envs\MyDjangoEnv\lib\ntpath.py", line 221, in dirname return split(p)[0] File "C:\ProgramData\Anaconda3\envs\MyDjangoEnv\lib\ntpath.py", line 183, in split p = os.fspath(p) TypeError: expected str, bytes or os.PathLike object, not NoneType -
Django Edit User profile model
The views function send two forms to template and receive data from it, it saves the changes about User (email, first_name, last_name), but don't save for second form Views: if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) profile_form = UserProfileInfoForm(request.POST, instance=request.user) if form.is_valid() and profile_form.is_valid(): user_form = form.save() custom_form = profile_form.save(False) custom_form.user = user_form custom_form.save() print(custom_form) return HttpResponseRedirect(reverse('profile')) return render(request, 'root/profile.html', {"client_info": client_info, "client_details": client_details, "form_1": EditProfileForm, "form_2": UserProfileInfoForm}) Forms: class EditProfileForm(forms.ModelForm): class Meta: model = User fields = ( 'email', 'first_name', 'last_name' ) class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ("social_media_ins", "social_media_vk", "social_media_tk", "social_media_fb", "social_media_youtube",) -
cannot login into Django admin after put it in sub-domain
I just moved my website using django to run with sub-domain and host at heroku. everything works just find except when I ran the admin it give me https://test.mydomain.com/admin/login/?next=/admin/ and I cannot login into the admin panel as before, I also tried by re-run the createsuperuser but still cannot login with credential . anyone know the solution, please -
Create a chat app in django using python, html and css, without java script
I want to create a basic chat app in django but in many places i have seen that people are using python with java script but i dont want to use java at all i just want to use html, css and python. I recently have switched from c++ to python, now i dont want to switch to java because i want to make some good projects otherwise i will keep switching. Plz help me about the project and plz tell how can i make a simple chat app using python,html and css. Seriously i dont want to use java script as a frontend language. I can use django template language or css and html but i just dont want to use java. Plz answer as soon as possible. . . . Thank you