Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use same database for Django and Laravel
I'm using Django for backend, but for some reason, I want to use Laravel beside Django and share the database between them. so the same database for Django and Laravel. but the problem is that Django migrations are not equal to Laravel migrations so the database is different from ( for example constraints and indexes and some other options). Is this going to break backend if I use Django as the primary database and use Laravel as a secondary backend? If true, how I can use Django and Laravel in the same database? -
Django ModelForm not displaying
I'm trying to display a select box within a table in Django. Unfortunately, when I put the form within the HTML template it does not render although other elements do. forms.py: resultchoices = [ ('Not Started', 'Not Started'), ('Pass', 'Pass'), ('Issues', 'Issues'), ('N/A', 'N/A'), ] class checklistform(ModelForm): class Meta: model = checklist fields = "__all__" widgets = { 'INFO_001_result': Select(choices=resultchoices,), } models.py: class checklist(models.Model): resultchoices = [ ('Not Started','Not Started'), ('Pass', 'Pass'), ('Issues', 'Issues'), ('N/A', 'N/A'), ] INFO_001_result = models.CharField(choices=resultchoices,default='Not Started',null=False,max_length=11), INFO_001_remark = models.CharField(null=True,default='',max_length=400) Views.py: checklistform = checklistform # Create your views here. def checklist(request): context = { 'checklistform': checklistform, } return render(request, 'pages/Checklist.html',context ) HTML template: <td style="text-align:Center;background-color:#44546A;color:#000000;font-size:10px;width:108px;border: 1px solid #999999; " eth-cell="E5" >{{ checklistform.INFO_001_result }}</td> <td style="color:#000000;font-size:10px;width:88px;border: 1px solid #999999; " eth-cell="F5" >{{ checklistform.INFO_001_remark }}</td> </tr> Django doesn't give me any error it just fails to render that section within the template. -
["'<built-in function id>' is not a valid UUID."]
I am trying to patch an existing but i get an unknown problem .Does anybody know why? Models.py class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(UserProfile,on_delete=models.CASCADE, related_name='articles') caption = models.CharField(max_length=250) Views.py class ArticleView(CreateAPIView): serializer_class = ArticleCreateSerializer permission_classes = (IsAuthenticated,) def patch(self, request, *args, **kwargs): article = get_object_or_404(Article, pk=id) serializer = ArticleCreateSerializer(data=request.data, partial=True) if serializer.is_valid(): article = serializer.save() return Response(ArticleCreateSerializer(article).data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Error: ["'<built-in function id>' is not a valid UUID."] -
Django_filters. How to do foreign key as a lot of checkboxes?
I need to replace that To that In my models: class Product(models.Model): """Store product""" category = models.ForeignKey( 'Category', on_delete=models.SET_NULL, null=True, related_name='products' ) class Category(models.Model): """Product category""" name = models.CharField(max_length=50) Product has a foreign key to Category and I need to filter by categories with list of checkboxes. My filters.py: class ProductFilter(django_filters.FilterSet): category = django_filters.ModelMultipleChoiceFilter(queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model = Product fields = ['category'] Views: class ProductFilterView(ListView): model = Product template_name = 'store/product-filter.html' context_object_name = 'products' def get_context_data(self, **kwargs): context['filter'] = ProductFilter(self.request.GET, queryset=self.get_queryset()) How i can select categories for products by checkboxes? -
Error executing django-admin startproject
Installed django with the pip3 install django command. Then I decided to create a project with the django-admin startproject mysite command And got the error: zsh: command not found: django-admin How to solve this problem? I have mac os catalina 1.15.5 and python 3.7. Thank you in advance for the decision! -
Django custom context processor for sidebar navigation
I have an application that displays the parent object's title as a sidebar navigation label and its children under it as a list. To view this, this is my current setup: A project-level base template base.html with the sidebar and content layout. And in the base.html the sidebar navigation with lot of conditionals using {% if request.resolver_match.url_name == "<view-name>" %} to set what is active and display their related child objects as menu items under them. And then in the app templates I use {% extends "base.html" %}. But this feels a bit hacky and the sidebar content in the base.html is getting cluttered as I add views. Is there a simple pythonic/Django approach to solve this? I reckon context processors might be the right way to do this, but I am not sure how to do it without hardcoding the views. Something like, # do something and get the context object if is_parent(obj): child = get_related(obj) nav_categeory = obj.title nav_items = child.objects.all() # do something and return sidebar content html In other words, is there a functional DRY approach to conditionally populate the sidebar with navigational elements based on their context objects? -
Compiled slug size: 578.1M is too large (max is 500M)
I have been trying to install my python dependencies and it's accumulating to a size of 578 MB, not letting me push my files. This is the first time I am trying to push python dependencies to my application. Hence cache clearing is not the expected answer Any suggestion would be greatly appreciated -
Internal server occurred just before sending email in Django
I have written "Reset Password" feature in my Django app as per the steps given in link Reset Password When I run application in Debug mode, I am able to send email. But when I run this in production mode, I am getting "Server Error (500)". error just before sending email and I don't see any error in server logs. I am thinking issue could here at url link ("dau_gui_app/registration/reset/") In Production I ensured that following Set the DEBUG mode OFF in settings.py file as below DEBUG = False TEMPLATE_DEBUG = False DEV_DEBUG = False ALLOWED_HOSTS = ["*"] 3. url(r'^login/password_reset/$', auth_views.password_reset, {'template_name': 'dau_gui_app/registration/password_reset_form.html', 'password_reset_form': forms.CustomEmailValidationOnForgotPassword}, name="password_reset"), url(r'^password_reset/done/$', auth_views.password_reset_done), url(r'^dau_gui_app/registration/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',views.PasswordResetConfirmView,name='password_reset_confirm'), url(r'^reset_done/$', auth_views.password_reset_complete), url(r'^password_reset_link_expired', views.password_reset_link_expired_view, name="password_reset_link_expired"), Please let me know there is any way I will about what is issue?. -
I have an error while using pipenv install django on my cmd or terminal
pipenv install djangoo result is: [pipenv.exceptions.ResolutionFailure]: return resolve_deps( [pipenv.exceptions.ResolutionFailure]: File "c:\users\dell\appdata\local\programs\python\python38-32\lib\site-packages\pipenv\utils.py", line 718, in resolve_deps [pipenv.exceptions.ResolutionFailure]: resolved_tree, hashes, markers_lookup, resolver = actually_resolve_deps( [pipenv.exceptions.ResolutionFailure]: File "c:\users\dell\appdata\local\programs\python\python38-32\lib\site-packages\pipenv\utils.py", line 480, in actually_resolve_deps [pipenv.exceptions.ResolutionFailure]: resolved_tree = resolver.resolve() [pipenv.exceptions.ResolutionFailure]: File "c:\users\dell\appdata\local\programs\python\python38-32\lib\site-packages\pipenv\utils.py", line 395, in resolve [pipenv.exceptions.ResolutionFailure]: raise ResolutionFailure(message=str(e)) [pipenv.exceptions.ResolutionFailure]: pipenv.exceptions.ResolutionFailure: ERROR: ERROR: Could not find a version that matches dev [pipenv.exceptions.ResolutionFailure]: No versions found [pipenv.exceptions.ResolutionFailure]: Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies. First try clearing your dependency cache with $ pipenv lock --clear, then try the original command again. Alternatively, you can use $ pipenv install --skip-lock to bypass this mechanism, then run $ pipenv graph to inspect the situation. Hint: try $ pipenv lock --pre if it is a pre-release dependency. ERROR: ERROR: Could not find a version that matches dev No versions found Was https://pypi.org/simple reachable? -
What should I learn now?
so I know all python basic stuff and object-oriented python. I also have some knowledge about selenium and tkinter. In 2020, what libraries are good to learn to find work? I was thinking about machine learning or django, but I'm not sure that they are going to provide me work. -
Django Sqlite exporting model data from hosted application to local PC for another database
I am trying to export my sqlite database data (only one model) into form readable by SQL Server. I am using hosting service so database is not anywhere local but SQL Server is on my PC. I want to do it periodically (daily). I have read about python manage.py dumpdata and thought about executing this python script from hosted location but is it good idea? Maybe there is a tool that will be usefull? I have no experience in this matter so sorry if this is silly question. -
django csrf verification failed in android webview. android webview can not verify django csrf token
I design a Django web app and then I create an android webview.in android webview, all functions work properly.in the Django web app, I use a payment gateway. payment gateway working in all browsers but it's not working in the android web view.android webview its return a forbidden(403) CSRF verification failed error. <form action="{% url 'carts:checkout' %}" method="POST"> {% csrf_token %} <script src="https://checkout.razorpay.com/v1/checkout.js" data-key="rbu_htgd76hsd5fwc" data-amount="{{ object.total | multiply:100 }}" data-currency="INR" data-buttontext="Pay Now" data-name="" data-description="Test transaction" data-image="https://example.com/your_logo.jpg" data-prefill.name="{{ request.user.name }}" data-prefill.email="{{ request.user.email }}" data-prefill.contact="{{ request.user.mobile_no }}" data-prefill.order="{{ object.order_id }}" data-theme.color="#F37254" > </script> <input type="hidden" custom="Hidden Element" name="hidden"></form> -
Is not possible to add the correct date and time
I've created a simple form to test the DateTimeField. settings.py # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-GB' TIME_ZONE = 'Europe/Rome' USE_I18N = True USE_L10N = True USE_TZ = True USE_THOUSAND_SEPARATOR = True models.py from django.utils import timezone class DateTimeTest(models.Model): publishing_date = models.DateTimeField( default=timezone.now, ) forms.py class CustomDateTime(forms.DateTimeInput): input_type = 'datetime-local' class DateTimeTestForm(forms.ModelForm): publishing_date = forms.DateTimeField( widget= CustomDateTime( format='%d/%m/%Y %H:%M', ) ) class Meta: model = DateTimeTest fields = ['publishing_date'] views.py def create_datetime(request): if request.method == 'POST': form = DateTimeTestForm(request.POST or None) if form.is_valid(): new_testdatetime.save() return redirect('test') else: form = DateTimeTestForm() context = { 'form': form, } template = 'blog/forms/test.html' return render(request, template, context) urls.py path('test/', views.create_datetime, name='test'), test.html {% extends 'base.html' %} {% load static %} {% block content %} <form method="POST" enctype="multipart/form-data" novalidate>{% csrf_token %} {{ form.as_p }} <input type="submit" class="btn btn-info" value="Post"> </form> {% endblock %} When I try to post a date and time I see this message: Enter a valid date/time I remember that when I set the format I can insert a date and time based on the format. What I've wrong? -
Simply save time as UTC with Django
I get a timestamp (via an extern API). When I try to save that, it always is two hours earlier. I read some docs like Django Time zones, pytz and dateutil but I still don't understand how to tell Django that this specific time should not be converted to UTC because it already is UTC. It looks like this: t = '2020-05-29 08:47:39' # this is UTC MyModel( timestamp=t, … ).save() In the database it is stored as 2020-05-29 06:47:39. So it is shown on a template e. g. as 2020-05-29 08:47:39 whereas 2020-05-29 10:47:39 would be correct. settings.py TIME_ZONE = 'Europe/Berlin' USE_TZ = True -
Deploy Django project to heroku NLTK problem
I have a problem when i deploy django project to heroku in nltk package i used nltk.txt but i got application error despite deploying successfully but the problem in nltk packages any help . [nltk.txt][1] -
Create & display subcategories under the multiple parents categories
I am creating a blog by Django framework. In the blog, I have a Post function which I can assign multiple parents categories in that post in the admin page. However Im struggling to create a model that can assign multiple subcategories under the multiple parents categories in admin page. for example, I have 2 parents categories(Tom & Mike). and I have different subcategories under those parents categories. Tom(parents category) |- This is nice (to Post A)(Subcategory) |- This is not nice (to Post B)(Subcategory) Mike(parents category) |- This is cool (to Post A)(Subcategory) |- This is not cool (to Post B)(Subcategory) When the user selects the Parents category e.g. Tom, the user can see subcategories comments to each Post A and B. e.g. Localhost:8000/TOM Show the post and comments related Category TOM Post A - This is cool Post B - This is not cool the below is the model I created for the Post and Parents category. Can anyone advise me how to create a model what I want? and am sorry in advance if my question is difficult to understand for you. from django.db import models class Category(models.Model): name = models.CharField(max_length=20) description = models.TextField(default="") def __str__(self): return … -
Is there a python package to use with django so i can implement an activity feed app in my project
I am using Django 3.0.5 and I want to add activity stream and a notification system to my web application, what is the best way to do that, I have tried activity stream and Stream Framework but is there any other way to do that or a better tutorial than the documentation. -
Django message not working with success message mixin
when am trying to book the order, the success message is not displayed this is my views.py class booking_confirm(CreateView,SuccessMessageMixin, LoginRequiredMixin): form_class = booking_form1 model = Booking template_name = "confirm_booking1.html" success_url = reverse_lazy("Driver:Driverview") def form_valid(self, form,*args, **kwargs): booking = get_object_or_404(Loader_post, pk=self.kwargs.get('pk')) print(form.cleaned_data) bk = form.save(commit=False) bk.user = self.request.user bk.post = booking bk.approve= True bk.save() return super().form_valid(form) def get_success_message(self,cleaned_data): print(cleaned_data) return "Booking successfully completed" this is my html {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} -
How can i make an update view request for my article?
I want to update an existing article.I have already done the perform_create option but i don't know how to do the update.Can anybody help? Models.py class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(UserProfile,on_delete=models.CASCADE, related_name='articles') caption = models.CharField(max_length=250) Views.py class ArticleView(CreateAPIView): serializer_class = ArticleCreateSerializer permission_classes = (IsAuthenticated,) def post(self, request, *args, **kwargs): serializer = ArticleCreateSerializer(data=request.data) if serializer.is_valid(): article = serializer.save(author=self.request.user.profile) serializer = ArticleCreateSerializer(article) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def update(self, request, *args, **kwargs): ?????? -
Adding claims to DRF simple JWT payload
Using djangorestframework_simplejwt library, when POST to a custom view #urls.py path('api/token/', MyTokenObtainPairView.as_view(), name='token_obtain'), #views.py class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer I'm able to get a the following access token eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTkwOTEwNjg0LCJqdGkiOiI3M2MxYmZkOWNmMGY0ZjI3OTY4MGY0ZjhlYjA1NDQ5NyIsInVzZXJfaWQiOjExfQ.5vs0LmNGseU6rtq3vuQyApupxhQM3FBAoKAq8MUukIBOOYfDAV9guuCVEYDoGgK6rdPSIq2mvcSxkILG8OH5LQ By going to https://jwt.io/ I can see the payload is currently { "token_type": "access", "exp": 1590910684, "jti": "73c1bfd9cf0f4f279680f4f8eb054497", "user_id": 11 } So, we can see that the second part of the token is the payload - containing the claims. I've explored how to add more information to the Response body and now would like to know how to customize the Payload data by adding iat claim, username and today's date. -
Django model_to_dict stack overflow crash
In my app, I use a common Base model for all my models. I'v encountered a behaviour I can't explain with the Campus and Hall models: class Base(models.Model): id: int = models.AutoField(primary_key=True, editable=False) class Meta: abstract = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._initial = self.as_dict ... @property def as_dict(self) -> dict: fields = [field.name for field in self._meta.fields] res = model_to_dict(self, fields=fields) return res ... class Campus(Base): name: str = models.CharField(max_length=100) class Meta: verbose_name_plural = "campuses" def __str__(self): return self.name class Hall(Base): name: str = models.CharField(max_length=100) campus: Campus = models.ForeignKey(Campus, on_delete=models.SET_NULL, null=True) def save(self, *args, **kwargs): if self.campus is not None and isinstance(self.campus, str): self.campus = Campus.objects.get_or_create(name=self.campus)[0] super().save(*args, **kwargs) def __str__(self): return f"{self.name}{f' ({self.campus})' if self.campus else ''}" On the admin console, when I try to delete a certain Campus instance, the server crashes. This is a very small part of the (very long) trace: Fatal Python error: Cannot recover from stack overflow. ... Current thread 0x00000bdc (most recent call first): ... File "P:\Python\Coursist\academic_helper\models\base.py", line 142 in as_dict File "P:\Python\Coursist\academic_helper\models\base.py", line 98 in __init__ File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 512 in from_db File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 75 in __iter__ File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 1261 in _fetch_all File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 258 in __len__ … -
At first time If I enter wrong enroll_no error display, but if i enter second time after entering right enroll_no do error
models.py contains code: class Entexaminfo(models.Model): entexamses = ( ("June Session", "June Session"), ("December Session", "December Session"), ) approve_choice = ( ("p", "Pending"), ("a", "Accepted"), ("r", "Rejected"), ) ename = models.CharField(max_length=16, choices=entexamses) enrollno = models.OneToOneField(Student, on_delete=models.CASCADE) #programs = models.ManyToManyField(Programs, related_name='proNames', default=0) program = models.ManyToManyField(Programs, default=0) center = models.ForeignKey(Excenter, on_delete=models.CASCADE) remarks = models.CharField(validators=[max_len_check], max_length=256, default="-") #status = models.BooleanField() status = models.CharField(max_length=1, choices=approve_choice, default="p") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager # for admin pannel to display for correction def __str__(self): return self.ename def get_absolute_url(self): return reverse('show', kwargs={'pk': self.pk}) #For Table Name in DBMS class Meta: db_table = 'entexaminfo' #For Database table name verbose_name = "intexaminfo" #For Database table singular name verbose_name_plural = "intexaminfos" #For Database table plural name ordering = ['created_at'] #For table data sorting views.py contains: def hall_ticket(request): if request.user.is_authenticated: try: query = request.GET['enrollno'] except MultiValueDictKeyError: enrollno = False #query = request.GET['enrollno'] entedetail = Student.objects.filter(enrollNo=query) for obj in entedetail: global id #To avoid 'local variable 'id' referenced before assignment' error message id = obj.id ent1 = Entexaminfo.objects.filter(enrollno=id) esch = Ex_schedule.objects.filter(programs=2) params = {'entedetails': entedetail, 'ent1': ent1, 'query': query, 'esch': esch, 'title': 'Entrance Exam Hall Ticket'} return render(request, 'hall_ticket.html', params) else: messages.info(request, 'You need to Login first.') return redirect('/user/logout') urls.py … -
best place to host an e-commerce website other than heroku [closed]
which is the best place to host an e-commerce website other than heroku -
Django cannot find all my files in static files
I'm totally fresh to django. I downloaded a template to presents a well structured web page. But after I put all the template's file in to static dir then just didn't show any image or run any js css files. Here is my dir: Here is my settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] # URL prefix for static files STATIC_URL = '/static/' # Absolute path to the directory in which static files should be collected STATIC_ROOT = os.path.join(BASE_DIR, 'root') # Additional locations for static files (optional) STATICFILES_DIRS = [os.path.join(BASE_DIR,'static'),] This is what I got at terminal: [31/May/2020 07:55:02] "GET /static/assets/vendor/aos/aos.css HTTP/1.1" 404 1699 [31/May/2020 07:55:02] "GET /static/assets/vendor/owl.carousel/assets/owl.carousel.min.css HTTP/1.1" 404 1786 [31/May/2020 07:55:02] "GET /static/assets/vendor/icofont/icofont.min.css HTTP/1.1" 404 1735 [31/May/2020 07:55:02] "GET /static/assets/vendor/boxicons/css/boxicons.min.css HTTP/1.1" 404 1753 [31/May/2020 07:55:02] "GET /static/assets/vendor/venobox/venobox.css HTTP/1.1" 404 1723 [31/May/2020 07:55:02] "GET /static/assets/vendor/bootstrap/css/bootstrap.min.css HTTP/1.1" 404 1759 [31/May/2020 07:55:03] "GET /static/assets/vendor/jquery/jquery.min.js HTTP/1.1" 404 1726 [31/May/2020 07:55:03] "GET /static/assets/css/style.css HTTP/1.1" 404 1684 [31/May/2020 07:55:03] "GET /static/assets/vendor/bootstrap/js/bootstrap.bundle.min.js HTTP/1.1" 404 1774 [31/May/2020 07:55:03] "GET /static/assets/vendor/jquery.easing/jquery.easing.min.js HTTP/1.1" 404 1768 [31/May/2020 07:55:03] "GET /static/assets/vendor/php-email-form/validate.js HTTP/1.1" 404 1744 [31/May/2020 07:55:03] "GET /static/assets/vendor/waypoints/jquery.waypoints.min.js HTTP/1.1" 404 1765 [31/May/2020 07:55:03] "GET /static/assets/vendor/counterup/counterup.min.js HTTP/1.1" 404 1744 [31/May/2020 07:55:04] "GET /static/assets/img/portfolio/portfolio-9.jpg HTTP/1.1" 404 1732 [31/May/2020 07:55:04] … -
TypeError: UserCreateForm() got an unexpected keyword argument 'initial'
I am new to django and I am developing a social media site following the course and I am facing this weird error when I try to open signup page from the site, which after a lot of search and experiments wasn't able to get away with.Thus, I came here so if anyone could help me. My forms.py file where i think the actual culprit is from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm def UserCreateForm(UserCreationForm): class Meta: fields = ['username', 'email', 'password1', 'password2'] model = get_user_model() def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) self.fields['username'].label = 'Username' self.fields['email'].label = 'Email Address' views.py file from django.shortcuts import render from django.views.generic import CreateView from django.urls import reverse_lazy from . import forms # Create your views here. class SignUpView(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy('login') template_name = 'accounts/signup.html' urls.py file in the application directory i.e. accounts/urls.py from django.urls import re_path from django.contrib.auth.views import LoginView, LogoutView from . import views #code here urlpatterns = [ re_path(r'^login/$', LoginView.as_view(template_name='signin.html'), name='login'), re_path(r'^logout/$', LogoutView.as_view(), name='logout'), re_path(r'^signup/$', views.SignUpView.as_view(), name='signup'), ] full log of error I am facing File "C:\Users\dell\Anaconda3\envs\pyEnv\lib\site-packages\django\views\generic\edit.py", line 133, in get return self.render_to_response(self.get_context_data()) File "C:\Users\dell\Anaconda3\envs\pyEnv\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_ data kwargs['form'] = self.get_form() File "C:\Users\dell\Anaconda3\envs\pyEnv\lib\site-packages\django\views\generic\edit.py", line 33, …