Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I populate an HTML table created by Django using javascript?
I have this html code which takes a list of images (of any reasonable length) and displays them in a table with 4 columns <div> <table> <tr> <th>A</th> <th>B</th> <th>C</th> <th>D</th> </tr> {% for image in image_list %} {% cycle "<tr>" '' '' '' %} <td align="center"><img src="{{ image }}"></td> {% cycle '' '' '' "</tr>" %} {% endfor %} </table> </div> I am converting the page to work asynchronously using Ajax. I have the list of images in a javascript array, but I do not know how to send image_list to the html from javascript. I can update a single item on the page using a function function showImage(src, width, height, alt) { document.getElementById("top-image").src = src; }; But updating from a list defeats me. Can someone show me how to do it? -
Filtering Django query filtering
I'm doing some querying currently and I was wondering if I would be able to query something from these 3 models where the return would give me all the projects the users are working on. I know about the basic filtering however thats not really enough in this case, how would one go about querying through 2 foreign keys. class User(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField() class ProjectUser(models.Model): project = models.ForeignKey("Project", on_delete=models.CASCADE) user = models.ForeignKey("User", on_delete=models.CASCADE) is_lead = models.BooleanField(default=False) class Meta: unique_together = (("project", "user"),) class Project(models.Model): name = models.CharField(max_length=255) client = models.CharField(max_length=255) complete = models.BooleanField(default=False) -
age/Cor/CoreMain.cpp:1117 ]: Checking whether to disconnect long-running connections for process 2345176, application
My Django website is hosted on a shared host, running Apache apparently. The website seems working fine (I can access it), but I've found this error in several instances (50 times in a row) in the error log of the server. age/Cor/CoreMain.cpp:1117 ]: Checking whether to disconnect long-running connections for process 2345176, application I've read that there's a link with passenger on Apache (Passenger Core Shutdown With No Known Cause) but as said, I'm on shared hosting and don't have read access to it. Is it a problem on the webhost's side? My wsgi.py is stock: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mywebsite.settings') application = get_wsgi_application() -
Django saves same data twice for two different instances when created in same minute
Whenever I try to create a new object for my model, it uses the previous data that was recently stored for that new object. -
Android Retrofit response returning null object
I had built a simple rest API using Django on my localhost and was trying to access the GET, POST methods using android retrofit. I have successfully used the GET method & retrieved the JSON objects in a simple android TextView. But when I tried using POST from the remote android device, it did return with code 500(which is called internal server error). But my POST is working from the localhost server. I can't figure out why the POST is not working and so the response.body() is returning a null object to my Post class. Here is my createPost() which I tried to Post something on the localhost Django Server: private void createPost() { Post post = new Post("AAAAAAAA", "33"); Call<Post> call = jsonPlaceHolderApi.createPost(post); call.enqueue(new Callback<Post>() { @Override public void onResponse(Call<Post> call, Response<Post> response) { if(!response.isSuccessful()){ tv.setText("Code" + response.code()); } Post postResponse = response.body(); String content = ""; content += postResponse.getAlias() + "\n"; content += postResponse.getName() + "\n\n"; tv.append(content); } @Override public void onFailure(Call<Post> call, Throwable t) { tv.setText(t.getMessage()); } }); } And my Post class: public class Post { @SerializedName("name") private String name; @SerializedName("alias") private String alias; public Post(String name, String alias) { this.name = name; this.alias = alias; … -
how to make a videos view counter like instagram in django?
for example count the number of views if played for 3 or more seconds and unique for each user. should i make a timer in front end and request the update counter if played for more than 3 seconds. how does Instagram do it. my model attributes. class video(): name views_counter video_file -
Upload multiple archives in django model
i'm using a django inline model to receive multiple images in a principal model, but i don't know how to add this data to my inline model in the views.py. class FoundPet(models.Model): TIPO_CHOICES = ( ('C','Cachorro'), ('G','Gato') ) GENDER_CHOICES = ( ('M','Macho'), ('F','Fêmea') ) # Nome do Responsável nome = models.CharField(max_length = 40, blank = True) # Telefone do responsável phone = models.CharField(max_length = 40, blank = True) # Descrição description = models.TextField() # Tipo do animal tipo = models.CharField(max_length = 1, choices = TIPO_CHOICES, blank = False, null = False) # Sexo do animal gender = models.CharField(max_length = 1, choices = GENDER_CHOICES, blank = False, null = False) active = models.BooleanField(default = False) user = models.ForeignKey(User, on_delete = models.CASCADE, default=1) def __str__(self): return str(self.id) class Meta: db_table = 'found_pet' class ImagesFoundPet(models.Model): img = models.ImageField(upload_to = "media", null= True,blank = True) user = models.ForeignKey(FoundPet,on_delete = models.CASCADE) def __str__(self): return str(self.id) And i wrote a form html to receive the data from the user and send to my view. def set_found_pet(request): # Nome de quem está cadastrando nome = request.POST.get('nome') # Telefone do responsável phone = request.POST.get('phone') # Descrição description = request.POST.get('description') # Tipo do animal tipo = request.POST.get('tipo') # Sexo … -
Django forms date.today() doesn't return the right date in the morning
I have a form with : class DateInput(forms.DateInput): input_type = "date" Date = forms.DateField(widget=DateInput(),initial=datetime.date.today().strftime('%Y-%m-%d')) However I have the right date only after ~ 10AM, before I have the date of yeasterday. Any idea of what I miss ? Thanks -
how to get to the next element of list inside for loop in django template?
<div class="row align-items-stretch"> {% for img in data %} <div class="col-6 col-md-6 col-lg-3" data-aos="fade-up"> <a href="{{img}}" class="d-block photo-item" data-fancybox="gallery"> --img1 <img src="{{img}}" alt="Image" class="img-fluid"> -- img1 <div class="photo-text-more"> <span class="icon icon-camera"></span> </div> </a> </div> <div class="col-6 col-md-6 col-lg-6" data-aos="fade-up" data-aos-delay="100"> <a href="{{img}}" class="d-block photo-item" data-fancybox="gallery"> --img2 <img src="{{img}}" alt="Image" class="img-fluid"> --img2 <div class="photo-text-more"> <span class="icon icon-camera"></span> </div> </a> </div> <div class="col-6 col-md-6 col-lg-3" data-aos="fade-up" data-aos-delay="200"> <a href="{{img}}" class="d-block photo-item" data-fancybox="gallery"> --img3 <img src="{{img}}" alt="Image" class="img-fluid"> --img3 <div class="photo-text-more"> <span class="icon icon-camera"></span> </div> </a> </div> {% endfor %} </div> here what i'm trying to do is i want first element of img in first and and in second and i want the second element of img and so on. In python we can do this by indexing list or by next() of iterator but how can i make it possible in django template -
How can I serve an image in django?
I have a binary field to save images photograph = models.BinaryField(default=None) In my form, I save the image photograph = cd['photograph'].file.getvalue(), ) In My view f = open('my.jpeg', 'bw') myfile = File(f) myfile.write(student.photograph) filepath = os.path.abspath(os.path.realpath('my.jpeg')) context['urls'] = filepath return render(request, 'dashboard.html', context) The image is saved to the database, it is being retrieved successfully. Screenshot of the image being saved successfully My template The HTML in the template renders well. If I copy the HTML into a local file, the image appears well and good. However, the image doesn't load properly when I use django. Right click > copy image address gives me this: about:blank#blocked Is it a security or a permissions issue? -
How to solve object has no attribute 'action' error?
I want to pass some profile information via the django rest api to my front end. When doing so I encountering the following issue: 'ProfileAPI' object has no attribute 'action' class ProfileAPI(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = ProfileSerializer queryset = Profile.objects.all() def get_queryset(self): if self.action == 'list': return self.queryset.filter(user=self.request.user) return self.queryset Im currently a little bit lost to trace down the problem. -
NoReverseMatch in Django not working tried everything
Reverse for 'projectDetail' with no arguments not found. 1 pattern(s) tried: ['projects/(?P<projectinfo_id>[0-9]+)/$'] Request Method: GET Request URL: http://localhost:8000/projects/yourprojects Django Version: 3.0.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'projectDetail' with no arguments not found. 1 pattern(s) tried: ['projects/(?P<projectinfo_id>[0-9]+)/$'] urls.py file from django.urls import path, include from . import views urlpatterns = [ path('newproject', views.newproject, name='newproject'), path('yourprojects', views.yourprojects, name='yourprojects'), path('<int:projectinfo_id>/', views.projectDetail, name='projectDetail'), ] views.py file from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from .models import Projectinfo from django.utils import timezone from django.views.decorators.csrf import csrf_exempt,csrf_protect def home(request): return render(request, 'projects/home.html') def yourprojects(request): projectinfo = Projectinfo.objects return render(request, 'projects/yourprojects.html', {'projectinfo':projectinfo}) @login_required def newproject(request): if request.method == 'POST': if request.POST['title'] and request.POST['branch'] and request.POST['directorate'] and request.POST['email'] and request.POST['program_service'] and request.POST['giturl']: projectinfo = Projectinfo() projectinfo.title = request.POST['title'] projectinfo.branch = request.POST['branch'] projectinfo.directorate = request.POST['directorate'] projectinfo.email = request.POST['email'] projectinfo.program_service = request.POST['program_service'] if request.POST['giturl'].startswith('http://') or request.POST['giturl'].startswith('https://'): projectinfo.giturl = request.POST['giturl'] else: projectinfo.giturl = 'http://' + request.POST['giturl'] projectinfo.pub_date = timezone.datetime.now() projectinfo.project_lead = request.user projectinfo.save() return redirect('/projects/' + str(projectinfo.id)) else: return render(request, 'projects/newproject.html', {'error': 'All fields are required'}) else: return render(request, 'projects/newproject.html') def projectDetail(request, projectinfo_id): projectinfo = get_object_or_404(Projectinfo, pk=projectinfo_id) return render(request, 'projects/projectDetail.html', {'projectinfo': projectinfo}) yourprojects.html {% extends 'base.html' %} {% block content %} {% load static %} <main> … -
Why is Conditional Expressions adding new Items to a list view
I am trying to add a Post to a list view, the Home list view has already an Item context. In my project, a user can add a post and add an item each is a different app with different models. So In my Home list view, I have my items looped and in each item, it is showing the user related to it. What I am trying to do is check if this item.user has a post which is admin_approved=Truerelated to the user and if it does exist a button show appears in the page linking to another page with these posts. So if there are Zero posts related to the user or posts available but admin_approved=False or not yet admin_approved=True the button should not appear but if there is 1 or more posts that are admin_approved=Truethe button should appear. I have tried to annotate the queryset but the issue is that when a user has 2 posts one which is approved and another not approved, 2 items appears one with the button and one without the button and duplication takes place in the homepage List view I have tried to use .distinct() but it didn't work items are … -
Django : find encrypted password in the database with filter
when I register a new user, his password is encrypted in the database with the sha1 method. When I want to search if a user is or not already register in the database for my login page, I have to check if the email address exist and then if the password which is send is the good. This is my code : *views.py :" #Login @api_view(['POST', ]) def log_in(request): if request.method == 'POST': data = {} email = request.POST.get('email') password = request.POST.get('password') password = hashlib.sha1(password.encode('utf-8')) account = memberArea.objects.filter(email = email, password = password) if account.exists(): for account in account: data['succes'] = "Successfully connected" data['id'] = account.id data['email'] = account.email else : data['error'] = "email and password doesn't match !" return Response(data) Here, I try to encrypt the password which is send by the user and then to search into the databse for this encrypt password. After testing it doesn't work. Thank's by advance for helping me. -
Issue loading Django fixture. UnboundLocalError: local variable 'pk' referenced before assignment
I have the following models for which I will attempt to load data using a Django fixture file. class StaffPosition(models.Model): title = models.CharField(max_length=64) class Rating(models.Model): title = models.CharField(max_length=64) class StaffRatingCombinations(models.Model): staff_position = models.ManyToManyField(StaffPosition) position_rating = models.ManyToManyField(Rating) And the following fixture. When I add records for just staffposition and rating tables, the data loads fine. When I try to use foreign keys for staffratingcombinations, I get the error below. [{ "model": "myapp.staffposition", "pk": 1, "fields": { "title": "Lead" } }, { "model": "myapp.rating", "pk": 1, "fields": { "title": "Gold" } }, { "model": "myapp.staffratingcombinations", "pk": 1, "fields": { "staff_position": 1, "position_rating": 1 } }] When I run loaddata, I get: (myapp) pi@raspberrypi:~/Documents/Development/Myapp/django/myapp $ python3 manage.py loaddata initial_data.json Traceback (most recent call last): File "/home/pi/Documents/Development/Myapp/lib/python3.7/site-packages/django/core/serializers/base.py", line 287, in deserialize_m2m_values for pk in field_value: TypeError: 'int' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/pi/Documents/Development/Myapp/lib/python3.7/site-packages/django/core/serializers/json.py", line 69, in Deserializer yield from PythonDeserializer(objects, **options) File "/home/pi/Documents/Development/Myapp/lib/python3.7/site-packages/django/core/serializers/python.py", line 122, in Deserializer values = base.deserialize_m2m_values(field, field_value, using, handle_forward_references) File "/home/pi/Documents/Development/Myapp/lib/python3.7/site-packages/django/core/serializers/base.py", line 294, in deserialize_m2m_values raise M2MDeserializationError(e, pk) UnboundLocalError: local variable 'pk' referenced before assignment The above exception was the direct cause of the following exception: … -
How to register view without having to use reverse with app name in Django?
I have a custom directory for allauth templates. I need some custom views as well as I don't want some default views. I wanted to start with glueing in the entire allauth and change things that I need later on. My main app config/urls.py file from django.urls import include, path urlpatterns = [ path("account/", include("users.urls")), ] Users app: users/urls.py app_name = "users" urlpatterns = [ path("login/", allauth_views.login, name="account_login"), path("logout/", allauth_views.logout, name="account_logout"), path("signup/", allauth_views.signup, name="account_signup"), ] With this basic setup, if I go to /account/login it routes correctly to the desired view, but it is defined in users app, therefore, I have to access it in other views with reverse(users:account_login). The problem is that allauth LoginView has this method def get_context_data(self, **kwargs): ret = super(LoginView, self).get_context_data(**kwargs) signup_url = passthrough_next_redirect_url(self.request, reverse("account_signup"), self.redirect_field_name) redirect_field_value = get_request_param(self.request, self.redirect_field_name) site = get_current_site(self.request) ret.update({"signup_url": signup_url, "site": site, "redirect_field_name": self.redirect_field_name, "redirect_field_value": redirect_field_value}) return ret which does the lookup on reverse("account_signup") but Django gets lost and throws django.urls.exceptions.NoReverseMatch. If I set those allauth urlpatterns in my main urls file it works correctly but I want to keep this file small and define allauth urls in my users app. Is it possible to use reverse without an app name … -
MogoDb connection with Django
I am having issue with database connection with MongoDB. DATABASES = { 'default': { 'ENGINE': '‘djongo’', 'NAME': os.path.join(BASE_DIR, 'DJANGOPROJECT'), 'HOST' : 'mongodb+srv://rshah2:******@cluster0.nwaeb.mongodb.net/DJANGOPROJECT?retryWrites=true&w=majority', 'USER' : 'rshah2', 'PASSWORD' : '*****', } } But, when I try to run code, I get an error raise InvalidName("database names cannot contain the " pymongo.errors.InvalidName: database names cannot contain the character '\\' Any help? -
Auto logout user based on date in Django
I have an expiry date associated with every user, I just want to automatically log out the particular user, if the expiry date has been reached. I'm pretty confused while searching for solutions, some say to use django-session-timeout. Will it work for this type of system? -
Graphene-django with generic resolver to return List or Field
I am trying to simplify my graphene-django view to have a single graphene query that returns a graphene.List or a graphene.Field based on whether a parameter was sent. I am attempting the following code, but I am not sue how to handle the change between a List and Field response; """ graphene.Field & graphen.List will not be determined until the resolver 'resolve_employee' checks if a employeeId param is sent. Issue : How can I make this generic to return a list or a field """ employee = graphene.Field(EmployeeType, employeeId=graphene.Int()) def resolve_employee(self, info, **kwargs): employeeId = kwargs.get('employeeId') if employeeId is not None: return Employee.objects.get(pk=employeeId) else: return Employee.objects.all() This is my current schema.py with two seperate class EmployeeType(DjangoObjectType): class Meta: model = Employee class Query(object):) allEmployees = graphene.List(EmployeeType, active=graphene.Boolean()) employeeDetail = graphene.Field(EmployeeType, employeeId=graphene.Int()) def resolve_allEmployees(self, info, **kwargs): active_param = kwargs.get('active') if type(active_param) == bool: return Employee.objects.filter(term_date__isnull=active_param) return Employee.objects.all() def resolve_employeeDetail(self, info, **kwargs): employeeId = kwargs.get('employeeId') if employeeId is not None: return Employee.objects.get(pk=employeeId) -
Need to enable button WHEN Recaptcha and checkbox has been validated
I'm quite new to Django, jQuery so need some help here(basically a noob). I need enable Start Test button after the recaptcha has been validated from the server side,cannot be bypassed from front-end and check box has been checked. I did checkbox thing earlier but don't know how to add Captcha to that. HTML CODE <div class="g-recaptcha captcha-button" align="center" data-sitekey="sitekey"></div> <br> <div class="form-check test-check-button" align="center"> <input type="checkbox" class="form-check-input display-7" id="instructions" > <label class="form-check-label text-center" for="instructions" > <strong>I have read the instructions given above.</strong></label> </div> <div class="mb-5 mt-2 text-center start-button" id="startButton"> </div> $("#instructions").on("click", function () { $.ajax({ type: "GET", url: '/test/confirm', data: { 'checkbox': 1 }, dataType: 'json', success: function (data) { if (data.button) { $(".test-check-button").html(''); $(".start-button").html(data.button); } } }); }); Views.py def confirm(cls, request: HttpRequest): button = '<button class="btn btn-primary mt-3" id="submit_test" type="submit">Start Test</button>' data = {'button': button} return JsonResponse(data) There's no forms.py in the project. So wanted to know how I can validate the captcha server-side without forms and enable the Start test button after validation and checkbox is checked. Thank you. Without start button With Start button -
Javascript stopping Django views.py from doing anything
I have a Apply For Staff page but when I add the javascript it stops working. It still makes HTTP POST requests with all the data that was submitted but -
PostgreSQL Backups with Docker(cookiecutter)
Try to backup postgres data using cookiecutter on windows, follwed instructions here PS C:\Users\Super\Desktop\mysite\mysite> docker-compose -f local.yml exec postgres backups /usr/bin/env: ‘bash\r’: No such file or directory how to solve this? -
how to upload whole folder(with content) in django?
I want to upload whole folder(with content in it like PDF,text,image) from front-end and in the back-end that is in python(i'm using Django by the way),I have to create a folder same name as the folder that i uploaded in the media folder . and when pages load's respective folders for respective user will be show.means when user A logged in his uploaded folders will be shown in the dashboard...I am totally clueless how to do it.. thank you in advance -
crop image with opencv in django project
I want to crop user profile image with OpenCv-python in django and i tried this : if 'image' in request.FILES: img = cv2.imread(request.FILES['image']) User = request.user width=img.shape[1] height = img.shape[0] if height> width: p = (height - width) / 2 img = img[p:p+width,0:width] User.profile.image = img User.profile.save() else: p = (width - height) / 2 img = img[0:width,p:p+width] User.profile.image = img User.profile.save() return redirect('profile') hope you understand and solve my problem . -
Test on checking value with null constraint error
So I have a School model that has a required attribute student (from model Student). Somewhere in my serializer I do the following: @staticmethod def get_student_name(school): if school.student: return school.student.name return "no name" Now, a student can of course not be none or empty, ideally. But I do want to have the test if it's none to avoid errors (if there are mistakes in the database or..) So I want to write a test to go over these checks (to have a full 100% coverage). But when I try to create a School model in my test class, I, ofcourse, get a Null constraint error Is there a way to test this so I return "no name" for a student name if he doesn't have one instead of an error?