Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
static file locate issue on cpanel
my project is working fine on local but on live server(godaddy) its not getting static folder. urls are just admin/ [name='homepage'] login/ [name='login'] ^media\/(?P<path>.*)$ url for static not even located here . my settings.py static settings are STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] which are working on local perfectly . and location for static folder is here in image , just a static folder placed. -
Django project celery and django-filter causing errors
I had a working django project, but I started getting errors with celery after I added django-filter to my requirements file. I'm using python 3.7 and here's the list of installed packages w/ versions: Django-3.0.7 amqp-2.6.0 asgiref-3.2.7 billiard-3.6.3.0 celery-4.4.4 certifi-2020.4.5.1 chardet-3.0.4 django-bootstrap3-12.1.0 django-celery-results-1.2.1 django-filter-2.2.0 djangorestframework-3.11.0 idna-2.9 importlib-metadata-1.6.0 kombu-4.6.10 ovirt-engine-sdk-python-4.4.3 psycopg2-2.8.5 pycurl-7.43.0.5 python-gitlab-2.2.0 pytz-2020.1 redis-3.5.3 requests-2.23.0 six-1.15.0 sqlparse-0.3.1 urllib3-1.25.9 vine-1.3.0 zipp-3.1.0 I decided to remove my code that uses filtering and just left the pip install for the package, and I still saw the same errors. Below is a pertinent snippet, but I can add the whole trace if necessary. celery-beat_1 | [2020-06-04 18:11:33,145: CRITICAL/MainProcess] beat raised exception <class 'ModuleNotFoundError'>: ModuleNotFoundError("No module named 'future'") celery-beat_1 | Traceback (most recent call last): celery-beat_1 | File "/usr/local/lib/python3.7/site-packages/kombu/utils/objects.py", line 42, in __get__ celery-beat_1 | return obj.__dict__[self.__name__] celery-beat_1 | KeyError: 'scheduler' celery-beat_1 | celery-beat_1 | During handling of the above exception, another exception occurred: celery-beat_1 | celery-beat_1 | Traceback (most recent call last): celery-beat_1 | File "/usr/local/lib/python3.7/site-packages/kombu/utils/objects.py", line 42, in __get__ celery-beat_1 | return obj.__dict__[self.__name__] celery-beat_1 | KeyError: 'backend' . . . celery-beat_1 | [2020-06-04 18:11:33,161: WARNING/MainProcess] File "/usr/local/lib/python3.7/site-packages/celery/backends/base.py", line 10, in <module> celery-beat_1 | [2020-06-04 18:11:33,161: WARNING/MainProcess] from future.utils import raise_with_traceback celery-beat_1 | [2020-06-04 … -
How do I load YAML seed data for a many-to-many field?
I'm using Django 2.2 and Python 3.7. I have the below model. Notice the "ManyToMany" addresses field ... class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType) addresses = models.ManyToManyField(Address) enabled = models.BooleanField(default=True, null=False) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) web_site = models.TextField() In my seed file, I have sturctured the data like below. The "1" in the "addresses" column, is the primary key of an address that already exists in the database (MySql 8) ... - model: directory.coop pk: 1 fields: name: "1871" types: - ['Coworking Space'] addresses: - [ 1 ] enabled: True phone: email: web_site: "http://www.1871.com/" However, when I try and load the seed data, it dies with an "["'[1]' value must be an integer."]: (directory.coop:pk=1) field_value was '[1]'" error. Below is teh complete trace. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Users/davea/Documents/workspace/chicommons/maps/web/directory/management/commands/docker_init_db_data.py", line 13, in handle call_command('loaddata', 'directory/fixtures/seed_data.yaml') File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 148, in call_command return command.execute(*args, **defaults) File … -
How to apply different css styles to two different form elements on the same page?
I am trying to create a web page with a search bar that has it's own styling at the top and then a form later on in the page using django and crispy forms. Currently, the styling for my search bar applies to the styling for my form, and I don't want that. I would like to use bootstrap crispy forms to style the form and my own custom css to style the search bar. (The search bar is coded as a form with input.) I have tried reordering the links in the head of my html, bootstrap first, search bar second, and the other way around, and it didn't affect anything rather than screw up the positioning of my search bar. I have tried wrapping both forms in divs with seperate ids and seperate classes, and it also didn't work. I have tried giving an id to my custom search bar form. I am aware of CSS Specificity. I'm not sure how to make it happen so that I can completely separate the two. Help is appreciated. relevant html: <head> ... <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'assets/css/main.css' %}" /> … -
POST request to Django Model Formset with Vuejs front-end
I am using Django to build a back-end of my project and Vuejs to build the front-end. I have defined my models in Django and have used Django forms to save data to the models. For a single form, I just pass a JSON object in the body of the POST request. This works perfectly fine. But now I need to save multiple records at the same time. I found that Django model formsets can do this. However, I am not able to figure out how to format the POST request. The Django documentation assumes that I'll be using Django templates (which is quite annoying), and therefore says nothing about the format of the request itself. The application is an API documentation tool and I need to allow the user to define the params of the API. As of now, I have the following: from django.forms import modelformset_factory from docs.models import ApiParams ParamsFormSet = modelformset_factory(ApiParams, exclude=('param_id',)) def create_params(request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) formset = ParamsFormSet(body) instaces = formset.save() return HttpResponse(instances) I called this API with the following data: [ { "api": 2, "param_name": "param1", "param_type": "string", "param_required": true, "param_sample": "param" }, { "api": 2, "param_name": "param2", "param_type": "numeric", … -
Fieldsets don't do anything in admin django
I'm learning Django and found that we can use fieldsets to customise the way admin creation form looks like. Here is the code I'am using: class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ('email', 'age', 'is_staff', 'is_active',) list_filter = ('email', 'age', 'is_staff', 'is_active',) fieldsets = ( ('Advanced options', { 'classes': ('wide',), 'fields': ('email', 'age', 'is_staff', 'is_active',), }), ) admin.site.register(CustomUser, CustomUserAdmin) Here is the result: As you can see this "fieldsets" does nothing for this creation page. And if I completely remove this "fieldsets" nothing will change. What I did wrong here? I want my fieldsets work. Thank you! -
Best way to deploy small Django local website
I have used lock down in UK to develop a website as a front end to my CCTV and home automation systems. It uses Django, Celery (beat and workers), ffmpeg, channels and Redis. I have built it in a virtual environment on a 4g Pi4. I need to host locally as the Pi controls hardware directly. It was hard work but it all works well “in development”. Given Daphne can act as a server, I decided that I would simply use my development code directly as a production version by daemonising with systemd. I thought I had done all the hard work developing the code. I now find that deploying to production causes even more headaches. I have paused as I am no longer confident I am going in the right direction. I just want a simple set up that works on a Pi4. I want to reboot reliably. I want to be able to easily see which services have crashed, if any. I would like to be able to easily examine logs. I would like to be able to easily update Django code and update the production. What are your recommendations for locally hosted small but reasonably complex production … -
Django Ajax request returns no HttpResponse
Hi I am currently trying to improve my django project by adding ajax functionality to avoid the page from being reloaded everytime I like or comment a post of my blog. First I have added the functionality to give likes and it worked very well! However, after I have added the similar functionality for my comments, I am getting the following error for both (like and commenting function): When I like a post: The view feed.views.post_like didn't return an HttpResponse object. It returned None instead. When I create a comment: The view feed.views.comment_create didn't return an HttpResponse object. It returned None instead. I have added my jquery code in my base.html file, the upper part is for likes, the lower for creating comments: <script type="text/JavaScript"> // JQuery Event Handler $(document).ready(function(event) { $(document).on('click', '#like', function(event){ event.preventDefault(); // Primary Key from form is the value of the button! var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: '{% url 'post-likes' %}', data: {'post_id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}' }, dataType: 'json', success: function(response){ $('#like-section').html(response['form']); console.log($('#like-section').html(response['form'])); }, error: function(rs, e){ console.log(rs.responseText); }, }); }); }); $(document).on('submit', '.comment-form', function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: $(this).attr('action'), data: $(this).serialize(), dataType: 'json', success: function(response) { $('#comment-section').html(response['form']); console.log($('#comment-section').html(response['form'])); }, … -
Serve static folder in Django
from django.urls import path from django.views.generic import TemplateView from server import api urlpatterns = [ path('admin/', admin.site.urls), path('api/', api.site.urls), path('index.html', TemplateView.as_view(template_name='index.html')) ] So I am currently serving path('index.html', TemplateView.as_view(template_name='index.html')). I instead would like to serve all html files in my template folder without having to specify each one. I have my react frontend being output to my template folder. I would like to serve that entire folder rather than having to explicitly declare each path. So for example my folder: templates/ index.html second.html auth/ login.html register.html I want all those to be served matching the file/folder name so: index.html = /index.html second.html = /second.html login.html = /auth/login.html register.html /auth/register.html How am I able to just serve the entire folder without explicitly declaring each file and that path? -
Django , handling file field( mp3 files)
My Django Rest Framework app have mp3 file field as mentioned in the below model. I upload mp3 files from admin side. When I send GET request for mp3 files in frontend , it downloads in browser without issues. but shows some error in terminal. AttributeError: 'NoneType' object has no attribute 'split' Should I use any parser to retrieve audio files from server ? MODELS.PY from django.db import models class Music(models.Model): ... track = models.FileField(upload_to='tracks') -
Cannot resolve keyword 'is_active' into field (Django custom user model)
I am using a custom user model: class User(AbstractBaseUser): email = models.EmailField(verbose_name="email", unique=True, max_length=255) first_name = models.CharField(max_length=30, blank=True, null=True) surname = models.CharField(max_length=30, blank=True, null=True) active = models.BooleanField(default=True) #can they login? staff = models.BooleanField(default=False) #staff user non superuser admin = models.BooleanField(default=False) #superuser date_joined = models.DateTimeField(auto_now_add=True) And a view for giving users the possibility of resetting the password: urls: from django.contrib.auth import views as auth_views [...] path('password_forgotten/', auth_views.PasswordResetView.as_view(template_name='registration/password_forgotten_form.html'), name='password_forgotten_form'), Template <form method="POST" class="form-signin">{% csrf_token %} <h1 class="h3 mb-3 font-weight-normal">Reset password</h1> <input name="email" class="form-control" placeholder="Email address" type="email" id="id_email" required="true"> <button class="btn btn-lg btn-primary btn-block" type="submit">Send reset email</button> </form> With Django 3, I get Cannot resolve keyword 'is_active' into field (Django custom user model) when I hit submit. The curious thing is that if I add a is_active field to my user model it gets ignored by my migrations. Adding a slightly different field name, like is_activeT, works. Is is_active a protected field, or something like that? How can I solve my issue? A property won't do it. I'm aware of this: https://code.djangoproject.com/ticket/22192 . But then, Django just ignores if I add a is_active field, even if I add the AddField function directly in my migrations file; it'll be silently deleted in the next … -
Async calls not working from sync code in Django channels
I am working on an app that uses Django channels. My client is a flutter mobile application. So it needs to send token along the request. I am using restframework_jwt for authentication. In the consumers.py, I am trying to decode the token and get the user out of it. I tried two different ways but each shows a different behavior. First I tried this way: token_header = dict(self.scope['headers'])[b'authorization'].decode().split() token = token_header[1] result = jwt.decode(token, settings.SECRET_KEY) username = result['username'] user = self.get_obj(username) whereas get_obj() is defined below as: @database_sync_to_async def get_obj(self, user): return User.objects.channel_get(user) now the issue is that when I print user, returned from get_obj(), it returns this : "<coroutine object SyncToAsync.__call__ at 0x0000015447FE21C8>" where is it not returning user instead and what am I missing? The second way I tried was : token_header = dict(self.scope['headers'])[b'authorization'].decode().split() payload = {'token': token_header[1]} valid_data = await sync_to_async(VerifyJSONWebTokenSerializer().validate)(payload) and it should return : {'token': <token>, 'user': <user_obj>} but instead it returns that same payload. Can anyone tell me where am I going wrong? -
how do I fix (key error) when registration?
I try to create a user registration when a user is signing up he has to moves to the last section which called "complete register". I thought that mission is done by session I need to know if using a session is true in this case or not. if using a session is good how can I save the data from the first form because I get every time the key error? I'm sure the save method in complete_register function is wrong but I have no any idea how can I continue to complete this mission. views.py from django.shortcuts import render, redirect from .forms import RegistrationForm, CompleteRegisterForm from importlib import import_module from django.conf import settings def register(request): if request.method == "POST": user_form = RegistrationForm(request.POST) if user_form.is_valid(): user_form.save(commit=False) SessionStore = import_module(settings.SESSION_ENGINE).SessionStore user_session = SessionStore() user_session['continue_form'] = user_form.clean() # user_session.create() return redirect("account:complete-register") else: error_msg = "something went wrong" return render(request, "account/registration.html", {"user_form": user_form, "error_msg": error_msg}) else: user_form = RegistrationForm() return render(request, "account/registration.html", {"user_form": user_form}) def complete_register(request): if request.method == "POST": # get the rest of data by session user_session = request.session complete_form = CompleteRegisterForm(request.POST) if complete_form.is_valid(): form = user_session['continue_form'].save() complete_form.save() return redirect("music:albums") else: error_msg = "something went wrong" context = {"complete": complete_form, … -
css is not connecting to html in python django
css is not connecting to html in python django. here is my templates/index.html file content <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %}BareTalk{% endblock %}</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> </head> <body> <header> <input type="text" id="search-question" placeholder=" Search"> <img src="search.png" id="search-img"> </header> <br> <br> {% for q in question_list %} <div id="question-log"> <p>Rating: {{ q.rating }}</p> <p id="title">{{ q.title }}</p> <p>{{ body }}</p> </div> {% endfor %} <script src="script.js"></script> </body> </html> and this is my templates tree templates (folder) f (folder) index.html style.css the html is working, but css in not :( -
django arrayfield saving a array item containing comma
I have a django model that has a postgres array field ArrayField(blank=True, default=list, base_field=CICharField(max_length=200, blank=True)) There is also a corresponding admin page for this model where I can update field this in the regular case, but If for example I want to save the field as ['foo,bar', 'baz'] this is not possible since django seems to be splitting always by comma. I tried saving with "foo,bar",baz thinking csv rules but that didn't work out either. Is there any workaround to achive this in django admin ? -
Django unable to access with JQuery on generated HTML
sorry for the long post. I generated some HTML code with django template tag. Template tag look like this : @register.simple_tag def api_render() : return mark_safe(Loader().render()) The template look like this : <div id='{{ "demo"|api_register:"/api/demo/demo.json" }}'> </div> {% api_render %} <script src="{% static "/jquery/dist/jquery.min.js" %}"></script> <script src="{% static "/api/js/api.js" %}"></script> Final result look like this : <body> <div id="a28207e8cade58babd2bf80d"> </div> <div id="#api"> <div data-dja-id="a28207e8cade58babd2bf80d" data-dja-slug="/api/demo/demo.json" data-dja-event="click" data-dja-suc="demo_click_success" data-dja-err="demo_click_error"></div> </div> <script src="/static/jquery/dist/jquery.min.js"></script> <script src="/static/api/js/api.js"></script> </body> But when I'am trying to access to the div with the id #api I'm not abble to do it: Does someone know how can I solve this? -
Why i am unable to fetch data on the template
What mistake in my code anybody tell me if you can catch my mistake so please inform me i am unable to fetch data on template ............Please tell me pppppppppppppppppppppppppppppppppppp................................................................. views.py def userprofile(request,username): user=User.objects.filter(username=username) if user: user=user[0] profile=Profile.objects.get(user=user) post=getPost(user) bio=profile.bio conn=profile.connection follower=profile.follower following=profile.following user_img=profile.userImage print(user) print(bio) print(conn) print(follower) print(following) print(user_img) print(user) data={ 'user':user, 'bio':bio, 'conn':conn, 'follower':follower, 'following':following, 'userImg':user_img, 'posts':post } print(data) return render(request,'userview/userProfile.html') else: return HttpResponse(" 404 No Such User exist") My data is show on after run server so can you tell me what mistake in my code if you can help me please tell me what mistake in code please tell me why i am not couldn't fetch............................................................................................. profile.html {% extends 'base.html' %} {% block title %}profile{% endblock title %} <style> .pst{ width: 350px; height: 200px; margin-bottom: 30px; } </style> {% block body %} <div class="container my-4"> <div class="media"> <img src="{{userImg.url}}"class="align-self-start mr-3 userImage" alt="......."> <div class="media-body-info"> <h4 class="mt-4" >{{user.get_username}}</h4> <p>Follower : {{follower}} Following : {{followin}} </p> <p><b>{{bio}}</b></p> </div> </div> <hr> <!-- <h3> Username:{{user.get_username}}</h3> <h3> FirstName:{{user.first_name}}</h3> <h3> lastname:{{user.last_name}}</h3> <h3> Email:{{user.email}}</h3> --> <!-- <h3> country:{{user.country}}</h3> sss --> <div class="row"> {% for i in posts %} {% for j in i %} <div class="col-md--4 "> <img src="{{j.image.url}}" alt="" class="pst"> </div> {% … -
Django aggregate Min on filtered reverse foreign field
class Order(models.Model): ... class OrderApplication(models.Model): created_at = models.DateTimeField(auto_now=True) driver = models.ForeignKey(Driver, on_delete=models.CASCADE) suggested_price = models.DecimalField(..., blank=True, null=True) I have the models as described above. All Orders usually have more than 1 OrderApplication (OA). However, there is only 1 OA for each Order which has a non-null suggested_price field. At some moments I have to serialize a list of Orders and send it to the front-end React app. I want my orders to be placed in a very specific Order: For each order I want to get the OA which relates to it and have a non-null suggested_price field Then when I get this OA I want to check its created_at field Basing on this field the earlier the OA was created the closer to the end should the Order be placed. So, the first Order will be the one which has an OA with specified suggested_price and created as recently as possible What I have already tried is ordering the Orders by the first created OA related to it: .annotate(suggestion_created=Min('orderapplication__created_at')).order_by("-suggestion_created") Here inside Min aggregator I use a reversed foreign relation of the Order which is can be accessed as orderapplication and get the first date of the objects which are … -
Upload image using django-restframework
Pardon if this question has been answered already. I can't find a solution that works - please point me in the right direction if you can. I need to upload an image using django-restframework but my code is not working. I get the following error: Got a `TypeError` when calling `Product.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Product.objects.create()`. You may need to make the field read-only, or override the ProductSerializer.create() method to handle this correctly. My models.py: class Product(models.Model): store = models.ForeignKey(Store, to_field='store_name', on_delete=models.SET_NULL, null=True) product_name = models.CharField(max_length=71) price = models.PositiveIntegerField(null=True, default=0) total_stock = models.PositiveIntegerField(default=0) image = models.ImageField(upload_to='images', blank=True) created = models.DateTimeField('date added', auto_now_add=True) modified = models.DateTimeField('date modified', auto_now_add=True) My serializers.py: from rest_framework import serializers from inventory.models import Product class ProductSerializer(serializers.ModelSerializer): store = serializers.ReadOnlyField(source='store.store_name') slug = serializers.ReadOnlyField(source='store.slug') store_logo = serializers.ImageField(source='store.logo', read_only = True) class Meta: model = Product exclude = ('created', 'modified',) My views.py from rest_framework.parsers import FileUploadParser from rest_framework import generics from rest_framework.response import Response from rest_framework import status class ProductCreate(generics.CreateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer parser_class = (FileUploadParser,) def create(self, request, *args, **kwargs): serializer = ProductSerializer(data=request.data) print(serializer) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) … -
Super in Python
I have been working in django CBV but i am stuck and cannot reslove it i also googled that thing but nothing much i get it sometimes in classes we use super class ArticleCounterRedirectView(RedirectView): permanent = False query_string = True pattern_name = 'article-detail' def get_redirect_url(self, *args, **kwargs): article = get_object_or_404(Article, pk=kwargs['pk']) article.update_counter() return super().get_redirect_url(*args, **kwargs) class ArticleCounterRedirectView(RedirectView): permanent = False query_string = True pattern_name = 'article-detail' def get_redirect_url(self, *args, **kwargs): article = get_object_or_404(Article, pk=kwargs['pk']) article.update_counter() return super(ArticleCounterRedirectView,self).get_redirect_url(*args, **kwargs) we use super to to call the parent class then in one example we give no arguments and in another we give it two arguements please can someone help me out in this -
Def - time conversion
Folks, It could help me build Def, via SHELL i was able to extract exactly what i need, which is to calculate the duration of hours, in my example it is related to a maintenance window but i'm not sure how to assemble at DEF. Doubt - The manipulation DEF can be represented in the "duration" object that I created? >>> import datetime >>> time1 = datetime.strptime("03-06-2020 23:00",'%d-%m-%Y %H:%M') >>> time2 = datetime.strptime("04-06-2020 04:00",'%d-%m-%Y %H:%M') >>> difference = time2 - time1 >>> difference datetime.timedelta(seconds=18000) >>> difference.seconds 18000 >>> datetime.timedelta(0, 18000) datetime.timedelta(seconds=18000) >>> >>> format(datetime.timedelta(seconds=difference.seconds)) '5:00:00' class Sishora(models.Model): description = models.CharField(max_length=100) OCUPACTION_CHOICES = ( ( 'AlocTOC','Alocacao_TOC'), ('AloENG','Alocacao_apoio_ENG'), ('ImpJan','Implementacao_Janela') ) ocupaction = models.CharField(max_length=50, choices=OCUPACTION_CHOICES) PROJECT_CHOICES = ( ( 'BR1','BR19062'), ('BR2','BR20009'), ('BR3','BR20009.2') ) project = models.CharField(max_length=50, choices=PROJECT_CHOICES) date_ord_1 = models.DateField(null=True, blank=True, default=None) date_ord_2 = models.DateField(null=True, blank=True, default=None) date_ord_2 = models.DateField(null=True, blank=True, default=None) date_ord_3 = models.DateField(null=True, blank=True, default=None) date_ord_5 = models.DateField(null=True, blank=True, default=None) TIME_ORD_1_CHOICES = [(None, '------')] + [(dt.time(hour=x), '{:02d}:00'.format(x)) for x in range(0, 24)] time_ord_1 = models.TimeField(null=True, blank=True, default=None, choices=TIME_ORD_1_CHOICES) date_exth_start = models.DateField(null=True, blank=True, default=None) date_exth_end = models.DateField(null=True, blank=True, default=None) timehe1start = models.DateTimeField(null=True, blank=True, default=None, auto_now_add=False) timehe1end= models.DateTimeField(null=True, blank=True, default=None, auto_now_add=False) duracao = models.DurationField(null=True, blank=True) #user = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField(default=True) @property … -
Django session is not being persisted and cookie is not being set when using Django Channels
Django 3.6, Channels 2 I am writing a chat application in which I assign a random username to non-authenticated users. I save this username to self.scope['session'] within the consumer. For authenticated users, the csrftoken cookie and the sessionid cookie are being set correctly in the browser. However, even though I both set and save the scope['session'] variable for non-authenticated users in the consumer's connect method, the session is not being saved in the django_session table and the user_name cookie is therefore not being set in the browser. I am using an async consumer, and I am using the correct database_sync_to_async to save the session as shown at the bottom of the first example code shown here. Relevant code sections: consumers.py: from channels.generic.websocket import AsyncJsonWebsocketConsumer from channels.db import database_sync_to_async from chat.models import * class ChatConsumer(AsyncJsonWebsocketConsumer): DIGITS = string.digits ANON_NUMBER_LENGTH = 7 async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = f'chat_{self.room_name}' if not self.scope["user"].is_authenticated: if 'user_name' not in self.scope['session']: # Create user name session for anonymous user random_number = ''.join(random.choice(ChatConsumer.DIGITS) for i in range(ChatConsumer.ANON_NUMBER_LENGTH)) self.scope['session']['user_name'] = f'Guest_{random_number}' await database_sync_to_async(self.scope["session"].save)() elif 'user_name' in self.scope['session']: # Remove user_name from session if present self.scope['session'].pop('user_name') await database_sync_to_async(self.scope["session"].save)() routing.py: from channels.auth import AuthMiddlewareStack application = ProtocolTypeRouter({ # … -
django all-auth can you switch mid-project
I have implemented my own custom accounts app that require email and password for authentication. Recently, I've heard a lot about all-auth and am considering if I should switch to all-auth. Given that custom authentication should be done right when you start a new project, is it advisable to switch to all-auth when you have an existing authentication? If this is possible, what are the additional steps after going through the normal installation of all-auth? -
When should I create methods in model
I have model Post and i'm making querysets like this in view user = CustomUser.objects.get(username=user) blocked_users = user.blocked.all() posts_except_blocked = Post.objects.exclude(author__in=blocked_users).order_by('-pub_date') and a few similar. But i recognized that I can put this into model class as @staticmethod and now it's looking @staticmethod def get_posts_except_blocked(user): user = CustomUser.objects.get(username=user) blocked_users = user.blocked.all() return Post.objects.exclude(author__in=blocked_users).order_by('-pub_date') Should I put every queries like this to model? I have there in views method def create_notifications(post): for word in post.content_post.split(): if '@' in word: user_to_notificate = CustomUser.objects.get(username=word[1:]) TalkAbout(where=post, _from=post.author, to=user_to_notificate).save() I'm calling it after save post form to create notifications. Can this be in views or maybe I need to put it in Post class too? Is it possible to call this function automaticly after creating post? -
Django - authenticate method error. The view home.views.loginAdmin didn't return an HttpResponse object. It returned None instead
I'm newbie to Django. I'm stuck at one thing that, my login authenticate method return None. I've tried my best to search and try to solve this but i didn't find my problem solution. In first screen shot, I'm getting value of form and using variable in authenticate method but its giving me that error. But in second screen shot if, I used hard coded value in authenticate method that i know saved in database username and password, then it will execute successful. I've debug form username and password They are coming. I tried to elaborate my problem. Please guide me how to solve this. Thank You. Screen Shot 1 Link: Having error in This Screen Shot 2 Link: But No error if Hard Coded Value