Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have to click the button twice to make the onclick work
Here is my html and JS code. When I first click on the button it submits the form but doesn't call the onclick function. I've tried adding onsubmit method to the form and make button type=button. However, that didn't change anything. The form submission is for Django btw. <form action='' method='GET' required id='form_id'> <input class='url_box' type='url' name='url_value' placeholder='Paste the URL...'/> <br> <button class='submit-btn' type='submit' onclick="delayRedirect()">Listen</button> </form> JavaScript function delayRedirect(){ setTimeout(function(){ window.location = 'player'; }, 1500); } Thanks in advance! -
django cassandra not executing select query with where clause for datetime range
I have data in cassandra and I am trying to fetch data from the DB within a datetime range. Below is the code. fromdate = datetime.combine(dt, datetime.min.time()) todate = datetime.combine(datetime.now().date(), time(23, 59, 59)) print(fromdate) print(todate) batch = BatchStatement() batch.add(SimpleStatement("SELECT * FROM datadump WHERE 'pickup_time' >= '%s' AND 'pickup_time' <= '%s' ALLOW FILTERING;"), (fromdate, todate,)) data = session.execute(batch) The above code does not work when I try to fetch data within a datetime range but if I try to fetch all the data like "SELECT * from datadump" it works. Can someone please let me know what's wrong with the above approach? Thanks in advance! -
Python comma for loop conditional comma seperation
I want, when i for loop, there will be comma in the end of each item except the last item, last item should be dot x = ['df', 'second', 'something', 'another'] separator = '' for i in x: r = i print(r, separator) separator = ',' else: separator = '.' this is my current code. My expected result should be like this below: df second , something , another. can anyone help me in this case? -
Accessing Angular/Django Application deployed on EC2 through host computer
I have deployed 2 applications on a EC2 machines. 1. Angular 8 Application (frontend) running on 0.0.0.0:80 2. Django Application (backend) running on 127.0.0.1:8000 I am able to access my Angular (frontend) application through browser on http://localhost:80 and also getting successful response from my backend application. Whenever I am trying to access this application from any other system (present in the same network), I can still access my frontend application on http://public_ip:80, but not getting any response from the backend. -
How does .get() work on the back end of Django?
I'm trying to wrap my head around how django's .get() function works; it cant just be a simple LIMIT 1 because the exception it throws gives you the exact number of objects returned. So does django do a COUNT first and then a LIMIT 1? I'm not an SQL expert so I don't know if there's a better way to do it -
Resize images before uploading to google cloud storage django
I am trying to resize and compress images that are uploaded from my django app before it is uploaded to google cloud storage. I tried using firebase to resize any image that is uploaded automatically, but it gives giving resize error. I would like my django app to do this compression first before it is uploaded to google cloud. The standard pillow compression doesn't work on cloud storages. How can accomplish this? -
How to redirect python graph output to the same page using django?
Description of Image 1 - The HTML page shown in the image is divided into two parts. After the user selects the file & clicks the SUBMIT button the graph should be generated on the same HTML page in the second section. This graph is generated from the python code. I'm using Django, Python 3.7 & HTML. Description of Image 2 - The final output should appear as shown in the image. -
Error running 'Django' Can't run remote python interpreter: Process `docker-compose config` failed
I'm struggling with this error for hours now.. There is so little documentation on the internet about this error. All my docker "instances" are running (app, db, mongo,..) but running or testing application doesn't work due to this error. Anyone knows where I can start? It's really frustrating.. -
Dango: What is "the proper successor to" pinax.notifications?
pinax.notifications is a nice package but it uses the decorator @python_2_unicode_compatible and it apparently still tries to get it from django.utils.encoding rather than six. This is after running pip3 install --upgrade pinax.notifications just now. Is there a more up-to-date package that I should be using now? -
Run function on loading DetailView in Django
I would like to execute a function immediately upon loading a DetailView. Specifically, I have a Market model, and when users land on a DetailView using that model, I want the current_price on the relevant market to be saved in the most_recent_price feature of the relevant user. Here's what I have right now, which isn't doing anything - I don't get any error message or anything, it simply doesn't get executed: class MarketDetailView(LoginRequiredMixin, DetailView): model = Market template_name = 'question.html' login_url = 'login' def set_current_price_for_user(self, **kwargs): pk = self.kwargs['pk'] market = Market.objects.get(pk=pk) user = request.user user.most_recent_price = market.current_price I feel like I'm missing something basic here. What am I doing wrong? -
How to close all html popup window when I click logout button in django backend
I tried to close all the html popup window when I clicked on logout button. But when I tried with Httpresponse and javascript It's not working. So I have attached my code for better understanding. I can't understand what's happening. I tried to render with Httpresponse in views.py with the help of Javascript, But It's failed. Thanks in advance... Success.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <!-- Interaction Script Here --> <script type="text/javascript"> function win() { var secondWindow= window.open("{% url 'choice' %}","choice","height=700,width=700,scrollbars=no"); if(window.close()){ secondWindow.close(); } } function win1(){ var thirdWindow= window.open("authordetails.html","AUTHOR DETAILS","height=800,width=700,scrollbars=no"); if(window.close()){ thirdWindow.close(); } } function win2(){ var fourthWindow= window.open("maxsales.html","MAX. SALES","height=800,width=700,scrollbars=no"); if(window.close()){ fourthWindow.close(); } } function win3(){ var fifthWindow= window.open("updatePrice.html","CHANGE PRICE","height=800,width=700,scrollbars=no"); if(window.close()){ fifthWindow.close(); } } function win4(){ var sixthWindow= window.open("report.html","REPORT","height=800,width=700,scrollbars=no"); if(window.close()){ sixthWindow.close(); } } window.onload=function(){ window.resizeTo(700,700); window.open("{% url 'success' %}","success","width=700,height=700,scrollbars=no"); }; </script> </head> <body> <nav class="fixed-top"> <input type="checkbox" id="check" /> <label for="check" class="checkbtn"> <i class="fas fa-bars"></i> </label> <label class="logo">Book Managment</label> <ul> <li><p style="font-size:17px;color:white;">Welcome {{user.username}}</p></li> <li><a href="{% url 'logout' %}">Logout</a></li> </ul> </nav> <!-- Interaction Code Here--> <div class="suc"> <h1>Your Interaction</h1> <form action="{% url 'success' %}" method="POST"> <fieldset class = "insertion"> <div> <label for="insert">Insert Values</label> <button type="button" id="insert" onclick="win()">SELECT</button> </div> <div> <label for="details">View Author Details</label> <button type="button" id="details" … -
How to generate coverage reports programmatically using Coverage.py?
At present, I am generating coverage reports via coverage.py, by giving the coverage command which would thus generate an HTML report. Now I want to automate this whole process such that in my Django project I should have a URL and a corresponding view that should generate the coverage report for the whole project and render it as HTML file..! -
Django Serve Special files like favicon and manifest
How can I serve a directory as the default in Django? I build a django/react application. Got it all set up with uWSGI. Static files for both react and django working (using whitenoise for multiple static directories). But files like /favicon.ico and /manifest.json in the index.html built from react return a 404 error because they don't exist. How can I get django to attempt to serve files in the same directory as index.html if everything else fails? Currently I serve index.html by doing the following in Django: In myproject/urls.py: urlpatterns = [ path('', index, name='index'), path('favicon.ico', favicon, name='favicon'), ...other-stuff ] In myproject/views.py index = never_cache(TemplateView.as_view(template_name='myproject/index.html')) favicon = never_cache(TemplateView.as_view(template_name='myproject/favicon.ico')) The index works, but favicon doesn't. So what about the other files that need to be served? How can I define those files (anywhere from 4-20 files) to be served by uwsgi? -
Passing data from html to python
It is necessary to obtain information from the selected cell from the html file and then work with it in views.py. Is it possible and how to do it? Thank you in advance! <tbody> {% for element in qz %} <tr> <td class="counterCell"></td> <td style="display: none">{{ element.0 }}</td> <!-- information is needed for this cell when it is selected --> <td>{{ element.1 }}</td> <td>{{ element.2 }}</td> <td><span class="glyphicon glyphicon-trash"></span></td> </tr> {% endfor %} </tbody> -
'QuerySet' object has no attribute 'favourite'
Can any one please fix the problem. Here in this view I am getting the error . Actually I am adding the favourite list to the product and tried to write the view . listings/views.py from django.shortcuts import get_object_or_404, render from .choices import price_choices, bedroom_choices, state_choices from django.core.paginator import EmptyPage, PageNotAnInteger,Paginator fetch the data from .models import Listing, Comment from realtors.models import Realtor from sellers.models import Seller Create your views here. def index(request): #varname = modelname.objects.all() # listings = Listing.objects.all()//displaying in any order # now displaying the list in the latest date(descending) listings = Listing.objects.order_by('-list_date').filter(is_published = True) if listings.favourite.filter(pk = request.user.id): is_favourite = True #creating the pagination paginator = Paginator(listings, 3) page = request.GET.get('page') paged_listings = paginator.get_page(page) is_favourite = False context = { 'listings' : paged_listings, 'is_favourite':is_favourite } return render(request, 'listings/listings.html', context) def listing(request, listing_id): if request.method == "POST": name = request.POST['name'] message = request.POST['message'] proid = listing_id query = Comment(message = message, name = name ) # stars = stars query.proid_id = proid # query.stars = stars query.save() listing = get_object_or_404(Listing, pk = listing_id) seller = Seller.objects.all().filter(pk = listing_id) comment = Comment.objects.all().filter(proid = listing_id) context = { 'listing' : listing, 'comments':comment, 'seller':seller } return render(request,'listings/listing.html',context) def search(request): queryset_list = … -
Django: How to show second form on submit of first form without refreshing the page?
Hi all I am trying to display a second form without refreshing the page when I click on submit button of first form. Is there any solution for this? Thanks in advance. -
Deploying a Django Application (Apache, Passenger, Virtualenv)
Im stuck in deploying my working Django Application on a production PLESK server. The project can be started as a development server successfully by typing: httpdocs# cd mysite httpdocs/mysite# source myvenv/bin/activate httpdocs/mysite# export LD_LIBRARY_PATH="/usr/local/lib" httpdocs/mysite# python manage.py runserver <freyt.de>:8000 Then, if I point the browser to freyt.de:8000 I can see my app. Fine. Right now, I'm trying to call my app by Passenger from Apache. When checking with "passenger-config restart-app" it seems to run, but when curl freyt.de it shows me html with 403 Forbidden. So, I assume my Django app is not started successfully. This is my current folder structure: https://i.stack.imgur.com/8xNMG.png I already adjusted some topics in PLESK as follows: Apache Webserver: wsgi is activated I created a Service Plan and subscribed it with my domain freyt.de In the Service Plan under tab "Webserver" I added additional directives for HTTP as follows. PassengerEnabled On PassengerAppType wsgi PassengerStartupFile passenger_wsgi.py In the Service Plan under "Hosting Parameters" I enabled SSH access to the server shell: /bin/bash For the "Domain" I set the Document root to "..httpdocs/public". Also I added in "Apache & nginx Settings" the same directives. (I also tried without, but dont seem to have an effect.) Some details at … -
DRF when generating cookie sessionid
I am creating /auth/ page on my Django Rest Framework site. And I can not save session id. Have i create this cookie or its creating automatically? My auth view: class AuthView(APIView): permission_classes = (permissions.AllowAny,) renderer_classes = [TemplateHTMLRenderer] @csrf_exempt def get(self, request): return render(request, 'login.html', {}) @csrf_exempt def post(self, request): serializer = AuthFormSerializer(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.data username = data.get('username') password = data.get('password') if username is None or password is None: return Response({'error': 'Please provide both username and password'}, status=HTTP_400_BAD_REQUEST, template_name='login.html') user = authenticate(username=username, password=password) if not user: return Response({'error': 'Invalid Credentials'}, status=HTTP_404_NOT_FOUND, template_name='login.html') self.token, _ = Token.objects.get_or_create(user=user) user_token = Token.objects.get(user_id = user.pk) if (datetime.now() - user_token.created.replace(tzinfo=None)).days > 10: Token.objects.update(user_id=user.pk, key=Token.generate_key(user.pk), created = datetime.now()) context = {'token': self.token.key} # return Response(, status=HTTP_201_CREATED, template_name='') return HttpResponse(json.dumps(context), content_type="application/json") -
How to extend field in UserCreationForm in django?
I have been trying to add a phone number field in UserCreationForm so that on registration a user gives its phone number but unfortunately phone number is not storing. it accepts the Phone number on the registration page but it doesn't show the phone number on the webpage. I think it is not storing. forms.py class myCreateForm(UserCreationForm): ph= forms.CharField(max_length=400, required=True, label='Phone') class Meta: model = User fields = ['first_name', 'last_name' ,'username', 'email', 'password1', 'password2','ph'] def save(self, commit=True): user = super(myCreateForm, self).save(commit=False) user.ph = self.cleaned_data["ph"] if commit: user.save() return user views.py def register(request): form = myCreateForm() if request.method == "POST": form = myCreateForm(request.POST) if form.is_valid(): form.save() return redirect('loginPage') return render(request , 'register.html', {'form' : form}) template {%for i in user%} Hi {{i.first_name}}<br> Username : {{i.username}}<br> E-Mail : {{i.email}}<br> Phone : {{i.ph}}<br> {%endfor%} but on my webpage, it shows everything except phone number. Please Help Me Out -
How to keep Celery running in Django (drf) + Redis + WSGI (EC2)
I don't think its a very new question. I just could not find the right answer. I am trying to use Celery for background tasks while implementing a backend with the Django Rest Framework. I have a Redis server. Celery is working as expected with celery worker -A my_project --loglevel=info However, it does not work if I sop this command. How do I keep that running? I have found a blog with supervisor. I just want to know what is the standard (as well as easier) to do this. -
Formset not applying required=True
I use a formset, made of several forms, where each form contains a ModelChoiceField. However, while I wrote required=True for this field, I am able to post data although I do not select anything in it (when looking at the HTML source code, I can indeed check that required is not included in the select tag). Moreover, formset.is_valid() returns True contrary to what I expected. So far, I have managed to solve this by adding 'required' : 'required' in attrs (see below), but I guess it is not the usual way to achieve this. Here are my forms.py: class InitialForm(forms.Form): group = forms.ModelChoiceField(queryset=Group.objects.all(), required=True, label="Poule", widget=forms.Select(attrs={'class': 'select'})) nb_rounds = forms.IntegerField(min_value=1, max_value=5, required=True, label="Nombre de manches", initial=1, widget=forms.NumberInput(attrs={'class':'input', 'style': 'width:5ch'})) nb_teams = forms.IntegerField(min_value=2, max_value=5, required=True, label="Nombre d'équipes", initial=2, widget=forms.NumberInput(attrs={'class': 'input', 'style': 'width:5ch'})) class FinalForm(forms.Form): def __init__(self, *args, **kwargs): group = kwargs.pop('group') nb_rounds = kwargs.pop('nb_rounds') super(FinalForm, self).__init__(*args, **kwargs) self.fields['teams'] = forms.ModelChoiceField(queryset=Team.objects.filter(group=group), required=True, label="Equipe", widget=forms.Select(attrs={'class': 'select', 'required': 'required'})) for i in range(nb_rounds): self.fields['score_%i' % i] = forms.IntegerField(min_value=0, max_value=50, required=True, label="Score", initial=0, widget=forms.NumberInput(attrs={'class':'input', 'style': 'width:5ch'})) and views.py def initial_new_game(request): # GET request if request.method == 'GET': form = InitialForm() return render(request, 'initial_form.html', {'form': form}) # POST request else: form = InitialForm(request.POST) if form.is_valid(): request.session['group_id'] … -
Django: How do I upload an image to a folder named after the article slug
I defined two models Article, Article_photos. Photos present in each article is stored in the relevant Article_photos model. I intend to store multiple photos per article in this way. I want each photo to be uploaded to a folder by naming the folder in this manner: {slug}_images. This is Article model: class Article(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='Author') article_title = models.TextField() article_content = models.TextField() slug = models.SlugField(max_length=30, blank=True) ... def save(self, *args, **kwargs): self.slug = slugify(self.article_title) super(Article, self).save(*args, **kwargs) And the Article_photos model to store one or more photos: class Article_photo(models.Model): article = models.ForeignKey('Article', on_delete=models.CASCADE) photo = models.ImageField(upload_to='{}_images'.format(article.slug)) Now, when i'm running makemigrations, it's returning this error: AttributeError: 'ForeignKey' object has no attribute 'slug'. How do rename the folder in the pattern I want? -
Use mongoDB with django 3.0
As I said in the title I want to integrate mongoDB next to my Postgres Database in a Django3.0 project. I used to use djongo* but it seems it's not compatible with the latest version of Django. What do you think is the best connector to use mongoDB in a Django project ? *https://github.com/nesdis/djongo -
Django Serve Other Files and Default Route
If I should split this up into 2 questions I will but I have 2 major questions here. First Question How can I serve a directory as the default in Django? I build a django/react application. Got it all set up with uWSGI. Static files for both react and django working (using whitenoise for multiple static directories). But files like /favicon.ico and /manifest.json in the index.html built from react return a 404 error because they don't exist. How can I get django to attempt to serve files in the same directory as index.html if everything else fails? Currently I serve index.html by doing the following in Django: In myproject/urls.py: urlpatterns = [ path('', index, name='index'), ...other-stuff ] In myproject/views.py index = never_cache(TemplateView.as_view(template_name='myproject/index.html')) So what about the other files that need to be served? Am I supposed to be defining them all manually, or is there a way to do it properly? Second Question How can I get django to redirect all unknown urls to / Since the react part of the project uses react-router, it changes the url in the SPA. So if I go to /options in the app, it works, but if I were to … -
how to remove these usercreation forms instruction in django
class Driver_SignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): fields = ("username", "email", "password1", "password2") model = User help_texts = { 'username': None, 'email': None, 'password1': None, 'password2': None, } this is the code i already use the help text none but not working properly here is image of that