Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't add project to scrapyd
The problem I had is I can't upload my .egg file to scrapyd using curl http://127.0.0.1:6800/addversion.json -F project=scraper_app -F version=r1 egg=@scraper_app-0.0.1-py3.8.egg its returning an error message like this {"node_name": "Workspace", "status": "error", "message": "b'egg'"} So I'm using Django and Scrapy in the same project, and I had this folder structure my_app/ -- apps/ # django apps folder -- crawler/ -- __init__.py -- admin.py -- apps.py -- etc.. -- pages/ -- __init__.py -- admin.py -- apps.py -- etc.. -- my_app/ # django project folder -- __init__.py -- asgi.py -- settings.py -- etc.. -- scraper_app/ # scrapy dir -- scraper_app/ # scrapy project folder -- spiders/ -- abc_spider.py -- __init__.py -- middlewares.py -- pipelines.py -- settings.py -- etc.. -- scrapy.cfg -- manage.py -- scrapyd.conf -- setup.py # setuptools for creating the egg file -- etc.. and here is what my setup.py looks like from setuptools import setup, find_packages setup( name="scraper_app", version="1.0.0", author="Khrisna Gunanasurya", author_email="contact@khrisnagunanasurya.com", description="Create egg file from 'scraper_app'", packages=find_packages(where=['scraper_app']) ) my scrapyd.conf file [scrapyd] eggs_dir = eggs logs_dir = logs logs_to_keep = 5 dbs_dir = dbs max_proc = 0 max_proc_per_cpu = 4 http_port = 6800 debug = off runner = scrapyd.runner application = scrapyd.app.application and my scrapy.cfg content [settings] default = … -
iterating over dynamic content with jquery
var deneme = document.getElementsByClassName("content-holder"); var uzat = document.getElementsByClassName("uzat"); for (var i = 0; i < deneme.length; i++) { var yuksek = deneme[i].offsetHeight; if (yuksek > 250) { deneme[i].style.height = "97px"; uzat[i].style.display = "block" } }; This function finds entries in a page which are longer than 250 px and shrinks them to 97 px, also adds a button "uzat" and when this button is clicked entry gets back to the original size. Now I'm using infinite scroll to load new entries and this function doesn't work on newly loaded entries. I tryed to trigger the function everytime new content is added but it also effected the old entries. Is there anyway to change only the new entries without effecting the old ones? -
how to get value from radio button from html template
i want to access value from radio button without django from only from a html from <div class="form-check ml-3"> <input class="form-check-input" name="{{i.question_date}}" id="1" type="radio" checked> <label class="form-check-label" for="option1"> {{i.option1}} </label> </div> <div class="form-check ml-3"> <input class="form-check-input" name="{{i.question_date}}" id="2" type="radio" checked> <label class="form-check-label" for="option2"> {{i.option2}} </label> </div> <div class="form-check ml-3"> <input class="form-check-input" name="{{i.question_date}}" id="3" type="radio" checked> <label class="form-check-label" for="option3"> {{i.option3}} </label> </div> <div class="form-check ml-3"> <input class="form-check-input" name="{{i.question_date}}" id="4" type="radio" checked> <label class="form-check-label" for="option4"> {{i.option4}} </label> </div> this is views.py def answer_check(request): if request.method=="POST": print(request.POST['1']) return render(request,"index.html") return render(request,"index.html") -
Trying to load certain form if user is authenticated and preload all the information in the database with the user credentials
Trying to load certain form if a user is authenticated and preload all the information in the database but I get this error, most probably something is wrong in forms.py but the idea is that if the user is authenticated they should not go through the process of entering their name and email, they would just have to send the message. It currently works like a charm for non registered users but I never did something like this before for the registered users so I am stuck. forms.py from django import forms from django.forms import ModelForm from .models import Message class NonAuthMessage(forms.ModelForm): class Meta: model = Message fields = "__all__" class AuthMessage(forms.ModelForm): def __init__(self): self.name = user.request.username self.email = user.request.email class Meta: model = Message fields = ["message"] models.py from django.db import models from django.utils import timezone class Message(models.Model): name = models.CharField(max_length=50) email = models.EmailField() message = models.TextField(max_length=3000) date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email class Meta: ordering = ['-date_posted',] views.py from django.shortcuts import render, redirect from .models import Message from .forms import NonAuthMessage, AuthMessage def contact(request): formAuth = AuthMessage() formNonAuth = NonAuthMessage() mess = Message.objects.all() if request.user.is_authenticated: if request.method == "POST": form = AuthMessage(request.POST) if form.is_valid(): form.save() return redirect('contact') … -
"Token contained no recognizable user identification" while creating custom django jwt token
I have created my login view which on successful login returns access token and refresh token..Then on accessing any view the user have to attach this access token as bearer token in every url.. I have manually created my access token and refresh token . But i have inherited restframework_simplejwt.views.TokenRefreshView which will return an access token for each refresh token.. All this is working fine... Now i have used permission_classes((IsAuthenticated)) above my home_api_view and when i paste the access token over the homepage url it says "Token contained no recognizable user identification" my views.py @api_view(['POST','GET',]) @permission_classes([]) def login_view(request): username = request.data.get("username") password = request.data.get("password") response = Response() user = authenticate(request,username=username,password=password) if user is not None: login(request,user) user = User.objects.filter(username=username).first() #This will return directly the username . If you dont use .first() it will return a dictionary access_token = Generate_Access_Token(user) refresh_token = Generate_Refresh_Token(user) response.data={'refresh_token':refresh_token,'access_token':access_token} return response else: return HttpResponse("USERNAME or PASSWORD ERROR!!!") utils.py` def Generate_Access_Token(user): access_token_payload = { 'token_type':'access', 'exp':datetime.datetime.utcnow()+datetime.timedelta(days=0,minutes=5), 'jti': uuid4().hex, 'user':user.username, 'id':user.id, 'iat':datetime.datetime.utcnow(), } access_token = jwt.encode(access_token_payload,settings.SECRET_KEY,algorithm='HS256').decode('utf-8') return access_token def Generate_Refresh_Token(user): refresh_token_payload = { 'token_type':'refresh', 'id': user.id, 'exp' :datetime.datetime.utcnow()+datetime.timedelta(days=7), 'iat':datetime.datetime.utcnow(), 'jti': uuid4().hex } refresh_token = jwt.encode(refresh_token_payload,settings.SECRET_KEY,algorithm='HS256').decode('utf-8') return refresh_token -
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.