Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How many users are there in the chat session (django-channels)?
Basically I have created the chat application but i don't know how to show that how many users has been joined the chat group.Briefly i want to show name of the user and they are online/offline. I have tried import Group but then i came to know that it has been deprecated and then tried django-channel-presence but now able to understand. Kindly Help ! # chat/consumers.py # Sorry 😅😅for my code import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer, AsyncJsonWebsocketConsumer from django.contrib.auth import get_user_model from .models import Message from django.db.models.signals import post_save from django.dispatch import receiver # import channels # from channels.auth import channel_session_user, channel_session_user_from_http User = get_user_model() class ChatConsumer(WebsocketConsumer): def new_message(self, data): author = data['from'] author_user = User.objects.filter(username=author)[0] message = Message.objects.create( author=author_user, content=data['message']) content = { 'command': 'new_message', 'message': self.message_to_json(message) } return self.send_chat_message(content) # def messages_to_json(self, messages): # result = [] # for message in messages: # result.append(self.message_to_json(message)) # return result def message_to_json(self, message): return { 'id': message.id, 'author': message.author.username, 'content': message.content, 'timestamp': str(message.timestamp) } commands = { 'new_message': new_message } # PREDEFINED # *************************************************************************************************************************** def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] print("self.scope['url_route']['kwargs']['room_name'] : "+self.scope['url_route']['kwargs']['room_name']) self.room_group_name = 'chat_%s' % self.room_name print("self.room_group_name : " + self.room_group_name) print("self.channel_name, : " + … -
Django media files not found
I have a problem with displaying user submitted images in django. i've read through a lot of other threads similar to this question but couldn't get anything to work from those solutions. i have a model with an image field that i submitted through the admin panel and the image uploaded correctly. class Listing(models.Model): #fields editable by users title = models.CharField(max_length=25) description = models.TextField() starting_bid = models.DecimalField(max_digits=6, decimal_places=2) image_url = models.ImageField(upload_to='images/') #auto-created fields def __str__(self): return self.title to settings.py i added MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' and i added the static line in my urls.py from django.urls import path from django.conf.urls.static import static from django.conf import settings from . import views urlpatterns = [ path("", views.index, name="index"), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and i am trying to render in the template the image {% for entry in entries %} <div class="container"> <img src="{{entry.image_url}}", alt="image"> <p>{{entry.image_url}}</p> <p>{{entry.title}}</p> </div> {% empty %} <p>There are no active listings right now! come back later</p> {% endfor %} in my main directory with my app folders i have the 'media' folder with the 'images' folder inside. The HTML returns the objects and displays the title as expected and prints the image … -
Django query with two Foreign keys - check if exist, assign or create
I am trying to create a Car dealer app - When a user selecting a car/vehicle, they must select a make, and model in that order. The preferred behaviour would be to cascade each lookup selection as a filter to the next lookup. When a user changes a master lookup (Model), all child lookups should be cleared. In this case, only one - Make of a vehicle/car I will add vehicles via Django shell query manually, but I don't know, how to ensure, that when for example Make of vehicle does not exist, that DB will create it. And later, when I will be adding another car/vehicle, which Make already exists in DB, it is needed that only FK of ID will be assigned to the new record, and no one entry will be created for Make For example, When first I will add a car with Make of "BMW" and another one will be also "BWM" - so there will not be duplicate records in Make table. Expected result in DB is: Make Model Vehicle ---- ------ ------- BMW ---- X6 ---- AAA, BBB |--- 535i ---- CCC, DDD |--- i8 ---- EEE, FFF Audi ---- A6 ---- GGG, … -
Difference between User.objects.create_user() vs User.objects.create() vs User().save() in django
In djnago documentaion, it uses User.objects.create_user() to create a user. I am confused, what is the difference between that and User.objects.create() and User().save() which are the normal ways to create objects of other models -
DJANGO 3.0: List out of QuerySet (Basic-Level question)
It is very beginner level question, I know. But can anyone just tell me how to make List out of QuerySet. I am getting queryset with following query: sports = Category.objects.all() print(sports) Output: <QuerySet [<Category: Golf>, <Category: Cricket>, <Category: Football>, <Category: Golf>, <Category: Hockey>]> But what I require, is: print(sports) Desired Output: ['Baseball', 'Cricket', 'Football', 'Golf', 'Hockey'] -
Django - Unit testing a form containing recaptcha
I am trying to write a unit test for a form containing recaptcha: My contact view looks like this: @check_recaptcha def contact(request): if request.method == 'POST': f = ContactForm(request.POST) if f.is_valid() and request.recaptcha_is_valid: f.save(request) messages.add_message(request, messages.INFO, "Thanks for submitting feedback!") return redirect('contact') else: f = ContactForm() return render(request, 'cms/contact.html', {'form': f}) The decorator check_recaptcha() is defined like this: def check_recaptcha(view_func): @wraps(view_func) def _wrapped_view(request, *args, **kwargs): request.recaptcha_is_valid = None if settings.DEBUG: request.recaptcha_is_valid = True return view_func(request, *args, **kwargs) if request.method == 'POST': recaptcha_response = request.POST.get('g-recaptcha-response') data = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) result = r.json() if result['success']: request.recaptcha_is_valid = True else: request.recaptcha_is_valid = False messages.error(request, 'Invalid reCAPTCHA. Please try again.') return view_func(request, *args, **kwargs) return _wrapped_view And the code to test the contact form looks like this: class TestContactForm(TestCase): def test_can_send_feedback(self): data = { "name": "tom", "email": "tom@test.com", "subject": "A test subject", "message": "Hello jerry", } response = self.client.post(reverse('contact'), data=data) self.assertEqual(Feedback.objects.count(), 1) self.assertEquals(response.status_code, 302) self.assertRedirects(response, reverse('contact')) The test run perfectly fine if I remove request.recaptcha_is_valid condition in the contact view. Is there a way to get rid of captcha during testing? -
Django Formset Initialization in POST and GET
I want a formset initialized with a varying number of forms. class MapView(TemplateView): def get(self, request, *args, **kwargs): template_name = 'terms/termmappingnames.html' formlength = request.session["formlength"] FieldMappingFormset = formset_factory(FieldMappingForm, extra=formlength) formset = FieldMappingFormset() choices = [(x, x) for x in ["a", "b", "c"] for i, form in enumerate(formset): form.fields["map_to_option"].choices = choices form.fields["map_to_option"].label = metadata_names[i] context = { "formset": formset } return TemplateResponse(request, template_name, context) def post(self, request, *args, **kwargs): template_name = 'terms/termmappingvalues.html' # error here formset = FieldMappingFormSet(request.POST) context = { } return TemplateResponse(request, template_name, context) This is my TemplateView and I dont know how to access the FieldMappingFormset created in the get method. Diplaying the form with "formlength" number of forms works, however I can't access it in POST because, obviously, FieldMappingFormSet is not defined. It doesn't work using class variables or global variables. -
Ajax in django, how i could solve problem with my modal window
** sorry for my language, it is not my native language, but I will try** Hi everyone i am shy. and i have problem. i try to make my modal window in my first django project(i dont know js and i starter in django) and i put function js on my modal window click <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> $(function () { $(".js-create-articles").click(function () { $.ajax({ url: '/articles/create/', type: 'get', dataType: 'json', beforeSend: function () { $("#modal-articles").modal("show"); }, success: function (data) { $("#modal-articles .modal-content").html(data.html_form); } }); }); }); class MainArticles(ListView): template_name = 'dishes/articles.html' model = Articles class MainArticlesCreate(View): def get(self, request): form = ArticlesForm() context = {'form': form} html_form = render_to_string('dishes/articles_create.html', context, request=request, ) return JsonResponse({'html_form': html_form}) class ArticlesForm(forms.ModelForm): model = Articles fields = {'name', 'tag', 'deception'} class Articles(models.Model): name = models.CharField(max_length=100) tag = models.CharField(max_length=20, null=True, blank=True) deception = models.TextField(max_length=800) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> {% extends 'main.html' %} {% load static %} {% block javascript %} <script src="{% static 'js/articles.js' %}"></script> {% endblock %} {% block content %} <section class="feature"> <div class="col-md-9"> <h2 class="section-header">Товары в корзине</h2> <div class="table-responsive"> <p> <button type="button" class="btn btn-primary js-create-articles"> <span class="glyphicon glyphicon-plus"></span> New article </button> </p> <table class="table"> <tr class="info"> <td class="info col-md-3">Товар</td> </tr> {% for obj in object_list %} … -
Django models and foreign key
this is my first django project and I still seem to have a problem with the concept of foreign keys. I'm using a mysql db and i defined the model (a part/snippet) of the model: class Doctors(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=31) fachrichtung = models.CharField(max_length=51) adresse = models.CharField(max_length=24) plz = models.CharField(max_length=6) ort = models.CharField(max_length=9) def __str__(self): return self.name class Meta: managed = False db_table = 'doctors' class Leistung(models.Model): bezeichnung = models.CharField(max_length=77) dauer = models.PositiveIntegerField() preis = models.FloatField() id = models.IntegerField(primary_key=True) artikel = models.ManyToManyField(Artikel) class Meta: managed = False db_table = 'leistung' class Behandlung(models.Model): datum = models.DateField() re_nr = models.CharField(max_length=12) doctor = models.PositiveIntegerField() istpreis = models.FloatField() leistungs_text = models.CharField(max_length=32) leistung = models.ForeignKey('Leistung', models.DO_NOTHING) verrechnet_am = models.DateField() class Meta: managed = False db_table = 'behandlung' class Rechnung(models.Model): id =models.IntegerField(primary_key=True) doctor = models.ForeignKey('Doctors', models.DO_NOTHING) erstellt_am = models.DateField() class Meta: managed=False db_table='rechnung' when i start the server and want to produce an entry to Rechnungen with the following lines: date = datetime.today().strftime('%Y-%m-%d') #doctorid is a parameter passed to the view method doc = Doctors.objects.get(id=doctorid) rechnung = Rechnung(doctor=doc.id,erstellt_am=date) rechnung.save() i get the following error: (1054, "Unknown column 'doctor_id' in 'field list'") when i run: date = datetime.today().strftime('%Y-%m-%d') #doctorid is a parameter passed to the … -
confirmation email with a custom user model not working
im having a problem in creating a confirmation email that leads to a view and set up the account.is_active to True things that keep in mind ,i have a custom user model that abstracts from the User model the token generator works fine ,i get the email i click the link ,it says that the account is activated but nothing actually is happening i think the problem is in the activate view my models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email",max_length=60, unique=True) username = models.CharField(max_length=60,unique=True) phone = models.CharField(max_length=60,unique=True) date_joined = models.DateTimeField(verbose_name="date joined",auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login",auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email','phone'] objects = MyAccountManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True tokens.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, account, timestamp): return ( six.text_type(account.pk) + six.text_type(timestamp) + six.text_type(account.is_active) ) account_activation_token = TokenGenerator() view.py #active view========================================== def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) account = Account.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, Account.DoesNotExist): account = None if account is not None and account_activation_token.check_token(account, token): account.is_active = True account.save() login(request, account, backend="users.backends.AccountAuthBackend") # return redirect('home') return HttpResponse('Thank you for your … -
check then update method in MyModel.m2m_field.through django
i want to update a field which have a M2M connection for example : class SelectMobile(models.Model): #others imei = models.ManyToManyField(Imei) status = models.BooleanField(default=True) and this is my Imei model class Imei(models.Model): imei = models.CharField(max_length=15,verbose_name='IMEI',unique=True) mobile = models.ForeignKey(MobileModels,on_delete=models.CASCADE) active = models.BooleanField(default=True) hi , i need to update active in Imei only when an instance of SelectMobile been created and its status field equal to True i tried this def update_imei_m2m(sender,instance,**kwargs): if instance.status == True: #this doesnt work , now it works on `Imei` instead of `SelectMobile` Imei.objects.filter(pk__in=kwargs.get('pk_set')).update(active=True) m2m_changed.connect(update_imei_m2m,sender=SelectMobile.imei.through) thanks for helping -
Encoding issue when reading binary file in Django
I am uploading files in my Django application, which are recorded on the hard drive, and at a later moment they are retrieved. This works well for most files. However, every once in a while there is a file -- generally a PDF file -- that can't be retrieved properly. This is the error that comes up: UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 194: ordinal not in range(128) I have seen other questions about this encoding issue, which all relate to how to deal with this when encoding plain text, but I am dealing with binary files. Here is my code: Relevant upload code: with open(path, "wb+") as destination: for chunk in attachment.chunks(): destination.write(chunk) Code to retrieve the file: with open(file_path, "rb") as f: contents = f.read() response = HttpResponse(contents, content_type="application") response["Content-Disposition"] = "attachment; filename=\""+name + "\"" I understand there is an encoding issue, but where exactly should I fix this? -
How can I dynamically set django filter
I am doing a table in React, fetching some data from my Django DB. It has filters and I want them to call the API to get results if needed. Thing is I have to duplicate a lot of lines whereas I am pretty sure there is a better way to do this. Here is some part of the code: if ss_value and not es_value and not iv_value and not timestamp: queryset = DailyReport.objects.all().filter(station_departure=ss_value) elif not ss_value and es_value and not iv_value and not timestamp: queryset = DailyReport.objects.all().filter(station_arrival=es_value) elif not ss_value and not es_value and iv_value and not timestamp: queryset = DailyReport.objects.all().filter(is_virtual=iv_value) elif not ss_value and not es_value and not iv_value and timestamp: queryset = DailyReport.objects.all().filter( Q(timestamp__range=(min_dt, max_dt)) | Q(upload_timestamp__range=(min_dt, max_dt))) logger.debug(queryset) elif ss_value and es_value and not iv_value and not timestamp: queryset = DailyReport.objects.all().filter(station_departure=ss_value, station_arrival=es_value) elif ss_value and not es_value and iv_value and not timestamp: queryset = DailyReport.objects.all().filter(station_departure=ss_value, is_virtual=iv_value) and it goes on and on. Do you have any idea of a way to do it in a cleaner way ?? Thank you :) -
Django OpenID Connect and OAuth2.0 - Splitting Authorization Server and Resource Server
I have multiple Resource Servers and one Auth Server all written in Django. I have implemented OIDC Provider in the Auth Server using Django OIDC Provider Library. So it provides OAuth 2.0 support as well. Having OAuth 2.0 Token Introspection (RFC 7662) implemented, it allows authorized protected resources to query the authorization server to determine the set of metadata(and verification) for a given access token that was presented to them by an OAuth 2.0 client. I'm getting trouble in setting up the Resource Server, as there's no RESOURCE_SERVER_INTROSPECTION_URL provided like other standard OAuth 2.0 providers for internally verifying the access token with Auth Server(using an internal post request to Auth Server). For example in the Django OAuth Toolkit library, it has clearly been specified in their documentation. But In Django OIDC Provider, they have provided a hook for that OIDC_INTROSPECTION_PROCESSING_HOOK, which I could not understand how to use. Also, there's no detail about it on their official page. I need help in setting up my separate resource servers which can rely on my Auth Server for any token creation and verification. I want to set up an introspect endpoint something like this in my resource server settings.py file: OAUTH_PROVIDER = … -
How to control Django with Javascript?
I am building a web application with Django and I show the graphs in the website. The graphs are obtained from real time websites and is updated daily. I want to know how can I send graphs using matplotlib to template and add refresh option with javascript which will perform the web scraping script which I have written. The main question is which framework should I use? AJAX, Django REST, or what? -
Django - Save multiple object with form.save()
In my application there must be two inputs which will get numbers, and when I'll clickcreate button in the given range (which was written in inputs) difference of that number times object must be created. For example, in first input I'll write "2", in second "5", 3 objects must be created. Here are my codes: models.py: class Blank(models.Model): blank_series = models.CharField(_('Blankın seriyası'), max_length=3) number_from = models.IntegerField() number_to = models.IntegerField() def __str__(self): return self.blank_series forms.py: from django.forms import ModelForm from .models import Blank class CreateBlankForm(ModelForm): class Meta: model = Blank fields = '__all__' html: <tr> <td>{{ form.blank_series.label }}</td> <td>{{ form.blank_series }}</td> </tr> <tr> <td>{{ form.blank_number.label }}</td> <td> {{ form.number_from }} {{ form.number_to }} </td> </tr> <tr> <td class="create-blank-btns"> <button class="create-blank-btn"><span class="material-icons">add_circle_outline</span><input type="submit" value="Əlavə et" name="create-blank"></button> </td> </tr> views.py: @login_required(login_url='sign-in') def blanks(request): if request.method == 'POST': form = CreateBlankForm(request.POST) if form.is_valid(): form.save() else: form = CreateBlankForm() blanks = Blank.objects.all() context = { 'form': form, 'blanks': blanks, } return render(request, 'blank.html', context) -
Passing values between Javascript ajax and django view
I am trying to pass the id value of the selected option to Django view through Ajax and then on success to ajax, move to next tab action to be performed, but i am facing 2 issues here (based on 2 different code blocks i tried): If i use this code block: #form-post is the name of the form $(document).on(submit,'#form-post', function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/form', data:{ Selected:$('#selectradio').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), }, success:function(json){ alert('in success'); $('#tabs a[href="#tab2"]').tab('show'); }, error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console } }); }); I am getting the below output: and not moving to the next tab as it is not going into success:function but the correct id value is being passed, hence i am getting the below: {"Selected": true, "LockedUser": "user1"} If i am using the below:, it is going into the success:function and moving to the next tab but the selected value being passed is wrong (always same value, like ex., if there are 3 rows, out of that if i select 2nd row i would expect 2 as value but i am getting 1. In the above code i am … -
Documentation for Non Rest API Framework Project of Django
I have a running Django project with custom views and URLs defined. But there are lot of of URL doing different type of stuff. How can i make a nice documentation for them, similar to rest API framework of Django. Django REST Swagger is one of the best framework available for generating documentation of rest frameworks. What Framework or template i can use for documentation of Django projects that are not built using rest framework. -
Changing id field to slug field in django
Everything worked fine when I used <int:pk> in urlconfig to view DetailView page of my blogs. # included from urls.py in main dir urlpatterns = [ path('', views.index, name='blog_index'), path('blogs', views.allblogs.as_view(), name='blogs'), path('blogs/<int:pk>', views.blogDetail.as_view(), name='blog-detail'), ] # result url example 127.0.0.1:8000/blog/blogs/2 I later changed my mind to display the url as 127.0.0.1:8000/blogs/new-blog instead of an int value. To achieve this result I made the following changes to urls.py, urlpatterns = [ path('', views.index, name='blog_index'), path('blogs', views.allblogs.as_view(), name='blogs'), re_path(r'^blogs/(?P<slug_me>[-\w]+)$', views.blogDetail.as_view(), name='blog-detail'), ] and following additions to models.py: class Blog(models.Model): ... slug = models.SlugField(default=slugify('iamslug'+str(id))) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.title) super(Blog, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('blog-detail', kwargs={'slug':self.slug, 'id':self.id}) But now when I access 127.0.0.1:8000/blog/blogs, it throws the following error: Reverse for 'blog-detail' with keyword arguments '{'slug': 'djangodbmodelsfieldscharfield', 'id': 1}' not found. 1 pattern(s) tried: ['blog\\/blogs/(?P<slug_me>[-\\w]+)$'] And at 127.0.0.1:8000/blog/blogs/new-blog, it throws this error: Generic detail view blogDetail must be called with either an object pk or a slug in the URLconf. I am unable to move forward. I tried changing urls.py to include slug keyword, which results in Page Not Found. # changed re_path(r'^blogs/(?P<slug_me>[-\w]+)$', views.blogDetail.as_view(), name='blog-detail') to re_path(r'^blogs/(?P<slug>[-\w]+)$', views.blogDetail.as_view(), name='blog-detail') -
TypeError at /uploaddd/ uploaddd() takes 0 positional arguments but 1 was given
I'm getting the following error when I'm trying to just print JSON I have the following in my urls.py from search import views as search_views urlpatterns = [ url(r'^uploaddd', search_views.uploaddd, name='upload'), ] In my search/views.py directory I have the following def uploaddd(): documents = { { "@search.action": "upload", "HotelId": "1", "HotelName": "Secret Point Motel 2020", "Description": "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.", "Description_fr": "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.", "Category": "Boutique", "Tags": [ "pool", "air conditioning", "concierge" ], "ParkingIncluded": "false", "LastRenovationDate": "1970-01-18T00:00:00Z", "Rating": 3.60, "Address": { "StreetAddress": "677 5th Ave", "City": "New York", "StateProvince": "NY", "PostalCode": "10022", "Country": "USA" } }, } return JsonResponse({'doc': documents }) … -
Django CMS update function not working as intended
See I am following a youtube channel to create a blog, I am stuck at post_update function as when i try to update the post the comment is getting updated which should not happen in this scenario, so kindly some guide me as where I am going wrong. views.py from django.db.models import Count, Q from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render, get_object_or_404, redirect, reverse from .forms import CommentForm, PostForm from .models import Post, Author from marketing.models import Signup def get_author(user): qs= Author.objects.filter(user=user) if qs.exists(): return qs[0] return None def search(request): queryset = Post.objects.all() query = request.GET.get('q') if query: queryset = queryset.filter( Q(title__icontains = query) | Q(overview__icontains = query) ).distinct() context = { 'queryset' : queryset } return render(request, 'search_results.html', context) def get_category_count(): queryset = Post \ .objects \ .values('categories__title') \ .annotate(Count('categories__title')) return queryset def index(request): featured = Post.objects.filter(featured=True) latest = Post.objects.order_by('-timestamp')[:3] if request.method == "POST": email = request.POST['email'] new_signup = Signup() new_signup.email = email new_signup.save() context = { 'object_list' : featured , 'latest' :latest } return render(request, 'index.html', context) def blog(request): category_count = get_category_count() #print(category_count) most_recent = Post.objects.order_by('-timestamp')[:3] post_list = Post.objects.all() paginator = Paginator(post_list, 4) page_request_var ='page' page = request.GET.get(page_request_var) try: paginated_queryset = paginator.page(page) except PageNotAnInteger: paginated_queryset … -
Django, aggregate turns a duration field to None Type
I have a query where I'm trying to annotate a duration field and it works, it returns a dictionary containing the time in seconds and assigning it to a value converts the format: def get_group_actual_hours(self, group): """ :return hours: all the group's hours for the month. """ cows_data = CowEventsData.objects.select_related("cow").filter(cow__group=group) seconds = cows_data.aggregate(seconds=Sum('duration')) hours = seconds['seconds'] return hours when trying to use that data in another function it gets turned to a NoneType. def divide_by_days(self, group: Group, farm_id: Farm): farm = Farm.objects.get(id=farm_id) total_hours = self.get_group_actual_hours(group=group) min_hours = datetime.timedelta(hours=farm.min_pasture_hours) print("before action: ", total_hours) print("before action type:", type(total_hours)) days = total_hours / min_hours print("After action: ", total_hours) print("After action type: ", type(total_hours)) return days I added the print statements to try and understand this behavior. the output of this: before action: 8:43:54 before action type: <class 'datetime.timedelta'> After action: 8:43:54 After action type: <class 'datetime.timedelta'> before action: None before action type: <class 'NoneType'> 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 "/home/yovel/PycharmProjects/scr/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/yovel/PycharmProjects/scr/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/yovel/PycharmProjects/scr/venv/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/yovel/PycharmProjects/scr/venv/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute output = … -
Static directory declaration in Django did not catch typo error of 'STATICFILES_DIRS and 'collectstatic' command runs without error
I would like to write my observation here so that it will be helpful to others. I had a typo error in declaring the static directories in the Django setting.py. I had typed STATICFILES_DIR instead of STATICFILES_DIRS and I did not get any exception or error, even collectstatic command was not throwing any exception. Finally, I could point out the issue by posting the issue in SO. thank you -
i am getting this error when using list based views.no such table: first_app_theprofessionalresources
I am getting this error Exception Type: OperationalError Exception Value:no such table: first_app_theprofessionalresources when i am trying to use list views in django,classbased views. TEMPLATE: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> {%for p in resource_list%} {{p.Field}} {%endfor%} </body> </html> VIEWS.PY class TheProfessionalResourcesListViewCBV(ListView): context_object_name='resource_list' model=models.TheProfessionalResources MODELS.PY class TheProfessionalResources(models.Model): Field=models.CharField(max_length =100) Author=models.CharField(max_length=100) Title=models.CharField(max_length=100) ShortDesription=models.TextField(max_length=200) URL=models.URLField() type=models.CharField(max_length=20) SelfEmailAddress=models.EmailField(max_length=50) def __str_(self): return self.name URL.PY urlpatterns = [ url(r'^basic_skeleton/',views.basic_skeleton,name='basic_skeleton'), url(r'^first_app/',include('first_app.url')), url(r'^$',views.index,name='index'), url(r'^Professional_Development/',views.Professional_Development,name='Professional_Development'), url(r'^Personal_Development/',views.Personal_Development,name='Personal_Development'), url(r'^Financial_Development/',views.Financial_Development,name='Financial_Development'), path('admin/', admin.site.urls), ] second url.py urlpatterns=[ url(r'^$',views.basic_skeleton,name='basic_skeleton'), url(r'^Personal_Development/$',views.Personal_Development,name='Personal_Development'), url(r'^Financial_Development/$',views.Financial_Development,name='Financial_Development'), url(r'^Professional_Development/$',views.TheProfessionalResourcesListViewCBV.as_view(),name='Professional_Development'), url(r'^Resources_Professional/$',views.Resources_Professional,name='Resources_Professional'), url(r'^TheProfessionalResourcesCBV_list/',views.TheProfessionalResourcesListViewCBV.as_view(),name='list') ] please help i have nowhere mentioned that particular table first_app_theprofessionalresources why is it showing me that?I just want to list the fields form the mode and then view theier details in a separate page.PLease help. -
Django REST: queryset error type error int() must be a string
I'm trying to get all users who are employers. So what I did was I filter the users where the id can be found in the "employer" field of any (other) user. However this gives me the following error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' View: Get all employers class Employers(viewsets.ModelViewSet): queryset = CustomUser.objects.all() serializer_class = CustomUserSerializer def list(self, request): #queryset = CustomUser.objects.all(); queryset = self.queryset.filter(id__in=CustomUser.objects.filter(employer=id)) #this gives me an error serializer = CustomUserSerializer(queryset, many=True) return Response(serializer.data) Model (standard stuff): CustomUser model class CustomUser(AbstractBaseUser): username = None email = models.EmailField(verbose_name='email address', max_length=255, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) employer = models.ForeignKey("self", blank=True, null=True, on_delete=models.DO_NOTHING) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = MyUserManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(selfself, app_label): return True; I'm not sure what I'm doing wrong. Any suggestions?