Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Exception inside application: __init__() takes 1 positional argument When adding ASGI_APPLICATION in Django 3.1 for channels
I am getting the following error when adding channels in Django. Exception inside application: __init__() takes 1 positional argument but 2 were given Traceback (most recent call last): File "/home/dell/Desktop/s/s/s-env/lib/python3.6/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/home/dell/Desktop/s/s/s-env/lib/python3.6/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/home/dell/Desktop/s/s/s-env/lib/python3.6/site-packages/channels/routing.py", line 160, in __call__ send, File "/home/dell/Desktop/s/s/s-env/lib/python3.6/site-packages/asgiref/compatibility.py", line 33, in new_application instance = application(scope) TypeError: __init__() takes 1 positional argument but 2 were give The application works fine on WSGI configuration.The above error only appears when ASGI_APPLICATION = 'app.routing.application' is added. Since it's showing error originating from static files, I have tried generating static files again but that doesn't help. -
Django cached_db creating multiple sessions for me
If I delete all entries in the django_session DB table, and put in settings.py (using Memcached): SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' Then if I log in, log out, then log in again, then check the number of rows in django_session I see there are 2 rows. I was not expecting that because according to the docs: If the user logs out manually, Django deletes the row. Then I removed setting the SESSION_ENGINE from settings.py, so that it's the default db session engine, then cleared all rows in django_sessions, and deleted all browser cookies. Then logged in, then out, then in again, and this time there is only one row. It seems like there is something not quite right with cached_db? The reason I am investigating this is I have set my cache to keep refreshing with: # Set to 2 months of inactivity SESSION_COOKIE_AGE = 2 * 31 * 24 * 3600 # Refresh session timeout on every request SESSION_SAVE_EVERY_REQUEST = True SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' However often when I return the next day (without loggin out), I need to log in again. It works fine while I am using the site for a (few hours?), I stay logged in. Here are my … -
How to iterate and display a list in Django template
I am working on a Django project and I would lke to render some data in my template from a view. However the data is not getting displayed. Here is my view def ReportForm(request): user = request.user username = request.user.username result = request.session.get('result') print(result) html = render_to_string('report-form.html',{'result': result,'user':user}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename=\" {} report form.pdf"'.format(username) print(result) weasyprint.HTML(string=html) \ .write_pdf(response,stylesheets=[]) return response The otpu of the result printed is [{"model": "results.result", "pk": 2, "fields": {"student": 3, "DataComm": 50.0, "TradeProject": 515.0, "WebDesign": 5.0, "ObjectOrinted": 55.0, "SystemAnalysis": 21.0, "Remarks": "Passed"}}] This is the data that I wish to render on a table in the teplate Here is my template {% for res in result %} {{res.DataComm}} {% endfor %} Can someone kindly assist me on how to iterate over and render the data in the template -
Can make user.pythonanywhere.com in DjangoGirls tutorial
Ive done all the work regarding DjangoGirls but user.pythonanywhere.com does not work I cannot make a website, only localhost works right for me and Im afraid if I do something with it the website might crash eventually and the problem I guess might be in settings.py file I have done all the things step-by-step, but at some point, some codes did not work and I had no hope to continue my work and I abandoned most of my djangogirls folders and created a so-called "test_djangogirls" folder which I also abandoned because if I did something with it, computer would have crashed I did all the Django installation on venv and it worked, but there is no work for user.pythonanywhere.com, I did everything like ls, cd,dir commands for directory and everything was in directory Before I did not have problems like that I cannot understand how can I get to user.pythonanywhere.com otherwise? -
Django: What are my options in speeding up load times when having to query large datasets for users from my postgres dB to my web-server?
I have an online dashboard that loads financial data for users through visual tables and graphs. Users can input a few values which will trigger POSTS to populate data (from my postgres db), tables, and graphs. Naturally load times tend to exponentially grow the more values inputted. My dashboard uses Plotly-Dash, here are some of the recommendations that they recommend. There are several ways to improve speed using client-side callbacks using Javascript. (not an option for me right now as I don't know JS). Download necessary and repeated data during page load. Implement caching though several ways (redis, flask_caching, etc...) Reduce the amount of @callbacks Apart from my web-server, I can always optimize my postgresql requests to improve speed, but how much would that really improve speed if I'm just pulling data (using SELECT, ROUNDS, CAST, but nothing heavy on calculations. Calculating the STD for one data parameter is as far as I go) My questions are the following: Would it be better to store one large dataframe on website load, in a dictionary of dataframes rather? For reference, users need to pull around 500-10,000 rows of data (that's only because I don't want to increase the limit for now, … -
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 …