Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Real-time tracking with Google assets tracking
I want add real-time tracking for our app Courier. What ready-made solutions are available for such task? Found Google assets tracking but nothing is clear from the documentation. Can i integrate google assets tracking without google maps? -
set_wakeup_fd only works in main thread Python 3.8.2. Django 3.0.6 apache v3.2.4
203/5000 Hello I have a problem with error set_wakeup_fd only works in the main thread. The application works but every now and then this error was found. I know that there are several answers to this problem, but it does not help me. Python 3.8.2. Django 3.0.6 apache v3.2.4 Windows server 2012 ValueError at /art_chem/ set_wakeup_fd only works in main thread Request Method: GET Request URL: http://localhost/art_chem/ Django Version: 3.0.6 Exception Type: ValueError Exception Value: set_wakeup_fd only works in main thread Exception Location: C:\Python38\lib\asyncio\proactor_events.py in __init__, line 632 Python Executable: C:\xampp\apache\bin\httpd.exe Python Version: 3.8.2 Python Path: ['C:\\Users\\k.kowalski_1\\Desktop\\Magazyn', 'C:\\Python38\\python38.zip', 'C:\\Python38\\DLLs', 'C:\\Python38\\lib', 'C:\\xampp\\apache\\bin', 'C:\\Python38', 'C:\\Python38\\lib\\site-packages'] -
Django Cassandra Engine multiple primary keys
I have a model with multiple partition and clustering keys as follows: from django_cassandra_engine.models import DjangoCassandraModel from cassandra.cqlengine import columns class Event(DjangoCassandraModel): assessment_id = columns.UUID(partition_key=True) type = columns.Text(partition_key=True) fire_time = columns.DateTime(primary_key=True, default=now, clustering_order="DESC") id = columns.UUID(primary_key=True, default=uuid.uuid4, clustering_order="ASC") data = columns.Map(key_type=columns.Text, value_type=columns.Text, default=dict, index=True) on running python manage.py sync_cassandra I get the Runtime error: On Django Cassandra Models with more than one primary_key field, The model <class 'ws.models.Event'> must specify class Meta attribute 'get_pk_field'. E.g. class Meta: get_pk_field='id' So that Django knows which primary key field to use in queryies such as Model.objects.get(pk=123) -
Gunicorn : ModuleNotFoundError: No module named 'insitu.wsgi'
I'm following this tutorial to deploy a django application https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 I'm facing a problem at gunicorn step, here is the log : Oct 15 06:31:09 ubuntu-s-1vcpu-1gb-lon1-01 gunicorn[50835]: ModuleNotFoundError: No module named 'insitu.wsgi' Oct 15 06:31:09 ubuntu-s-1vcpu-1gb-lon1-01 gunicorn[50835]: [2020-10-15 06:31:09 +0000] [50835] [INFO] Worker exiting (pid: 50835) Oct 15 06:31:09 ubuntu-s-1vcpu-1gb-lon1-01 gunicorn[50833]: [2020-10-15 06:31:09 +0000] [50833] [INFO] Shutting down: Master Oct 15 06:31:09 ubuntu-s-1vcpu-1gb-lon1-01 gunicorn[50833]: [2020-10-15 06:31:09 +0000] [50833] [INFO] Reason: Worker failed to boot. Here is my gunicorn.service file : [Unit] Description=gunicorn daemon After=network.target [Service] User=djangoadmin Group=www-data WorkingDirectory=/home/djangoadmin/insitu-live ExecStart=/home/djangoadmin/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/djangoadmin/insitu-live/insitu.sock insitu.wsgi:application [Install] WantedBy=multi-user.target I don't know why the module insitu.wsgi is not found, because it exists. Can someone help me on that ? Thank you -
How to remove a permission from model?
So I had a permission in my model class like this: class Meta: permissions = (("can_send_messages", "Can send messages"),) This automatically created a migration that does this: operations = [ migrations.AlterModelOptions( name='organization', options={'permissions': (('can_send_messages', 'Can send messages'),)}, ), ] Now I removed class Meta and the permission from my model class. How do I make a migration that will undo that automatically created migration? -
How to set and print the value of json object in postgresql?
What I have done till now is : DO $do$ DECLARE namz Text; jsonObject json = '{ "Name": "Kshitiz Kala", "Education": "B.Tech", "Skills": ["J2EE", "JDBC", "Html"] }'; BEGIN SELECT jsonObject->'Name' into namz; select namz; END $do$ I am not finding any success here. actual problem is I am passing a json Object to a stored procedure which will store the data in three different table 1) user table contains user_id, user_name, user_edu. 2) skill table contain skill_id, skill_name. 3) user_skill table contain id, user_id, usr_skill_id. This is the json object I am passing from Django application {"Name": "Kshitiz Kala", "Education": "B.Tech", "Skills": ["J2EE", "JDBC", "Html"]} -
Page not found (404) is reporting
There is 'Page not found(404)' error that has been showing since yesterday but before that everything was working great. The program was running on the same URL path but now it isn't, please tell your suggestions. Thank You! urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from Platform import views urlpatterns = [ path('/admin/', admin.site.urls), path('/Home/', views.home, name='home'), path('/blog/', include('blog.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The Error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in Portfolio.urls, Django tried these URL patterns, in this order: /admin/ /Home/ [name='home'] /blog/ ^media/(?P<path>.*)$ The empty path didn't match any of these. -
multiple django forms validates but not submit
my form validates the required field but does not submit when i click create. I am using ModelForm for Recipe and modelformset_factory for Ingredients. Formset for Ingredients because recipe can have many ingredient. Here is my code: ----------------------------------# forms.py---------------------------------- from django.forms import modelformset_factory from .models import Recipe, Ingredient class RecipeModelForm(forms.ModelForm): class Meta: model = Recipe fields = ['name', 'time_to_cook', 'instruction'] labels = { 'name': 'Recipe Name', 'time_to_cook': 'Time to cook', 'instruction': 'Instruction' } widgets = { 'name': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Recipe Name here' } ), 'time_to_cook': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter time here (10 min)' } ), 'instruction': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter instruction here' } ) } IngredientFormset = modelformset_factory( Ingredient, fields=['name'], labels={ 'name': 'Ingredient Name' }, min_num=1, validate_min=True, extra=0, widgets={ 'name': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Enter Ingredient Name here', 'required': True } ) } ) --------------------------# views.py-------------------------- from django.shortcuts import render, redirect from django.views.generic import ListView from .models import Recipe, Ingredient from .forms import RecipeModelForm, IngredientFormset def create_Recipe_with_ingredients(request): template_name = 'recipe/create.html' if request.method == 'GET': recipeform = RecipeModelForm(request.GET or None) formset = IngredientFormset(queryset=Ingredient.objects.none()) elif request.method == 'POST': recipeform = RecipeModelForm(request.POST) formset = IngredientFormset(request.POST) if recipeform.is_valid() and formset.is_valid(): recipe = recipeform.save() for form in formset: ingredient … -
How to ping daphne server
I have setup daphne server in docker container, how can I ping this server to make sure everthing goes fine? I exposed the Django app ports in 8000 and 9000 and then using command: python manage.py runserver 0.0.0.0:8000 daphne -b 0.0.0.0 -p 9000 config.asgi:application to run both dev servers, but not working. -
My query in Django shell is working fine but not able to work View file
I have some condition in django modelviewset class:Group by ,Filter and greater than StoreClosingStock.objects.filter(CLOSING_STOCK__gte=1).values('ITEM_CODE').annotate(CLOSING_STOCK =Sum("CLOSING_STOCK")) The above query in shell script working fine .When i move to my view file its not working . This is my Modelviewset class class StoreClosingViewset(viewsets.ModelViewSet): queryset = StoreClosingStock.objects.all() serializer_class = StoreClosingStockSerializer filter_backends = [SearchFilter, OrderingFilter] search_fields = ['ITEM_CODE', 'CLOSING_STOCK'] def get_queryset(self): queryset=StoreClosingStock.objects.filter(CLOSING_STOCK__gte=1).values('ITEM_CODE').annotate(CLOSING_STOCK =Sum("CLOSING_STOCK")) return queryset Please check out the Same problem which i posted statckoverflow -
Pagination in DetailView with context? [django]
I made comment and comments in Article(DetailView) How can I make paginations this comments in DetailView. I have tried many options but without succes... VIEWS: class ArticleDetailView(FormMixin, HitCountDetailView): template_name = 'news/article_detail.html' model = Article count_hit = True form_class = CommentForm def get_success_url(self): pk = self.kwargs["pk"] slug = self.kwargs['slug'] return reverse_lazy('news:article_detail', kwargs={'pk': pk, 'slug': slug}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = ArticleComment.objects.filter(article_id=self.object.id).all() context['comments_number'] = ArticleComment.objects.filter(article_id=self.object.id).count() context['form'] = CommentForm() return context def form_valid(self, form): form.instance.article = self.object form.instance.author = self.request.user form.save() messages.success(request=self.request, message="KOMENTARZ ZOSTAŁ DODANY POPRAWNIE") return super().form_valid(form) def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) -
QBO with Django Open Id, Callback Anonymous User
I have hooked up Django to QBO (QuickBooks Online) and seem to be having trouble with 1 random account. I am using the Intuit oauth Python library with Django. For this one particular account, the request gets sent off to QBO, login and connect. Upon going back to my application, this callback is invoked. The request appears to be in some odd state because the logs tell me that request.user is an AnonymousUser. Also before I commented it out, this would actually fail on the state_tok check. It almost seems like the session is randomly getting cleared on Chrome browser, or the request is getting lost. Log: File "/app/public/views.py", line 867, in acccounting_callback business_account = BusinessAccount.objects.get(user=request.user) ... TypeError: 'AnonymousUser' object is not iterable Model: from django.contrib.auth.models import User ... class BusinessAccount(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) ... View: def acccounting_callback(request): auth_client = AuthClient( settings.CLIENT_ID, settings.CLIENT_SECRET, settings.REDIRECT_URI, settings.ENVIRONMENT, state_token=request.session.get('state', None), ) state_tok = request.GET.get('state', None) error = request.GET.get('error', None) print('callback') for key, value in request.session.items(): if '_auth' not in key: print('{} => {}'.format(key, value)) if error == 'access_denied': return redirect('business_account') if state_tok is None: return HttpResponseBadRequest() elif state_tok != auth_client.state_token: return HttpResponse('unauthorized', status=401) business_account = BusinessAccount.objects.get(user=request.user) ... -
Django js translation gives: warning: unterminated string
I am trying to translate js code in django translation. The problem is, I get a warning saying unterminated string, but I could not relate with the warning message. Still, it makes the translation, but there is some irregularity ie, it skips some of the gettext. When I enterred the following command: django-admin makemessages -l ne -d djangojs This is the exception from translator: ./static/js/comment.js:356: warning: unterminated string processing locale ne comment.js 352 edit_div.fadeOut(1000, 'linear', function(){ 353 this.remove(); 354 if(!($('.comment-of').length)){ 355 $("#comments").html('<div class="comment-of no-comment dis-color">'+gettext('No Comment')+'</div>'); 356 } 357 }); -
Using Custom Admin Form Starts to Show Editable Password Field and No Password Reset Form Link
When I use a custom Admin form the password field hash becomes editable and it is missing the password reset form like in this example image: https://cloud.githubusercontent.com/assets/4695692/3880996/d27b1d22-2189-11e4-8d50-09ce60a18946.png. How can I make the password field look like in the image? Admin.py: class ProfileAdmin(UserAdmin): form = ProfileAdminForm fieldsets = ( (None, {'fields': ('username', 'password')}), (_('Personal info'), {'fields': ('first_name', 'last_name', 'email', 'timezone', ...)}), (_('Permissions'), {'fields': ('is_verified', 'is_active', 'is_staff', 'is_superuser', ...)}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), (_('Subscription type'), {'fields': ('is_premium', ... )}), ) list_display = ['id','username', 'email', 'date_joined', 'is_verified', ...,] actions = [....] def changelist_view(self, request, extra_context=None): # Aggregate new subscribers per day chart_data = ( Profile.objects.annotate(date=TruncDay("date_joined")) .values("date") .annotate(y=Count("id")) .order_by("-date")[:30] ) # Serialize and attach the chart data to the template context as_json = json.dumps(list(chart_data), cls=DjangoJSONEncoder) extra_context = extra_context or {"chart_data": as_json} # Call the superclass changelist_view to render the page return super().changelist_view(request, extra_context=extra_context) admin.site.register(Profile, ProfileAdmin) Forms.py: class ProfileAdminForm(forms.ModelForm): class Meta: model = Profile fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['native_language'] = forms.ModelMultipleChoiceField( required=False, queryset=Language.objects.all()) self.fields['studying_language'] = forms.ModelMultipleChoiceField( required=False, queryset=Language.objects.all()) def clean_native_language(self): languages = self.cleaned_data['native_language'] language_list = [lang.id for lang in languages] return language_list def clean_studying_language(self): languages = self.cleaned_data['studying_language'] language_list = [lang.id for lang in languages] return language_list -
Need help for django live Graph plotting
I am new in django & python. Trying to make a Live generic graph plotting app. The data are coming from Mysql server(Phpmyadmin table). For that I'm badly in need of a documentation which will help me to make the project properly. Thanks for your attention . -
How can i validate DateTimeField using custom validators in models.py in django?
In models.py -> def validate_date_time(value): if value > timezone.now().date(): raise validationError(" date/time cannot be in past") Scheduled_date_time=models.DateTimeField(validators=[validate_date_time]) I am getting error message : Enter a Valid date/time. Plz help .... -
Python global variable not working in Django
I'm passing kwargs from a function to another function and declare the variable as global to use it in query but not working. def do_stuff_then_call_taxman(**kwargs): employee_id = kwargs['employee_id'] ''' doing stuff''' taxman(employee_id=employee_id) def taxman(**kwargs): global employee_id #<--- ATTENTION HERE employee_id = kwargs['employee_id'] qs = Employee.objects.filter(id=employee_id).values() #Error occurs here for global_variable in qs: '''variables''' I can't figure out what I'm doing wrong. Help will be appreciated. -
Unable to symlink '/usr/bin/python3' to '/home/ubuntu/my-env/bin/python3'
I have Django application which is getting deployed on Code Deploy. In logs i get an error saying 'Unable to symlink '/usr/bin/python3' to '/home/ubuntu/my-env/bin/python3' Any clues anyone, how to fix this issue,,..? -
Django click streams and Django packages in general
I am really new to coding and Django. I had two questions. I want to know more about Django clickstreams and if it is possible to achieve it? I researched using google. However the max I found was this Django package called django-clickstreams..however I don't see any updates around this. I wanted to know if there is a way to achieve user actions on a site using django and If so, is there any direction you can point me to? This brings me to the question around Django packages. Can they be trusted once they are added to your project ? Or there are any risks? Thank you -
Redirect to email_confirm.html after signup using django-allauth
I have a custom signup page and I would like to send email verification after user creation. However, I would like to redirect users to a different template after signup which shows them a message that they need to verify their email address. Currently my view is: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) #user.is_active = True user.save() send_email_confirmation(request, user, True) else: form = SignUpForm() return render(request, 'main/signup.html', {'form': form}) How can I redirect users to a the template verification_sent.html? I have also implemented a method for users to change the email address if incorrect but I cannot find how I can integrate that in my verification_sent.html template. -
is there a way to sett return value to an variable in django
I have an custom template tag with something like this: @register.simple_tag def getLikesByUser(likedFilter, loggedInUserID): likedPeople = likedFilter personLoggedIn = loggedInUserID for personLiked in likedPeople: if personLoggedIn == personLiked.id: return True return False this will return true or false in my template, is there an option to set this return to an variable in my template? this is how a call this: {% getLikesByUser Post.likes.filter request.user.id %} I would like to have this in a variable so I can further check if is true show button if false don't. thanks -
Django - Templates and Views: Adding a button that takes you to Checkout
I'm very new to Django and was wondering how to add a button to each row for the following table. When pressing the button, it should take add it to a cart. Here's some of my code: In templates: {% extends "bobs_cafe/base.html" % {% block content %} <br> <div class="row"> <div class="col-md"> <div class="card card-body"> <h5>Products</h5> </div> <div class="card card-body"> <table class="table"> <tr> <th>Product</th> <th>Price</th> <th><button class="btn btn-primary" type="submit">Button</button></th> </tr> {% for product in products %} <tr> <td>{{product.name}}</td> <td>{{product.cost}}</td> </tr> {% endfor %} </table> </div> </div> </div> <br> {% endblock content %} In views: class CatalogView(ListView): model = Item template_name = 'bobs_cafe/menu.html' context_object_name = 'products' class ProductDetailView(DetailView): model = Product This is my attempt so far: 1st attempt Any suggestions for what to do? Thanks -
Is any way to share variables among view in django
How to share an object among different views in django? I create a instance and wanna use it in another view when a different request coming. for example: def view1(request): a=A() def view2(request): #here I wanna use a a.run('test') -
Django / Python "frozen importlib._bootstrap" error - is this a generic error messaging?
I encountered the following error messages when trying to run Django manage.py runserver. Turns out I had forgotten to add a variable 'LOG_FILE' to an imported custom config file. remote: Traceback (most recent call last): remote: File "/home/myproject/myproject/manage.py", line 21, in <module> remote: main() remote: File "/home/myproject/myproject/manage.py", line 17, in main remote: execute_from_command_line(sys.argv) remote: File "/home/myproject/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/home/myproject/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 345, in execute remote: settings.INSTALLED_APPS remote: File "/home/myproject/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 76, in __getattr__ remote: self._setup(name) remote: File "/home/myproject/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 63, in _setup remote: self._wrapped = Settings(settings_module) remote: File "/home/myproject/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 142, in __init__ remote: mod = importlib.import_module(self.SETTINGS_MODULE) remote: File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 1006, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 983, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked remote: File "<frozen importlib._bootstrap>", line 677, in _load_unlocked remote: File "<frozen importlib._bootstrap_external>", line 728, in exec_module remote: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed remote: File "/home/myproject/myproject/config/settings.py", line 32, in <module> remote: LOG_FILE = django_config["LOG_FILE"] remote: KeyError: 'LOG_FILE' The clue that it was about the config 'LOG_FILE' variable is the last 3 lines: remote: File "/home/myproject/myproject/config/settings.py", line 32, in <module> remote: LOG_FILE … -
Django allauth redirect users that signup to email confirmation page by tracking their session
I have implemented an application which uses django-allauth. When users initially signup, it asks them for email verification on the page. Without authentication them (It doesn't authentication after they have signup. My intention is that based on the user session, the website will redirect users to an html page that they can change their email address (Something that Facebook does on signup and keeps track of you when you recently signup). My sign up view is: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) #raw_password = form.cleaned_data.get('password1') #user = authenticate(username=user.username, password=raw_password) user.is_active = False user.save() send_email_confirmation(request, user, True) return render(request, 'account/custom_snippets/verification_sent.html', {'email': user.email}) else: form = SignUpForm() return render(request, 'main/signup.html', {'form': form}) Now I would always like to redirect users to verification_sent.html if they recently signed up and the application is waiting on for user to verify their app. My email update view for newly signed users is: def update_user_email_on_verification(request): data = dict() user = request.user if request.method == "POST": new_email = request.POST.get('email') user.add_email_address(request, new_email) return render(request, 'account/custom_snippets/verification_sent.html', {'email': new_email}) else: context = { 'email':'' } data['form'] = render_to_string('account/email/update_email.html',context,request=request) return JsonResponse(data) my login view: @user_passes_test(lambda user: not user.username, login_url='/home/', redirect_field_name=None) def user_login(request): message = …