Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Periodic increment to all records in one field
Is there a more efficient way of incrementing all records of a field every hour besides running a task that loops through all records at set time intervals and individually updates all records? For example, User_profile Model: username | coins_bought | coins_free | coins_spent Amadeus | 0 | 0 | 0 <-- new user has 0 coins throughout Ludwig | 5 | 5 | 3 Elise | 21 | 9 | 12 <-- old user with prior activity 1 hr later: username | coins_bought | coins_free | coins_spent Amadeus | 0 | 0+1 | 0 Ludwig | 5 | 5+1 | 3 Elise | 21 | 9+1 | 12 5 hr later: username | coins_bought | coins_free | coins_spent Amadeus | 0 | 5 | 0 Ludwig | 5 | 10 | 3 Elise | 21 | 14 | 12 In this example, users can buy coins or wait 1 hour until they all receive a free coin and can use in on the web-app. I can't make this feature client side, because it's not a mobile app, and caching is easy to corrupt. -
How to get type=time field in DJango
I am trying to use input type = time in Django. But every time my type = text. I have tried it: field_name = forms.TimeField() <!--return--> <input type="text" name="field_name" required id="id_field_name"> this: time_st = forms.TimeField(widget=forms.TimeInput(format='%H:%M')) <!--return--> <input type="text" name="time_st" value="" required id="id_time_st"> How to get an effect like this: <input type="time" id="appt" name="appt" class="form-control" required> -
Problems with inheritance from User class
I have these 2 classes, Teacher and Student, which inherit from a customized Django User class. When I try to create a new Student/Teacher I keep getting this error. Also I'm using postgres as database. I don't know if that changes something. Here's the Model file: class User(AbstractBaseUser, PermissionsMixin): username = ... first_name = ... last_name = ... email = ... date_joined = ... USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', 'first_name', 'last_name'] objects = UserManager() class Meta: verbose_name = _('user') verbose_name_plural = _('users') class Teacher(User): birth= models.DateTimeField(null=True) photo = models.ImageField(upload_to='image/', null=True) class Student(User): birth= models.DateTimeField(null=True) photo = models.ImageField(upload_to='image/', null=True) And here's the Views file: def signup(request): if request.method == 'POST': if request.POST['password1'] == request.POST['password2']: try: user = User.objects.get(username=request.POST['username']) return render(request, 'account/signup.html', {'error' : 'Username already taken! :('}) except User.DoesNotExist: user = Student.objects.create_user(request.POST['username'], request.POST['email'] ,request.POST['password1']) user.photo = request.FILES['image'] user.birth= request.POST['birth'] auth.login(request, user) return redirect('home') else: return render(request, 'account/signup.html', {'error' : 'Passwords dont match'}) else: return render(request, 'account/signup.html') -
What is the best way to handle cookies in django?
Is it better to use Django Cookies or Django Sessions for the task? Is there a case against using javascript directly. Thank you a lot for your response. This question caused me a lot of trouble. -
Unable to upload an Image with React Js to Django Rest API
I'm trying to upload an image to Django backend and in the Django rest API I'm trying to update an existing image my Django View @permission_classes([IsAuthenticated]) @api_view(['POST']) @parser_classes([MultiPartParser,FormParser]) def UpdateTeacherProfileView(request,pk): teacher = TeacherProfile.objects.get(user_id=pk) serializer = TeacherProfileSerializer(instance=teacher,data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) React Js side const hadelImage = (e) =>{ if(e.target.files[0] && e.target.files[0].name){ setUR(e.target.files[0]); } } const hadelSubmit = (e)=>{ e.preventDefault(); Axios.post('http://127.0.0.1:8000/account-api/updateteacher/3/',{ profile_pic:ur//e.target.files[0] },{ headers: { 'content-type': 'multipart/form-data' } }).then(res=>{ console.log(res); }).catch(err=>{ console.log(err); }) } when I try to upload the image it gives Multipart form parse error - Invalid boundary in multipart: None Why I'm getting this error, is there any other method to upload the image using React Js -
How to detect the language of an audio file?
I am working on a project were I need to detect the language of audio files that are stored in our data base. We want to pass the files into the language detection service and get the language back. I found some projects that do that. E.g., https://cmusphinx.github.io/ But they have stopped the project last year. Is there a kind of a best practice for doing that? -
ordering items in a list but keep getting AttributeError
I am trying to organise all the posts in this list that I've created in order by descending 'created'. This is my function: def posts_search_by_following(request, user_username): start = int(request.GET.get('start') or 0) end = int(request.GET.get('end') or (start + 9)) profile = get_object_or_404(User, username=user_username) following_users = profile.get_following() posts = list()[start:end] for person in following_users: posts += Post.objects.filter(creator=person).order_by('-created') return JsonResponse( {'posts': [post.serialize() for post in posts]} ) As it is right now, it is only ordering posts by their 'created' field per person. So when the whole list is returned everything isn't all in order. However if I try to move .order_by('created') anywhere else: {'posts': [post.serialize() for post in posts].order_by('created')} it will give me an Attribute error like this: AttributeError at /posts/Moderator/following/search 'list' object has no attribute 'order_by' How can I get the total number of posts and then order them accordingly? -
Docker compose - python: can't open file 'manage.py': [Errno 2] No such file or directory
I want to create with docker-compose 2 Docker containers. 1 for DB (Postgres) and 1 for web (Django). Here are my files docker-compose.yml version: '3.7' services: api: build: ./portal command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - 8000:8000 env_file: - ./portal/.env db: image: postgres:13p.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=portal - POSTGRES_PASSWORD=portal - POSTGRES_DB=sterling volumes: postgres_data: Dockerfile # pull official base image FROM python:3.8.3-alpine # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip RUN apk add --no-cache \ build-base cairo-dev cairo cairo-tools \ # pillow dependencies jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev RUN pip install "flask==1.0.1" "CairoSVG==2.1.3" COPY ./requirements/base.txt . RUN \ apk add --no-cache python3 postgresql-libs && \ apk add --no-cache --virtual .build-deps gcc python3-dev \ libxml2 libxml2-dev musl-dev postgresql-dev && \ apk add libxslt-dev && \ python3 -m pip install -r base.txt --no-cache-dir && \ apk --purge del .build-deps # copy project COPY . . when i run docker-compose up it throws me the following error: web_1 | python: can't open file 'manage.py': [Errno 2] No such file or directory Do you have an idea why docker-compose doesn't find … -
Django channels websocket not receiving data sent
I'm currently learning how to use Django channels for websocket connections and so far I've gotten the websocket to actually connect, but when I send it data it doesn't receive it. This is my consumers.py class WSConsumer(AsyncConsumer): async def websocket_connect(self, event): print('connected', event) await self.send({ 'type': 'websocket.accept' }) await self.send({ 'type': 'websocket.send', 'message': 'TEST' }) print('sent') async def websocket_disconnect(self, event): print('disconnected', event) async def websocket_receive(self, event): print('received', event)) This is my javascript on the front end const roomName = JSON.parse(document.getElementById('room-name').textContent); const WSocket = new WebSocket( 'ws://' + window.location.host + '/ws/room/' + roomName + '/' ); WSocket.onopen = function(e) { console.log('websocket has connected'); }; WSocket.onmessage = function(e) { console.log(e); }; WSocket.onclose = function(e) { console.error('websocket closed unexpectedly'); }; -
How do I integrate the Google Calendars API into a Django project?
For our website, we want users to be able to enter an event name, start time, and number of hours (event duration) into a form, and for this information to then be used to generate the appropriate Google Calendars event. One concern we had was that the start/end date strings look like they are very specifically formatted, so we were wondering how to translate the form input into start/end time strings. -
passing form object to session variable in django
I'm making an email confirmation system in my django project at the moment and my system is as follows: When a new user creates an account, a randomly generated code is created for that account. The user is then redirected to a confirmation page where they input the code that was generated for them in an email they will receive. My problem is that when I try put the form object from the registration for into a session variable to be used on the confirmation page (so that the form can be saved to the database), I get an error saying that the RegistrationForm object (created in forms.py) is not JSON serializable. Any help would be much appreciated and I feel like this is a simple fix. # forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): email = forms.EmailField(max_length=60, help_text="Required add a valid email address.") class Meta: model = Account fields = ("email", "username", "restaurant_name", "password1", "password2") # views.py def registration(request): context = {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): email = form.cleaned_data.get("email") # setting all the necessary variables for the session variable request.session["account_data"] = { "email": form.cleaned_data.get("email"), "code": generate_account_code(), "form": form, } # confirm is … -
Django URL to Template View Preventing Media Folder from Displaying
I have been working on a Django DRF/Vue project and ran into issues with being able to download or view files from the media folder. I have this set up as a media root and directory in the settings and included the following in my url.py file: if settings.DEBUG: urlpatterns += static( settings.STATIC_URL, document_root = settings.STATIC_ROOT ) urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) The issue is happening from my path to the template views. re_path(r"^.*$", IndexTemplateView.as_view(), name="entry-point") If I comment this line out, the media directory works as I want but this causes my application to no longer direct users to my frontend and Django template files. I am fairly new to Django and am not sure exactly how to resolve this, or if it is possible to create a condition within the path to exclude /media from being triggered? I would appreciate any advice you can give. Cheers! -
TypeError: main() missing required positional argument request, while I have the argument request in the main function
I am new to Stack Overflow and I am learning Django from youtube. I am following tech with Tim's tutorial for Django and React JS. So in the first tutorial, I got an error while performing the migrations for manage.py where it gave me an error that there is am argument missing om the main function that returns the HttpResponse and that argument is request I have already included the request parameter in my main() function. If you guys wanna see the code just go to tech with Tim's channel and tutorial 1 for Django and react js that's all that I did. -
How do you get the "user_id" of the token payload into the JSON POST form?Django REST, simpleJWT, Vue3
So i have access and refresh tokens in my local storage. The decoded access token has "user_id" in the payload. I have a problem understanding how do you make a POST request to the REST API, where the JSON form includes the "user_id" of the currently logged in user. Do i get it from the stored JWT or is there another way? For a valid POST request i need 3 fields: { "post_author": "field, which needs the currently logged in user, aka user_id from the token " "post_body": "some text" "post_title": "some text" } Simplified question, how do you get the "user_id" of the decoded token into the JSON form? createPost.vue <template> <div id="authenticationDiv"> <div> <input type="text" v-model="postTitle" placeholder="post_title" /> <input type="text" v-model="postBody" placeholder="post_body" /> </div> <br /> <button @click="createPost">Submit Post</button> </div> </template> <script> import { getPosts } from "./importable_functions"; import { ref } from "vue" export default { setup() { const ACCESS_TOKEN = "access_token"; const postTitle = ref(""); const postBody = ref(""); async function createPost() { // var csrftoken = getCookie("csrftoken"); fetch("http://127.0.0.1:8000/api/create_post/", { method: "POST", headers: { "Content-type": "application/json", // "X-CSRFToken": csrftoken, Authorization: `Bearer ${window.localStorage.getItem(ACCESS_TOKEN)}`, }, body: JSON.stringify({ post_body: postBody.value, post_title: postTitle.value, // post_author: }), }).then((response) => { getPosts(); … -
Custom Permissions on a DRF Generic View
I have two models: class Service(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) class Order(models. Model): user = models.ForeignKey(User, on_delete=models.CASCADE) service= models.ForeignKey(Service, on_delete=models.CASCADE) I have a view that returns the orders for a specific listing: class ServiceOrdersView(generics.ListAPIView): serializer_class = OrderSerializer def get_queryset(self): service = Service.objects.get(id=self.kwargs['service_id']) return Order.objects.filter(service=service) It works fine and the expected results are returned, but how do I make it so that only the owner of the listing can call the view and get the results? -
How to set the default url when i run server in Django
In Django, When I run server, default url always come out with http://127.0.0.1:8000/blog/ But i want justin http://127.0.0.1:8000 url for start. How can i change the default of url? In urls.py, there are no redirectview function. -
Resolution and customization of Django REST Framework permissions
I have a given url defined that's being managed by a single view. re_path(r'^something(?P<path>(/[^/]+)*)$', SomethingView.as_view(), name='something'), So, the view handles a matrix of ['POST','GET','PATCH','DELETE'] but it also has another matrix which is determined by the url path following the /something. examples: /something/color /something/shape so, the permission for POST /something/color can differ from POST /something/shape. I do have a custom permission set for the entire SomethingView but the has_permission is called before the view processes the full path of the URL and is completely in the dark if /color or /shape is part of the path, which defeats my purpose of having custom permissions for all combinations of METHOD + what's coming after /something My options: not using DJango REST permission classes and implementing permissions myself on the actual get/post/... methods Finding a way to customize Django REST permission classes to get real-time information from the actual pre-processing of the path + method used in the request. Any ideas on #2? -
Django REST framework .annotate(Count()) appears to return incorrect count
I have three models that look approximately like this: class Utterance(models.Model): id = models.SlugField(max_length=20, primary_key=True) class TransformationWav(models.Model): utt = models.ForeignKey(Utterance, on_delete=models.CASCADE, blank=True, null=True) parent_wav = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) trimmed = models.BooleanField(default=False) class TransformationMFBs(models.Model): utt = models.ForeignKey(Utterance, on_delete=models.CASCADE, blank=True, null=True) wav = models.ForeignKey('TransformationWav', on_delete=models.CASCADE) And I have a QuerySet generated with these filters that returns two Utterance objects with the same ID: >>> filters = {'transformationwav__trimmed': False, 'transformationwav__utt__id': "m00_00_040", 'transformationmfbs__wav__trimmed': False, 'transformationmfbs__utt__id': "m00_00_040"} >>> utterances = Utterance.objects.filter(**filters) >>> utterances <QuerySet [<Utterance: m00_00_040>, <Utterance: m00_00_040>]> I can successfully remove the duplicate utterance by using .distinct(), leaving only one utterance in the queryset: >>> utterances = utterances.distinct() >>> utterances <QuerySet [<Utterance: m00_00_040>]> >>> len(utterances) 1 >>> utterances.count() 1 However, when I then try to annotate the utterances with their counts by utterance ID, Count() finds two objects in the QuerySet: >>> utterances = utterances.annotate(count=Count('id')) >>> for utt in utterances: ... print(utt.id, utt.count) ... m00_00_040 2 So my question is, why does .annotate(Count()) find two objects here instead of one? Note: Though I can use .annotate(count=Count('id', distinct=True)) to get only one result, I feel like I shouldn't have to use distinct twice, because I already used it on the QuerySet. I have also … -
Trouble with ProxyPass of REMOTE_USER from nginx to Django
I have an nginx web server that's configured with client certificate authentication. Once authenticated, I proxy requests to a uWSGI Django application server. I've set-up my Django application to perform authentication using REMOTE_USER (https://docs.djangoproject.com/en/3.1/howto/auth-remote-user/), however it doesn't seem to be working as I receive the "'AnonymousUser' object is not iterable" error from Django. I'm assuming that I'm missing something in my nginx configuration: server { listen 80; server_name my.website.net; return 301 https://$server_name$request_uri; } server { listen 443 ssl; ssl_certificate /etc/letsencrypt/live/my.website.net/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/my.website.net/privkey.pem; ssl_verify_client on; ssl_verify_depth 2; ssl_client_certificate /etc/nginx/ssl/cas.pem; proxy_set_header X-SSL-Client-Serial $ssl_client_serial; proxy_set_header X-SSL-Client-Verify $ssl_client_verify; proxy_set_header X-SSL-Client-S-DN $ssl_client_s_dn; proxy_set_header X-Remote-User $remote_user; proxy_set_header REMOTE_USER $remote_user; location / { root /var/www/my.website.net; index index.html index.htm; } location /django { proxy_set_header Host 10.101.10.228; proxy_http_version 1.1; proxy_set_header Connection "Keep-Alive"; proxy_set_header Proxy-Connection "Keep-Alive"; proxy_pass http://10.101.10.228:8000/webapp; proxy_redirect http://10.101.10.228/django/ https://my.website.net/django/; } } I've also tried utilizing the nginx uwsgi_* directives with no luck: upstream django { server 10.101.10.228:8000; } location /django { include uwsgi_params; uwsgi_pass django; uwsgi_param SCRIPT_NAME /webapp; uwsgi_param REMOTE_USER $remote_user; uwsgi_param X-REMOTE-USER $remote_user; } Is there something that appears to be missing? -
Automatically adding inline formsets in django create view
I'm creating a questionnaire site with django, whereby a user can select a questionnaire to answer. There are two models - questionnaire and response - for storing the completed questionnaires. There are another two models - template and questions - which store details such as the questions contained in each questionnaire. I've got everything to work. When a user selects the questionnaire they want to complete, a function based view runs that fetches the necessary info from the template and questions model, saves those into the questionnaire and response models before returning an update view where the user can then answer the questions. This is done via an inline formset. My question is whether this can be replicated without having to save the questionnaire and response models first. This is so that if a user decides not to complete the questionnaire, it won't have been needlessly saved. How would I go about automatically adding inline formsets in the create view. I haven't added any of my code here as I'm only looking for some high-level guidance so I can then research further. -
Testing Ajax on Django
I'm trying to write a test for an Ajax get a request in Django. Here's how I tried. from django.test import TestCase from django.urls import reverse from .models import ResourcePost, User from register.models import DonorProfile from django.utils import timezone class getResourcePostTests(TestCase): def setUp(self): ResourcePost.objects.create( title="test1", description="test", quantity=10, dropoff_time_1=timezone.now(), dropoff_time_2=timezone.now(), dropoff_time_3=timezone.now(), date_created=timezone.now(), donor=createdonor_1(), resource_category="FOOD", status="AVAILABLE", ) ... def test_getResourcePost(self): rescource_post_1 = ResourcePost.objects.get(title="test1") rescource_post_2 = ResourcePost.objects.get(title="test2") rescource_post_3 = ResourcePost.objects.get(title="test3") response = self.client.get(reverse('donation:getResourcePosts')) self.assertEqual(response.status_code, 200) Here is my view: @login_required def getResourcePost(request): user = request.user curr_user_rc_1 = user.helpseekerprofile.rc_1 curr_user_rc_2 = user.helpseekerprofile.rc_2 curr_user_rc_3 = user.helpseekerprofile.rc_3 posts = ResourcePost.objects.all() passingList = [] for post in posts: if post.date_created >= user.helpseekerprofile.message_timer_before and ( post.resource_category == curr_user_rc_1 or post.resource_category == curr_user_rc_2 or post.resource_category == curr_user_rc_3 ): notiPost = { "id": post.id, "title": post.title, "description": post.description, } passingList.append(notiPost) context = {"resource_posts": passingList} return JsonResponse(context) This is my ajax code: $(document).ready(function () { setInterval(() => { $.ajax({ type: 'GET', url: "{% url 'donation:getResourcePosts' %}", success: function (response) { $("#display").html('<i class="fas fa-bell"></i>') let postCounter = 0 for (i = 0; i < response.resource_posts.length; i++) { postCounter += 1 } if (postCounter > 0) { $("#display").append('<span class="message-number">' + postCounter + '</span>') } }, error: function (response) { console.log("No DATA FOUND") } … -
Deduced attributes of a LazyAttribute using Factory Boy
Using Factory Boy and Faker in a Django project, i would like to create deduced attributes, meaning a method from Faker returns a set of values that are dependent of each other. These values will be utilized for the other attributes of the Factory Class. Example: The location_on_land method from faker.providers.geo returns a tuple of latitude, longitude, place name, two-letter country code and timezone (e.g. ('38.70734', '-77.02303', 'Fort Washington', 'US', 'America/New_York'). All values depend on each other, since the coordinates define the place, country, timezone, etc. Therefor i cannot use separated functions for the (lazy) attributes like faker.providers.latitude, faker.providers.longitude for my attributes. Is it possible to somehow access the return values from the lazy attribute to use them for other deduced attributes? Is there a better way to access the return values from location_on_land to use them on the other depending attributes My Factory-Class looks like this: # factory_models.py class OriginFactory(factory.django.DjangoModelFactory): """Factory for Origin.""" class Meta: model = models.Origin exclude = [ "geo_data", ] # not working since not a lazy attribute # lat, lon, place, iso_3166_alpha_2, _ = fake.location_on_land() # desired outcome (not working) geo_data = factory.Faker("location_on_land") # attributes using the return values of `location_on_land` from lazy attribute (pseudo-code, … -
OnetoMany relationship models: limiting the number of instances of a model that have the same foreign key in django
I am working on a Django project where a user is able to create instances of a model Route and can create instances of a model Address. I have related those 2 models by adding the rout_name from the route model as a foreign key in the address model. I want to limit the number of instances that belong to a certain route_name strictly in the range up 50 addresses. This means that the user can only add 50 addresses that belong to a specific route_name. SO if the user successfully adds 50 and then wants to add another address to the same route name, I want the app to give them a message saying " Sorry, Cannot add more addresses to this route". Any idea where I can put this condition so that the addresses added can only be 50 or less than 50 that belong to the same foreign key(which is route_name in my case)? Here is the models.py for both of my models: class Route(models.Model): username = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE) title = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) number_of_locations = IntegerRangeField(min_value=2, max_value=50, default=None) def __str__(self): return self.title def get_absolute_url(self): return reverse('route-detail', kwargs={'pk': self.pk}) class Address(models.Model): route_name = models.ForeignKey(Route, on_delete=models.CASCADE) … -
How to setup Virtual Environment for Django development without internet?
Every time I create a Virtual Environment for Django, from inside the virtual environment, I need to run pip install django which requires internet access. Can I somehow install django globally on my machine and "pull" it from inside the Virtual Environment? I am running Zorion OS(Ubuntu-ish). -
Using Django on google colab
I am trying to start a new project on djago in google colab. In order to create a new one, I need to use cmd command line - $ django-admin startproject Project name. Is there another way to do it? Thank you