Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i apply changes when clicking on an html checkbox in a django project?
In my current django project I have the following model: Python 3.7.1 / django 3.0 class SampleClass(models.Model): active = models.BooleanField(default=False) and the following template code with 'sample' as an instance of the SampleClass above (only small snippet): HTML / django template language <form action='#' method='post'> <input type='checkbox' name='is_active_checkbox' {% if sample.active %}checked{% endif %}> </form> Now, when the state of the checkbox is changed, I would like to immediately apply the change to the django database, without reloading the page (if possible). Is there any way to do that? -
I'm trying to create a button like in django
I have created a model and would like to use a like button afterwards It did not work.How can I connect users and HTML with a function in views.py. accounts.modles.py class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) likes = models.ManyToManyField(User,related_name='likes',blank=True) profilepic = models.ImageField(upload_to='profile_pic',blank=True) likeme.views.py def like_post(request): obj = get_object_or_404(UserProfile,id=request.POST.get('userprofile_id')) obj.likes.add(request.user) return redirect('profile_details') likeme.ursl.py path("like/",likeview.like_post,name="like_post") like.html <form class="" action="{% url 'like_post' %}" method="POST"> {% csrf_token %} <button type="submit" name="post_id" value="{{ user.id }}" class="btn btn-info">Like</button> </form> -
NoReverseMatch at /rosetta/. Reverse for 'rosetta-file-list' not found
I want to add rosetta to my project and use it. First I installed it using pip -> 'pip install django-rosetta' Then I added it to my INSTALLED_APPS After that, I added the rosetta url to my project urls: url(r'^rosetta/', include(('rosetta.urls', 'rosetta'), namespace='rosetta')), But when I run the project and go to "http://127.0.0.1:8000/rosetta/", it send me back this error: NoReverseMatch at /rosetta/ Reverse for 'rosetta-file-list' not found. 'rosetta-file-list' is not a valid view function or pattern name. I have no idea where the problem is. Can anyone help me with this? Thanks in advance. -
How to call an auth view from another view
I want to execute a custom logic block in a view before the PasswordResetView is called. This is what I am trying to do, which of course always fails regardless the code, I must be taking a non adequate route to achieving this. I need to save some information, do some internal notifications and only call the password reset view if a condition is met. views.py from django.contrib.auth.views import PasswordResetView def user_password_reset(request): # Do something here before loading the passwordresetview # Logic here return PasswordResetView.as_view(template_name = 'account/password_reset_form.html', email_template_name='account/password_reset_email.html', html_email_template_name='account/password_reset_email.html', success_url = reverse_lazy('account:password_reset_done')) Which is the standard way of achieving this? Many thanks in advance. -
My chat consumer is not working django-channels?
I am tryna make a one-one chat application but my chat socket get's disconnected immediately when i send the data to it.I think the problem is in my asynchronous recieve function of my consumer? It's not giving me any reason for the error?The socket disconnects silently Here's the recieve handler async def receive(self, text_data): data = json.loads(text_data) text = data['message'] room_name = data['room_name'] username = data["username"] only_one_user = False profile = self.scope["user"].profile # GET THE ROOM AND THE PROFILE room_obj = await database_sync_to_async(Room.objects.get)(pk=self.room_name) other_user = await database_sync_to_async(room_obj.other_user)(profile) # CREATE AND ADD THE MESSAGE TO THE ROOM message = Message.objects.create(author=profile,text=text,to=other_user.user.username) room_obj.messages.add(message) room_obj.updated = timezone.now() room_obj.save() profile = self.scope["user"].profile clients_connected = await database_sync_to_async(Websocketclient.objects.filter)(room=int(self.room_name)) if clients_connected.count() < 2: only_one_user = True # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'data': {"text":text,"pk":room_obj.pk,"author":{"username":message.author.user.username,"image":str(message.author.image)},"only_one_user":only_one_user} } ) Also how can i know what exactly is the error in my code if i get any in future work... -
Why does a queryset applied in a ModelForm not inherit a queryset from a ModelManager?
I have a custom queryset on a model manager: class TenantManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(myfield=myvalue) class TenantModel(TenantModelMixin, models.Model): objects = TenantManager() class Meta: abstract = True I use the abstract TenantModel as a mixin with another model to apply the TenantManager. E.g. class MyModel(TenantModel): This works as expected, applying the TenantManager filter every time MyModel.objects.all() is called when inside a view. However, when I create a ModelForm with the model, the filter is not applied and all results (without the filter are returned. For example: class AddPersonForm(forms.ModelForm): person = forms.ModelMultipleChoiceField( queryset=MyModel.objects.all(), ) class Meta: model = MyOtherModel fields = ('person', ) Why is this and how to I ensure the ModelManager is applied to the queryset in ModelForm? -
I have created app in django and mapped views and the urls but still im not able to see the response. Please help me out to resolve this
Next, start your first app by running python manage.py startapp [app_label]. You're seeing this message because you have DEBUG = True in your Django settings file and you haven't configured any URLs. Get to work! -
How do I map urls to views in Django, getting AttributeError: module 'myproject.views' has no attribute
I just started learning django and running the tutorial part 3, decided to see if I understood the mapping from urls.py to views.py. I got views and urls to work in the polls app, but then I wanted to make views in the project folder, so I made a views.py file in the project folder (see code below), with a view/function , which I named 'home'. I then edited the urls.py in the project-folder(see below). run the server, It worked! visiting the url: http://localhost:8000/ it responded: Hello, world. You're at the HOME PAGE. BUT.. when I tried to make another view in same views.py called: morn, and adding the url for it, then error (see below), http://localhost:8000/morn returning: localhost refused to connect. I DID IT EXACTLY THE SAME WAY, so just when I thought I understood it, I didnt get it at all?!?! The difference between the two views are just their name and path, why doesnt it work then? on a linux manjaro Python 3.8.1 Django 3.0.3 # #this is my urls.py (which I made myself), in the project folder from django.urls import include, path from django.contrib import admin from . import views #from views import morn admin.autodiscover() urlpatterns … -
Run celery task for specific time period
I'm developing web app using django, and I'm using celery to run task in background. Everything is working fine, But i have one issue, I want to run celery task for the specific time period like from 2pm to 3pm. -
How to display images wrapped inside url() in Django
Here is the following code in an html file: <div class="hero-wrap js-fullheight" style="background-image: url('images/bg_1.jpg');" data-stellar-background-ratio="0.5"> I'm new to web development and am trying to figure out where I need to put the {% static ' ' %} command to display images/any style when they are referred through url(). I added the {% load static %} at the top already. Can anyone help me with this? Thanks! -
form is not getting rendered in django
the model class is : class Product(models.Model): name=models.CharField(max_length=120) address=models.CharField(max_length=120) trek=models.CharField(max_length=120) transid=models.CharField(max_length=20 ,default="") the form class is class formm(forms.ModelForm): class Meta: model=Product fields=('name','address','trek','transid') #fields="__all__" # exclude=['title'] the form part of html is <div class="jumbotron"> <form method="post"> {% csrf_token %} {{ form.as_p }} <input class="btn btn-primary" type="submit" value="SUBMIT"/> </form> </div> the function in view is def book(request): form=formm() if request.method == 'POST': form = formm(request.POST) if form.is_valid(): form.save() return redirect('/') else: form=formm() return render(request, 'trek/contact.html', {'form': form}) The form is not getting rendered .Only the submit button is getting shown. -
In Python Shell, Choice option is not giving a correct output [closed]
https://i.stack.imgur.com/Wf7vJ.png q.choice_set.create(choice_text="Django", votes=0) -
Django Rest Framework: View That Supports Arbitrary HTTP verbs?
Is there a view type that will, for example allow me to both: GET /account/items and POST / PATCH account/items/<UUID>/ all in one go? From one Viewset or something? Note that I am not creating anything in POST– I just need the call. As far as I can tell, I would need to make two separate views, one for getting the list via GET /account/items and one for doing custom POST and PATCH operations on a detail view. Is that right? -
authenticate(request, username=username, password =pswd) returns None for custom user model
The authenticate() function is returning none for registered users in mySQL db. I am using custom user verification, in which the registeration process works perfectly. I am using Django 3.0 The value of Account.objects.get(username = "uname").password == request.POST['password'] is True here is my models.py # Create your models here. class Account(AbstractBaseUser): username = models.CharField(max_length = 50, unique= True) email = models.EmailField(verbose_name = "email", max_length = 50, unique=True) #few other fields... USERNAME_FIELD = "username" REQUIRED_FIELDS = ['email'] objects = AccountManager() # any object from Account.object will return __str__ def __str__(self): return self.username #give permitions to custom user object def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True views.py def login(request): context = {} if request.method == "POST": form = AuthenticationForm(request.POST) if form.is_valid:#returns True name = request.POST["username"] pswd = request.POST["password"] user = authenticate(request, username = name, password = pswd) print("user = " + str(user)) #always returns None if user: print("valid user " + str(user)) login(request, user) print("user is " + str(request.user.is_authenticated)) return redirect("../dashboard/") form = AuthenticationForm() context['login_form'] = form return render(request, 'login.html', context) settings.py AUTH_USER_MODEL = "authenticate.Account" AUTHENTICATION_BACKENDS = ( #'authenticate.Accounts.' 'django.contrib.auth.backends.ModelBackend', ) could you please see what the mistake is? please excuse my etiquettes as this is my first … -
Django - Issues with Media Files
After I upgraded my django project to the latest version (3.0.3), the images are gone. The paths are the same as before, but the browser cant load them. I dont get any errors in the browser console like a 404 or 403. models.py def get_filename_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.splitext(base_name) return name, ext def upload_image_path(instance, filename): new_filename = random.randint(1,3943534353) name, ext = get_filename_ext(filename) final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext=ext) return 'media/{new_filename}/{final_filename}'.format( new_filename = new_filename, final_filename = final_filename ) class ModelA(models.Model): model_name = models.CharField(null=True, blank=True, max_length=20) model_thumb = models.ImageField(null=True, blank=True, upload_to=upload_image_path) model_date = models.DateTimeField(null=True, blank=True, auto_now_add=True) index.html {% if obj.model_thumb.url is not 0 %} <img class="main_cont_panel_slideshow_thumb" src="{{ obj.model_thumb.url }}"/> {% else %} {% endif %} settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') urls.py if settings.DEBUG: urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) The image paths I get in the template match with the media path. One path looks like this: /media/media/1590022831/1590022831.jpg In the project folder, there is a media folder with another media folder in it. In this media folder there are folders for every image I uploaded. The same setup as I had before, but now it does not work anymore. Thank you -
django search page throwing data
I am facing bit of difficulty in making search page work. The problem is my template and view throwing data on search page. And my search button function doesnt works. If some one can have a look and advise what i m missing would be highly appreciated. Thanks in advance. this is how ugly my search page looks following is my view : from django.shortcuts import render # Create your views here. #from django.shortcuts import render from django.http import HttpResponse from .mongodb_connection import mongosearch from .models import AppModel from django.db.models import Q # Create your views here. def search_view(request): model = AppModel template_name = 'search.html' results = [] title_term = "" desc_term = "" search_term = "" url_term = "" titles = AppModel.objects.all() url = AppModel.objects.all() if 'search' in request.GET: search_term = request.GET['search'] titles = titles.filter( Q(title__icontains=search_term) | Q(desc__icontains=search_term) ) titles = AppModel.objects.all() results = mongosearch(title=title_term #,desc = desc_term) ) print(results) context={ 'results':results, 'search_term':search_term, 'titles':titles } return render(request, 'search.html', context) following html page <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <!doctype html> <html> <nav class="navbar navbar-light bg-light"> <form class = "form-inline my-2 my-lg-1" method = "GET"> <!--action = "{%url 'search_view'%"> --> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name = 'search' value = … -
Check inputted link is from YouTube
I want to be able to allow a user to embed YouTube videos onto their profile via copying and pasting a link into a text field and having django automatically insert the link into a YouTube iframe to display. However I would like to python to check the link a user copy and pastes into the text field is from YouTube before the form submits. How would I go about doing this? Cheers -
django-allauth: facebook login button wouldn't do anything
I am using django-allauth library to integrate Facebook login into my website (on localhost). The problem is the following: when I have finished setting everything up and I try to click on my Facebook login button, nothing occurs at all. On hover, the browser shows the following link on the Facebook login button: javascript:allauth.facebook.login... I have the following code. In settings.py: ALLOWED_HOSTS = [ '127.0.0.1', 'localhost', ] INSTALLED_APPS = [ ... 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', ] ... ... ... AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "accounts.backends.EmailAuthenticationBackend", "allauth.account.auth_backends.AuthenticationBackend", ] SITE_ID=1 SOCIALACCOUNT_PROVIDERS = \ {'facebook': {'METHOD': 'oauth2', 'SCOPE': ['email','public_profile', 'user_friends'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'verified', 'locale', 'timezone', 'link', 'gender', 'updated_time'], 'EXCHANGE_TOKEN': True, 'LOCALE_FUNC': lambda request: 'kr_KR', 'VERIFIED_EMAIL': False, 'VERSION': 'v2.4'}} In urls.py (general project urls, however I tried to set this for accounts.urls separately, to no avail either): urlpatterns = [ ... path('', include('accounts.urls')), path('accounts/', include('allauth.urls')), path('admin/', admin.site.urls), ] In signup.html: ... <a class="facebook-login" href="{% provider_login_url "facebook" method="js_sdk" %}"> <i class="ion-logo-facebook"></i> <div>Sign up with Facebook</div> ... I have tried reconfiguring the template by setting method to oauth2 instead of js_sdk, but again nothing works. The button just seems to do nothing. On Facebook Developers, I have set … -
408 Request Timeout error occurs frequently when client uploads image with jquery-file-upload
I'm getting error via django logger like below. It does not occur always but frequently. Django==2.2.6 django-storage-swift==1.2.19 django-imagekit==4.0.2 python-swiftclient==3.7.0 models.py class Image(models.Model): ad = models.ForeignKey(Ad, on_delete=models.CASCADE, null=True, blank=True) index = models.IntegerField(null=True, blank=True) large = ProcessedImageField(upload_to=get_image_name, processors=[ResizeToFit(800, 533)], options={'quality': 50}, null=True, blank=True) forms.py class ImageForm(forms.ModelForm): class Meta: model = Image fields = ('large',) views.py def ajax_upload_image(request): form = ImageForm(request.POST, request.FILES) if form.is_valid(): image = form.save() data = {'is_valid': True, 'image_url': image.large.url, 'image_id': image.id} else: data = {'is_valid': False} return JsonResponse(data) template <input id="id_ad_image_upload" type="file" name="large" accept="image/jpeg,image/png" data-url="{% url 'ads:ajax_upload_image' %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}' > javascript $(function () { $('#id_ad_image_upload').fileupload({ dataType: 'json', start: function () {...}, change: function(e, data) {...}, done: function(e, data) {...}, fail: function (e, data) {...} }); }); nginx.conf sendfile on; tcp_nopush on; keepalive_timeout 20; client_header_timeout 10; client_body_timeout 10; send_timeout 10; client_max_body_size 75M; vps memory: 1GB/CPU 2Core SSD 50GB Could you please teach me which part occur this error and how to fix this? -
Handling date time range in django view
I'm trying to implement date time range in django. But I've no idea, how to implement properly. Here I'm using html forms. From the django view I'm requesting value like this. date_time_range = request.POST.get('date_time_range') expected outpul: [2020-01-31 09:03:11.161574, 2020-01-31 09:03:11.161574] actual outpul: 02/09/2020 12:00 AM - 02/09/2020 11:59 PM My actual scenario: Actually I want to start and stop task -
Django admin css not working after collectstatic
I started my website on "pythonanywhere" and ran bash command to 'collectstatic', but then the admin css looks broken. Is there a way to bring back the django default admin css? -
How to change Django database user based on login user
Is it possible to change Django database user based on login user. I'm using postgres db. -
Django associate existing user with social_user
I use Django, Django OAuth Toolkit (docs) and social-auth-app-django (docs). Authorization works fine. But now I'm interested in how I can create an association between a user registered with Django OAuth Toolkit and a user who has decided to login through a social network. For example, a user has registered with email 'foo@bar.com' and then decides to link the social network account (with the same email) to his or her account in order to use the social network account for quick login. My configs for social-auth pipelines: SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', <my own pipeline for creating user> # 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) -
Background Django tasks on Heroku without running a permanent background dyno
I'm new to Django and Heroku. I created a custom admin command which populates a Google Spreadsheet with data from my web app. The operation takes 4 minutes. It runs once a night via the Heroku schedular, which from what I understand, launches a dyno to execute the command and then shuts down the dyno. I'm now looking for a way to run this custom command on demand as well so it can be executed from my web application. I've found two solution: Celery and Redis Queue. Both looked good but from what I can see they both require a second dyno worker running 24/7. This is a hobby project so I don't want to be paying for a second dyno to be running all the time for an operation that I use once a week. Any ideas for solutions? -
Django : Binary File Download on Button click returning incorrect data
Implemented file download on button click for a binary file using Ajax and Django as below Django Code def generate(self,parms): #pdb.set_trace() json_data = json.loads(parms.body.decode('utf-8')) d_fldr = BASE_DIR+'/tmp/'+json_data['sessn']+'/' resp = None try: data = None with open(d_fldr + json_data['fn'],'rb') as f: data = f.read() resp = HttpResponse(data,'application/octet-stream') resp['Content-Disposition'] = 'attachment;filename=%s'%(json_data['fn']) except: resp = None return resp AJAX Call on Button Click console.log("Generate clicked"); json = { 'sessn' : global_sessn, 'fn' : $('#kdb_sel').val(), 'xml' : $('#kdb_xml').val() }; var req = { url: "ajx_generate", method: "post", processData: false, contentType: false, headers: { "X-CSRFToken": '{{ csrf_token }}' }, data: JSON.stringify(json), //responseType: 'arraybuffer', }; ajax_file_send(req,fun_succ1,fun_fail1); function fun_succ1(response) { // on success.. console.log("fun_succ1 success"); var binaryData = []; binaryData.push(response); var a = document.createElement('a'); var url = (window.URL || window.webkitURL).createObjectURL(new Blob(binaryData, {type: "application/kdb"})); a.href = url; a.download = $('#kdb_sel').val(); document.body.append(a); a.click(); a.remove(); window.URL.revokeObjectURL(url); } Issue The file that gets downloaded(2KB) on button click , is more in size than that is originally on server (1.4Kb) , while on Network TAB in DEV Tools Header : Content-Lengt is correctly set to 1.4Kb