Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a one to many relationship in Djando/Mysql?
Hi, there. Can someone help me understand how to make a one to many relationship in Django/Mysql? Here is models.py (code below) class Flora2Estado(models.Model): estado = models.OneToOneField(Estados, models.DO_NOTHING, primary_key=True) especie = models.ForeignKey('Listaflor', models.DO_NOTHING) class Meta: managed = False db_table = 'flora2estado' unique_together = (('estado', 'especie'),) class Listaflor(models.Model): especie = models.OneToOneField(Flora2Estado, models.DO_NOTHING, primary_key=True) familia = models.ForeignKey(Familia, models.DO_NOTHING, blank=True, null=True) nome = models.CharField(db_column='especie', max_length=255, blank=True, null=True) # Field renamed because of name conflict. class Meta: managed = False db_table = 'listaflor' class Estados(models.Model): estado_id = models.AutoField(primary_key=True) estado_nome = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'estados Thanks a lot. -
ModelChoiceField Customization (django-forms)
I have the following setup: MODELS.PY class MeatMenu(models.Model): MEAT_CHOICES = ( ('chicken', 'Chicken'), ('beef', 'Beef'), ) meat_type = models.CharField(max_length=20, choices=MEAT_CHOICES) meat_price = models.DecimalField(max_digits=10, decimal_places=2) In the same model file, I use the MeatMenu model as a fk to allow users to buy the meat they want (can calc total cost using price [hence the need for a fk as opposed to direct model choices]) class BuyMeat(models.Model): client = models.ForeignKey(User, on_delete=models.CASCADE) meat_needed = models.ForeignKey(MeatMenu, on_delete=models.SET_NULL, blank=True, null=True) date_created = models.DateTimeField(default=timezone.now) class Meta: ordering = ('-date_created',) def __str__(self): return str(self.meat_needed) FORMS.PY In my form, I'm trying to have a user execute an order for the meat they want as follows: class BuyMeatForm(forms.ModelForm): meat_needed = forms.ModelChoiceField(queryset=None, to_field_name='service_name', widget=forms.RadioSelect, empty_label=None) class Meta: model = BuyMeat fields = '__all__' exclude = ('client', 'date_created') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['service_needed'].queryset = MeatMenu.objects.all() VIEWS.PY def buy_meat(request): if request.method == 'POST': form = BuyMeatForm(request.POST) if form.is_valid(): new_purchase = form.save(commit=False) new_purchase.client = request.user new_purchase.date_created = timezone.now() new_purchase.save() else: form = BuyMeatForm() context = {'buy_form': form} .................... PROBLEM The problem comes in customizing my "meat_needed" field in the form. As you can see in my forms.py file, I would like to customize the foreignkey dropdown-select into radio buttons whereby … -
Calculate loss and profit based on expenses in Django
I am hoping someone can guide me. Basically , I would like to, using Django, to calculate either profit or loss based on expenses. For example, if I bought animal feed for 1 k and veterinary services cost another k, and there are other expenses within a month. After selling milk produce, I’d like to take the total amount received and deduct the expenses and return the margin. -
I cant solve this problem with python/django/oracle stored procedures
im working on a project with python, django and oracle db (with stored procedure as a requirement). Im new working with python and im trying to solve this problem, can you see what is the problem? this is the pythons function: The oracle PL/SQL stored procedure: And the "subtarea" table Can you please help me? -
Problems trying to get data
I am developing an application that sends data and represents it in a graph, the problem is that when I print the data it does it the way I want it, but when returning the data it only sends the first one, not the rest. This is my view. class DeveloperDatailView(DetailView): template_name = 'dates/dates.html' model = Developer def activities_porcentage(self): projects = Project.objects.filter(developer=self.kwargs['pk']) for project in projects: tasks = Task.objects.filter(project=project).filter(state=True) for task in tasks: activities = Activities.objects.filter(task=task).count() complete = Activities.objects.filter(task=task).filter(process=False).count() data = int((complete * 100) / activities) return data def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['projects'] = Project.objects.filter( developer=self.kwargs['pk']) context['quantity'] = Project.objects.filter( developer=self.kwargs['pk']).count() context['activities'] = self.activities_porcentage() return context -
static file serving with django/react/heroku
I have a small React/Django app deployed to Heroku, and I'm struggling to understand how static files are served. I've gotten as far as getting Django to serve the React entry point, but none of the images are showing up. The images are located in project-root/public/static, so that they will be copied to project-root/build/static when the project is built. (npm run build) For example https://ytterblog.herokuapp.com/build/static/photosquat-cropped.jpg returns a 404, despite the fact that the file is located in project-root/build/static/photosquat-cropped.jpg which becomes /app/build/static/photosquat-cropped.jpg when deployed to Heroku. I think I'm not configuring static file serving properly. I also don't really know what whitenoise is. Any help? Here's my settings.py file: """ Django settings for ytterblog_server project. Generated by 'django-admin startproject' using Django 3.1.3. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import django_heroku import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'rn!n3atk9adpep08=e%xge16x@7e0s_%fvpx@e=hwxa2@lf8hk' # SECURITY WARNING: don't run with debug turned on in production! DEBUG … -
vue slider help pls click img datatbase
when the image is clicked, the images need to be changed I cannot retrieve images from the database in script I have a django backend part I can’t from the databases I can’t use this in vue function <script> export default { name: 'Single', props:['id','img1'], data() { return { mds: {}, } }, created() { this.loadShop() }, methods: { async loadShop() { this.mds = await fetch( `${this.$store.getters.getServerUrl}/mds/${this.id}` ).then(response => response.json()) console.log(this.mds) console.log(this.id) }, } } </script> my html I want to make a slider on and click like in a photo but not a magician <div class="col-md-12" style=""> <img :src="'http://127.0.0.1:8000'+mds.img1" class="img-responsive" /> </div> <div class="col-md-12" style="margin-top:10px;"> <div class="col-md-2"> <img :src="count" class="img-slider" @click="slid()"/> </div> <div class="col-md-2"> <img :src="'http://127.0.0.1:8000'+mds.img2" class="img-slider" @click="slid()"/> </div> <div class="col-md-2"> <img :src="'http://127.0.0.1:8000'+mds.img3" class="img-slider" @click="slid()"/> </div> <div class="col-md-2"> <img :src="'http://127.0.0.1:8000'+mds.img4" class="img-slider" @click="slid()"/> </div> <div class="col-md-2"> <img :src="'http://127.0.0.1:8000'+mds.img5" class="img-slider" @click="slid()"/> </div> <div class="col-md-2"> <img :src="'http://127.0.0.1:8000'+mds.img6" class="img-slider" @click="slid()"/> </div> </div> I want to make a slider on and click like in a photo, but I can't I want to make a slider on and click like in a photo, but I can't I want to make a slider on and click like in a photo, but I can't I want to … -
Django Whitnoise/Heroku:whitenoise.storage.MissingFileError
I have ran into thise problem that is preventing me from using heroku and whitenoise. I have checked the doc of Whitnoise, they mentioned this: WHITENOISE_MANIFEST_STRICT Default True Set to False to prevent Django throwing an error if you reference a static file which doesn’t exist. This works by setting the manifest_strict option on the underlying Django storage instance, as described in the Django documentation: If a file isn’t found in the staticfiles.json manifest at runtime, a ValueError is raised. This behavior can be disabled by subclassing ManifestStaticFilesStorage and setting the manifest_strict attribute to False – nonexistent paths will remain unchanged. Note, this setting is only effective if the WhiteNoise storage backend is being used. I have already set manifest_strict to false WHITENOISE_MANIFEST_STRICT=False But where in the setting file should I put it , and how to I subclass ManifestStaticFilesStorage? I am very thankful for any help, wish you all a good day. -
how send aes encrypted document as a response in django
I am making a web app using Django I want to send some encrypted file to the user when he tries to click on the button. I am using return FileResponse(open("media/book/a_enc.pdf" , 'rb')) but it is giving me an internal server error. how can I send an encrypted file to a user in django -
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.