Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a new session for all new users in django
A few weeks ago i've started a project on django. Now i'm about to finish it, but while i'm testing it i've noticed that, when i've uploaded it on heroku it worked well, but only on one device a time, i don't know why but when there are more than one device connected, the app doesn't create a new session , but it refresh the existing one. So if i'm connected as user1 on my phone, and then i connect on the app but on another device, it show me the session of user1. I think the problem is because i've written most part of the code in the view section. how can i fix this? this is my app link: https://secure-password-manager.herokuapp.com -
Django Channels Websocket hanging - WebSocketProtocol took too long to shut down and was killed
Environment: Ubuntu 16.04.6 conda 4.12.0 Apache/2.4.18 (Ubuntu) python==3.8.1 Django==4.0.3 channels==3.0.5 asgi-redis==1.4.3 asgiref==3.4.1 daphne==3.0.2 I am attempting to create a websocket service that only relays messages from redis to an authenticated user. Users do not communicate with each other, therefore I don't need Channel layers and my understanding is that Channel layers are an entirely optional part of Channels. I'm simply trying to broadcast messages specific to a user that has been authenticated through custom middleware. I have custom auth middleware that takes an incoming session id and returns the authenticated user dictionary along with a user_id. I'm also attaching this user_id to the scope. I have elected to route all traffic through daphne via Apache2 using ProxyPass on port 8033. This is preferred since I'm using a single domain for this service. However, I'm really struggling to maintain a connection to the websocket server, particularly if I refresh the browser. It will work on the first request, and fail after with the following message in journalctl: Application instance <Task pending name='Task-22' coro=<ProtocolTypeRouter.__call__() running at /root/miniconda2/lib/python3.8/site-packages/channels/routing.py:71> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x7f658c03f670>()]>> for connection <WebSocketProtocol client=['127.0.0.1', 46010] path=b'/ws/userupdates/'> took too long to shut down and was killed. After spending hours on … -
What's the best way to store time ranges with django and mySQL? Example - 8am to 12pm
I have a requirement for my project where a user can select either time slots such as 8am-9am, 10am-11am, etc. OR select a wide time range such as 8am to 12pm, 12pm to 3pm, 3pm to 6pm, etc. I am using django as the back end for this project and haven't found the exact field type I'm looking for my model other than possibly DurationField. Does anyone have ideas they could share? -
TypeError at /booking render() got an unexpected keyword argument 'renderer'
TypeError at /booking there is an error when i a clicked on booking page of my site , https://hostclinic.pythonanywhere.com/ [forms.py] from django import forms from .models import Booking class DateInput(forms.DateInput): input_type = 'date' class BookingForm(forms.ModelForm): class Meta: model = Booking fields = '__all__' widgets = { 'booking_date': DateInput(), 'dob': DateInput(), } labels = { 'p_name': 'Patient Name', 'dob': 'Date of Birth', 'phn': 'Phone', 'email': 'Email', 'gender': 'Gender', 'department':'Departments', 'doctor':'Doctors', 'blood_group': 'Blood Group', 'address': 'Address', 'district': 'District', 'sub_branch':'Sub Branch', 'booking_date': 'Appointment Date', } -
How to use prefetch_related on two M2M values?
I want to prefetch_related to two level of M2M values, models.py class A(models.Model): name = models.CharField(max_length=40) b = models.ManyToManyField('B') class B(models.Model): name = models.CharField(max_length=40) c = models.ManyToManyField('C') class C(models.Model): name = models.CharField(max_length=40) d = models.ManyToManyField('D') And my ORM is a_obj = A.objects.all().prefetch_related('a__b__c') And I am trying to access the values like below, Method A: for each_obj in a_obj: print(each_obj.a__b__c) Method B: for each_obj in a_obj: print(each_obj.a.all()) Method A throws an error saying No such value a__b__b for A found Method B doesn't throw any error, but the number of queries increases to the length of a_obj. How to access a__b__c in a single query? -
Django Filter and Sum Value depends on different model
_Hi, guys! I'm trying to sum times for users for each Month(Mission), like this: times = goal.time_set.filter(day__year=today.year, day__month=today.month) Then I will sum: for time in times: total_min[member_number] = total_min[member_number] + time.value But it calculates for current Month(Mission). I want to calculate time depends on object model Mission. Model Mission: class Mission(models.Model): name = models.CharField(max_length=200, default='') description = models.TextField(default='') add_info = models.TextField(default='', blank=True) theme = models.ImageField(upload_to='themes/', default='themes/default.png') date_created = models.DateTimeField(null=True) date_finished = models.DateTimeField(null=True, blank=True) Like this I think: times = goal.time_set.filter(day__year=mission.date_created.year, day__month=mission.month_created.month) How can I achieve it? -
django project before every web project
I learned html css javascript then i started learning django as backend bcoz i am very good in python so now i learned django but i have one question we only use django for website like django serves html css javascript by its own so whenever i need to create any website first i need to create django project and then integrate my html css in it and server it. so what i mean is we learn html css separately but when creating a website like with django we integrate or generate html dynamicaly on the server side and send it to the user -
UUIDField vs Charfield with a UUID in it?
So I've been using UUIDs in a CharField as PKs for a lot of things on a project I'm working on, works fine, no issues. If I use a UUIDField, certain things in the backend will have issues with a UUID field (usually functions that expect the UUIDs to be a string). Is there any advantage of using a UUIDField vs just having 'default=uuid.uuid4' in a CharField? -
Why we need to specify read_only=True when dealing with foreign key related field in a serializer in Django rest framework?
Why we need to specify read_only=True when dealing with foreign key related field in a serializer in Django rest framework? field_name = RelatedFieldSerializer(many=True, read_only=True) many = True is understood as the foreign key is on the related object. -
inefficient iterarion over Django queryset
I'm trying to speed up the response time of a get request from React to Django. The delay is due to the iteration over a filtered queryset. stop_time_next_hour = StopTime.objects.filter( stop_id=stop_id, # Get all arrival times in the next hour arrival_time__gte=current_time.time(), arrival_time__lte=(current_time + timedelta(hours=1)).time(), ) This is the queryset, which must be iterated over, and with each iteration, a request is sent to the DB leading to slow response times. for stop_time in stop_time_next_hour: if stop_time.trip.service_id == str(service_id): check_trip_for_update(gtfsDict,stop_time.trip.trip_id) The filter is dynamic and is dependent on user input, so the queryset cannot be loaded prior to the get request containing the user input. How can this performance be optimized? -
How to enrich the Django request object with extended functions?
In my Django project, I have a situation where different views communicate via a request session data as follows: def view_one(request): ... request.session['my_session_key'] = data ... def view_two(request): ... data = request.session['my_session_key'] ... However, this has the following problems: The key string my_session_key is not a constant so it will be hard to scale it up to other parts of the code if I start writing to and/or reading from it in other parts of my code. As this system grows, it will become harder to identify which are the available keys being used and written in the session. In Kotlin (which I'm more familiar with), one way to solve this would be using an extension function, like so: var Request.my_session_key: Int get() = this.session['my_session_key'] set(value) { this.session['my_session_key'] = value } This way, I could now write my views as follows: def view_one(request): ... request.my_session_key = data ... def view_two(request): ... data = request.my_session_key ... Is there any way to accomplish something similar in Python or with Django? Or, alternatively, taking a step back, what would be the best way to organize the data stored in a Django session across multiple views? -
Updating partial data in DB while fetching data should count as GET or PUT request in REST API
My class is to fetch current song info from Spotify api. class GetCurrentSong(APIView): def get(self, request): dict_song_info = get_song_from_spotify(user_session=self.request.session.session_key) if 'Error' in dict_song_info: return Response({dict_song_info['Error_Type']: dict_song_info['Error']}, status=dict_song_info['Status']) # Update song name in database try: self.update_song_info_in_db(dict_song_info['name']) except Exception as ex: return Response({'Storage Error': 'Caanot persist current song info to database'}, status=status.HTTP_406_NOT_ACCEPTABLE) return Response(dict_song_info, status=status.HTTP_200_OK) Besides fetching song info and rendering to the frontend, I also need to update song name data in DB before rendering. My question is: this function involves data update (no create new entries, just update existing data record). Does it still count as "Get"? Or actually, I should use "PUT" for this function? -
How can I install Pandas in a Django project that is in a virtual Ubuntu environment
in the virtual machine of ubuntu I have a project in django for production, and within the project I need to install the panda module but it does not let the process be carried out. the following statement pandas collect comes out and then says killed. enter image description here -
Django's form unique_together validation
I want to make an error if a user comments once on a movie and then again on the same movie. Specifically, I want to allow a user to comment on a film only once, and to throw an error if they try to comment twice. How can I change this? Please be specific with your code. class Comment_movie_CreateForm(ModelForm): class Meta: model = Comment_movie fields = ('comment', 'stars') exclude = ['user'] comment = forms.CharField(required=False,label='comment',widget=forms.Textarea( attrs={'placeholder':'example input'}),max_length=1000) stars = forms.FloatField(required=False,label='stars',widget=forms.NumberInput( attrs={'type': 'range','id':'form_homework',"class": "no_resize",'min': '0','max':'10','step':'0.1'})) def clean(self): cleaned_data = super().clean() try: Comment_movie.objects.get(user=self.user, movie=self.movie) except Comment_movie.DoesNotExist: pass else: raise forms.ValidationError('Solution with this Name already exists for this problem') # Always return cleaned_data return cleaned_data class Comment_movie(models.Model): comment = models.TextField(max_length=1000) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) movie = models.ForeignKey(Movie, on_delete=models.CASCADE) created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(auto_now=True) class Meta: unique_together = ('user', 'movie') indexes = [ models.Index(fields=['user', 'movie']), ] -
How to filter in django with empty fields when using ChoiceField
I have a programme where users should be able to filter different types of technologies by their attributes. My question is, how would I filter the technologies when there's potential conflicts and empty values in the parameters I use to filter? Forms.py: class FilterDataForm(forms.ModelForm): ASSESSMENT = (('', ''),('Yes', 'Yes'),('No', 'No'),) q01_suitability_for_task_x = forms.ChoiceField(label='Is the technology suitable for x?', choices=ASSESSMENT, help_text='Please select yes or no', required=False,) q02_suitability_for_environment_y = forms.ChoiceField(label='Is the technology suitable for environment Y?', choices=ASSESSMENT, help_text='Please select yes or no', required=False) There are many fields in my model like the ones above. views.py class TechListView(ListView): model = MiningTech def get_queryset(self): q1 = self.request.GET.get('q01_suitability_for_task_x', '') q2 = self.request.GET.get('q02_suitability_for_environment_y', '') object_list = MiningTech.objects.filter(q01_suitability_for_task_x=q1).filter( q02_suitability_for_environment_y=q2) return object_list The difficulty is that not all technology db entries will have data. So in my current setup there's times where I will filter out objects that have one attribute but not another. For instance if my db has: pk1: q01_suitability_for_task_x=Yes; q02_suitability_for_environment_y=Yes; pk2: q01_suitability_for_task_x=Yes; q02_suitability_for_environment_y=''; In the form, if I don't select any value for q01_suitability_for_task_x, and select Yes for q02_suitability_for_environment_y, I get nothing back in the queryset because there are no q01_suitability_for_task_x empty fields. Any help would be appreciated. I'm also ok with restructuring everything if … -
I am not using any authentication method to login in Django. I am using this function is it right?
''' def login_action(request): if request.method != "POST": return HttpResponse("<h2>Method Not Allowed</h2>") else: user = Admin_user.objects.get(email_id=request.POST.get('email'), password=request.POST.get('password')) if user!=None: return HttpResponse("Loged IN") else: return HttpResponse("Not a User") ''' this Method Works for me is it a right method. I don't use authenticate method because my models has 5 user type. can any one suggest me a method for 5 user type if my method is not right -
Filtering on annotated field django ORM
I am trying to filter my queryset based on the newly created column using annotation. first_query = Products.objects.annotate(top_rating=Subquery( Ratings.objects.filter(product=OuterRef("pk")) .order_by("-date_val").value('rate_val')[:1], ))) sec_query = first_query.filter(top_rating=4) But I am getting error Cannot resolve keyword 'top_rating' into field -
Django: Getting last value by date from related model in html
Hy all I Just had a question: So on my parent product overview i show the name of the product and it's URL but there is also a related model to that parent model which holds the history of the prices over time. What i want to do is show also the latest price in my table here is my code: models.py: class Product(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=100, default=None, null=True, blank=True) url = models.CharField(max_length=255, default=None, null=True, blank=True) creation_date = models.DateTimeField(auto_now_add = True) update_date = models.DateTimeField(auto_now = True) class PriceHistory(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product_info = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(max_digits=20, decimal_places=2) creation_date = models.DateTimeField(auto_now_add = True) My views.py @login_required def overview(request): all_products = PersonalisedTrackingInfo.objects.filter(user=request.user) general_context = {'all_products': all_products} return render(request, 'overview.html', general_context) and my html <h4>Overview Products</h4> <table> <thead> <tr> <th>#</th> <th>Name</th> <th>Url</th> <th>Last price</th> </tr> </thead> <tbody> {% for product in all_products %} <tr> <td>{{ forloop.counter }}</td> <td>{{ product.name }}</td> <td>{{ product.url }}</td> <td>{{ product.id.price}}</td> <td></td> {% endfor %} </tr> </tbody> </table> My question is: how to get the latest price also together with my product in my html overview? I tried with {{ product.id.price}}. I think i'm not far off but can't get my head … -
How to relate models with reverse link
_Hi, guys! How can I relate two models? I want to write like this: user_goal_minutes = ninja.ninjagoal_set.goal_time * 60 My models: class Ninja(models.Model): id_user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="ninja", blank=True, null=True) id_teams = models.ManyToManyField("mission.Team", blank=True) avatar = models.ImageField(upload_to='avatar/', default='avatar/default.png', blank=True) goal_time = models.PositiveIntegerField(default=0, blank=True) class NinjaGoal(models.Model): id_mission = models.ForeignKey(Mission, null=True, blank=True, on_delete=models.SET_NULL) id_ninja = models.ForeignKey("accounts.Ninja", null=True, blank=True, on_delete=models.SET_NULL) goal_time = models.PositiveIntegerField(default=0, blank=True) -
Download a file after saving a model in Django
I'm trying to generate a PDF based on a ModelForm using Weasyprint. The idea is when the user clicks save the PDF is generated after the model is saved (I'm using the signal post_save to accomplish this). But when I hit the save button, the model is saved but the download prompt is not shown to the user, even though I have the correct Content-Disposition configuration in my HttpResponse. I also need to pass some parameters to the post_save signal because some of the fields that need to be added to the PDF are not in the Model, but are in the ModelForm, and I have not been able to find out how to do that. admin.py def save_model(self, request: HttpRequest, obj: Contract, form: ContractForm, change: Any) -> None: if not change and not request.user.is_superuser: obj = MythLabsMultiTenancy.assign_organization_to_obj( obj, request.user ) return super().save_model(request, obj, form, change) forms.py from dal.autocomplete import ModelSelect2 from django import forms from django.core.validators import RegexValidator class ContractForm(forms.ModelForm): class Meta: widgets = { 'handover_vehicle': ModelSelect2( url='vehicle_autocomplete', forward=('organization',), ), 'lease_holder': ModelSelect2( url='client_autocomplete', forward=('organization',), ), 'replacement_vehicle': ModelSelect2( url='replacement_vehicle_autocomplete', forward=('organization',), ), } warranty_card_company = forms.CharField(required=False, label='Tarjeta') warranty_card_number = forms.CharField( max_length=19, required=False, label='N° de tarjeta' ) warranty_card_expiration_date = forms.CharField( max_length=5, required=False, … -
How to count and filter object in Django template?
I have two models: in one, the user creates a post, and in the other, the likes of those posts are collected. Now I would like the number of these likes to be displayed on the post. Is there any way for all posts with the number of likes to be displayed on one template? template.html: <div class="col-sm-4 mx-auto "> <ul class="list-group"> {%for post in posts %} <a id="like_{{post.id}}" href="" class="like-link text-muted"> +{% for every_like in likes_obj%}{%if every_like.liked_what == post%}{{every_like.count}}{%endif%}{%endfor%} ## At this point I would like to see the number of likes for each post it is assigned to, but unfortunately {{every_like.count}} returns nothing. </a> {% endfor %} </ul> </div> views.py: def index(request): list = Post.objects.all().order_by('-date') paginator = Paginator(list, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, "network/index.html", { "post_form": PostForm(), "posts": page_obj, "likes_obj": Like.objects.all() }) models.py: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=200, blank=False) content = models.TextField(blank=False) class Like(models.Model): author_of_like = models.ForeignKey(User, on_delete=models.CASCADE) liked_what = models.ForeignKey(Post, on_delete=models.CASCADE) -
To convert m3u8 files directly from a link to mp4 video
I have searched about it and found a python module https://pypi.org/project/m3u8-To-MP4/ but I want a better solution to download video in mp4 format from URL -
Error while makemigrations, relation for custom user
I am currently in the middle of this project and the makemigration command is throwing an error. Previously I used migrated but it worked fine. The error line it is showing was added before and was migrated successfully too. This is the Error E:\Projects\V-conn-API>docker-compose run --rm app sh -c "python manage.py makemigrations base" [+] Running 1/0 - Container v-conn-api-db-1 Running 0.0s Traceback (most recent call last): File "/py/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "base_user" does not exist LINE 1: SELECT (1) AS "a" FROM "base_user" WHERE "base_user"."v_id" ... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/py/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/py/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/py/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/py/lib/python3.9/site-packages/django/core/management/base.py", line 393, in execute self.check() File "/py/lib/python3.9/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/py/lib/python3.9/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/py/lib/python3.9/site-packages/django/contrib/auth/checks.py", line 82, in check_user_model if isinstance(cls().is_anonymous, MethodType): File "/py/lib/python3.9/site-packages/django/db/models/base.py", line 477, in __init__ val = field.get_default() File "/py/lib/python3.9/site-packages/django/db/models/fields/__init__.py", line 850, in get_default return self._get_default() File "/app/base/models.py", line … -
authenticate return none for custom user model django rest framework
I am trying to use email instead of a username for login in django-rest-framework. but authenticate(request, email=email, password=password) always return None. I tried many ways but always it returns None. can someone help me to solve this problem? Model class CustomUser(BaseUserManager): def create_superuser(self,user_name, email, phone, password,**other_fields): other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_staff', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to is_staff=True') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to is_superuser=True') return self.create_user(user_name, email, phone, password, **other_fields) def create_user(self, user_name, email, phone, password, **other_fields): if not email: raise ValueError(gettext_lazy('Email is required')) other_fields.setdefault('is_active', True) email = self.normalize_email(email) user = self.model(user_name=user_name, email=email, phone=phone, **other_fields) user.set_password(password) user.save() return user class Profile(AbstractBaseUser, PermissionsMixin): user_name = models.CharField(unique=True, max_length=255) email = models.EmailField(gettext_lazy('email address'), unique=True) password = models.CharField(null=False, max_length=2000) phone = models.CharField(max_length=30) register_date = models.DateTimeField(default=timezone.now) is_varified = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = CustomUser() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_name', 'phone'] serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['email', 'user_name', 'password','phone'] extra_kwargs = { 'password': {'write_only': True} } View class RegisterView(APIView): def post(self, request): serializer = RegisterSerializer(data= request.data) if serializer.is_valid(): serializer.save() email = serializer.data.get('email') password = serializer.data.get('password') user = authenticate(request, email=email, password=password) print(user, email, password) # … -
DJANGO TEMPLATE not grabing image but the image exists
So i have a little problem. I have a funcion to upload and edit news, wich im going to paste the logic here: @login_required def listing_new(request): try: company = Company.objects.get(user=request.user) except Company.DoesNotExist: company = None try: mainnew = MainNew.objects.get(company=company) except MainNew.DoesNotExist: mainnew = '' try: news = New.objects.filter(company=company).order_by('-id')[:3] except New.DoesNotExist: news = None context = { "news": news, "mainnew": mainnew, "company": company, } return render (request, "list_new.html", context) And my template, wich is the one who is working fine: {% extends 'base.html' %} {% load static %} {% block title %} WIZI {% endblock title %} {% block content %} {% if company != None %} {% if mainnew != '' %} <section id="blog" class="blog_area pt-120 pb-130"> <div class="container"> <div class="row justify-content-center"> <div class="col-lg-6"> <div class="section_title text-center pb-25"> <h4 class="title wow fadeInUp" data-wow-duration="1.3s" data-wow-delay="0.2s">Notícias</h4> </div> <!-- section title --> </div> </div> <!-- row --> <div class="row"> <div class="col-lg-6"> <div class="single_blog mt-30 wow fadeInUp" data-wow-duration="1.3s" data-wow-delay="0.2s"> <div class="blog_image"> <img src="{{ mainnew.image.url }}" alt="blog" style="height: 450px; width: auto"> </div> <div class="blog_content"> <h3 class="blog_title"><a href="#0">{{ mainnew.title }}</a></h3> <p>{{ mainnew.text }}</p> </div> </div> <!-- single blog --> </div> </div> <!-- row --> </div> <!-- container --> </section> <a href=" {% url 'update-mainnew' %} "><button …