Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not able to create tables in postgresql
i am using django==2.2.1, postgres==10.8 and psycopg2==2.8.1 in ubunut 18.04 when i run makemigrations and migrate it's run successfully but the change not appear in postgres it gives me error django.db.utils.ProgrammingError: column ip_management_ipmanage.userTeam_id does not exist LINE 1: ...k_id", "ip_management_ipmanage"."userGateway_id", "ip_manage... -
PyCharm run django single test as part of class
When running single test in PyCharm (django), the IDE create new config with target boo.bar.tests.TestClass.test_whatwver This will not run the test, as the class is considered to be a method when running boo.bar.tests:TestClass.test_whatwver (with colon between tests:TestClass test will be executed is there a way telling PyCharm doing it by default? -
How to authenticate the user on his requests after login in django using TokenAuthentication from drf
I have implemented an endpoint for login, using the django-rest-framework and TokenAuthentication. What i want, is after the login, the user to be authenticated and can navigate on the website. I know that any get request on any protected using authentication uri should contain the token in the headers, so that the user can be authenticated. Everything is fine with that, if i could do all the get requests adding the token manually. But what i do not understand is, how can i add the token in the headers when for example the user manually does the request by writing the url? Let's say that the uri /api/ is protected and requires an authenticated user. The user logs in, and i save the token either on the cookies or in the localstorage. Now the user does a http get request on /api/. The token is not placed in the headers, so the response is: "Not authenticated". So the question is, how can i add the token on any subsequent request after user logs in successfully? Maybe the backend could check the cookies for a valid token, but isn't there any better and safer solution than this? -
Architect the site builder like wix
I've been assigned to build a site builder like wix or squarespace. However even after searching all the forums like anything I'm back to square. Can you please help me with the basic architecture ? I'm currently using Django, Postgres and reactjs for front end. -
How to render dictionary new entry as new row of table in django?
I am having a difficulty implementing something that seemed quite straightforward in the beginning. More specifically, I want to upload a file in a folder and rename it. After renaming it I want to display a row in a table, which contains 3 columns. First column should display the old name of the file, second column should display the new name of the file and then third column should display a download button. I want the table to display this for every file that I upload (for instance if I have uploaded 5 files I wanna see 5 rows in the table) This is my upload_file view: def upload_file(request): filedict = {} oldname = "" newname = "" if request.method == 'POST': uploaded_file = request.FILES['document'] fs=FileSystemStorage() oldname = fs.save(uploaded_file.name,uploaded_file) newname = "new"+oldname global counter filedict['counter'] = { 'oldname': oldname, 'newname' : newname } counter+=1 return render(request, 'files/renamefiles.html',{'names': filedict}) and this is the table in my template renamefiles.html: <div class="mt-5"> <table class="table table-hover"> <thead> <tr> <th scope="col">Source File</th> <th scope="col">Renamed File</th> <th scope="col">Action</th> </tr> </thead> <tbody> <tr> {% for key, entry in dictionary.items %} {% for key2, data in entry.items %} <th id="filedata">{{data}}</th> {% endfor%} {% endfor%} <th><a class="btn btn-sm btncolor">Download … -
Deserialisation Issue For Nullable Foreign key Field Django Rest Framework
While Deserialization of the nullable foreign key field. Getting the error : 'NoneType' object has no attribute 'foreign_field' This issue was not coming till Django-Rest-Framework Version: 3.6.4 Found the cause of the issue(Removed None check) : Link Why this check is removed ? Is there any workaround that can handle the Nullable foreign key field? Tried Following things : Tried setting the default value: Didn't Work Writing the Serializer Method isn't feasible(Lots of changes in existing Code). -
Template Does not Exist on IIS+Django
After the deployment process of my Django website on IIS i am getting an error like below, TemplateDoesNotExist at /test/new_site/list/ This is working fine in my local system. I tried to add the template folder in to the virtual directory also, but no use, still the same error is showing. I followed this tutorial in order to set up my application on IIS I am using python 3.7 and IIS 8.5 I spend my two days for solving this issue but i did not find any solution related to this. Any help would be greatly appreciated. Thanks in Advance. -
how to restrict django to overlap base.html css for navbar to all other templates css
i have added bootstrap css to navbar and what i did is i extended the application base.html to other html files in my case it is login.html to get that nav bar the ui is as expected and good in my homepage but where as in login.html the css overlapped with the bootstrap css and UI has changed here is the image https://ibb.co/PY9KV6x home page https://ibb.co/nRQrjty login oage I have tried removing the base.html extension tag then its perfectly fine but i cant extend the navbar base.html <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <title>{% block title %} Project!{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'posts/style.css' %}"> </head> <body> {% include 'posts/navbar.html' %} <div class = "container-fluid"> {% block content %} {% endblock %} </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html> login.html {% extends 'posts/base.html' %} {% block content %} {% load staticfiles%} <<div class="something"> <link rel="stylesheet" href="{% static 'accounts/css/accounts.css' %}"> i just want django to restrict css to that navbar section and isolate that login template i haven't added any css code because the issue is with django , but if you need … -
Django/Dropbox uploaded file is 0 bytes
I CAN'T figure out why my uploaded file to Dropbox via Django is always zero bytes. Outsize Django (using raw Python), the files get uploaded normally. My HTML has enctype="multipart/form-data" declared. VIEWS.PY: if cv_form.is_valid(): cv_form.save(commit=True) # print(request.FILES['cv'].size) == 125898 DOC = request.FILES['cv'] PATH = f'/CV/{DOC}' upload_handler(DOC, PATH) #http_response_happens_here() HANDLER: def upload_handler(DOC, PATH): dbx = dropbox.Dropbox(settings.DROPBOX_APP_ACCESS_TOKEN) dbx.files_upload(DOC.file.read(), PATH) #file gets uploaded but always 0bytes in size -
creating a editing function in django that edit a very simple form
i am unable to designa edit function though i have made putting data into form and rendering it through an html file i have made function to delete also but i have no clue of how to edit. this is model from django.db import models class Person(models.Model): name=models.CharField(max_length=50) email=models.EmailField(max_length=30) this is form from .models import Person from django import forms class Formm(forms.ModelForm): class Meta: model=Person fields=('name','email') -
Send some value to the form, by GET or POST request
I need to send some value to the form using GET or POST. My form: class InstallmentReportForm(forms.ModelForm): class Meta: model = InstallmentReport exclude = () def __init__(self, *args, **kwargs): super(InstallmentReportForm, self).__init__(*args, **kwargs) self.fields['title'].queryset = Report.objects.filter(grant_name=??????) InstallmentReportFormSet = inlineformset_factory(Installment,InstallmentReport, form=InstallmentReportForm, fields=['title','spent'], extra=1,can_delete=True) It is my view model: class InstallmentReportCreate(LoginRequiredMixin,PermissionRequiredMixin,CreateView): model = Installment template_name = 'catalog/installment_report_update.html' permission_required = 'catalog.can_change_grant' form_class = InstallmentForm success_url = None def get_context_data(self, **kwargs): data = super(InstallmentReportCreate, self).get_context_data(**kwargs) if self.request.POST: data['titles'] = InstallmentReportFormSet(self.request.POST) else: data['titles'] = InstallmentReportFormSet() return data def form_valid(self, form): context = self.get_context_data() print(titles) with transaction.atomic(): form.instance.owner = self.request.user self.object = form.save() if titles.is_valid(): titles.instance = self.object titles.save() return super(InstallmentReportCreate, self).form_valid(form) def get_success_url(self): return reverse('grant-installment-owner', args=(self.object.id,)) I need get 'grant_name' for filtering data. I'm using Python3.7.3 and Django 2.2.1 -
Kendo UI grid with Django
I am trying to show my model list with using Kendo UI. But it gives me error in browser console. I took the list as json. Please help me to solve this problem. template $("#grid").kendoGrid({ dataSource: { type: "odata", transport: { read: { //"https://demos.telerik.com/kendo-ui/service/Northwind.svc/Customers" url: "{% url 'test_json' %}", dataType: "json", } }, schema: { total: "count", data: "results", }, pageSize: 5 }, height: 550, groupable: true, sortable: true, pageable: { refresh: true, pageSizes: true, buttonCount: 5 }, columns: [{ field: "id", width: 240 }, { field: "book", }, { field: "no_of_page", }] }); views.py def test_json(request): books = Book.objects.all().values('id','name','no_of_page') booklist = list(books) return JsonResponse(booklist, safe=False) urls.py url(r'^test/book/$', test_json, name='test_json'), -
makemigrations does not create the trough model
I have made changes to one of my models in my project and migrate, makemigrations does not work as expected. Rebuilding the database creates only 2 out of 3 tables from my models.py and i cannot figure out the problem. There are two different apps; "blog" and "users". both are registered in the setting.py. I completely removed the database and deleted the migrations folders. then i tried the following stuff: django makemigrations blog django migrate blog doing a global django makemigrations does not have any effect, no changes are detected. here is the relevant models.py of "blog": class Room(models.Model): roomname = models.CharField(max_length=6, unique=True) roomeditors=models.ManyToManyField(User,related_name='rooms_user_can_edit', blank=True) displayadmin=models.ForeignKey(User, related_name='room_user_is_displayadmin',null=True, on_delete=models.SET_NULL) def __str__(self): return self.roomname class Post(models.Model): title = models.CharField(max_length=40) content = models.TextField(max_length=300) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) rooms = models.ManyToManyField(Room, related_name='roomposts', through='Display') def __str__(self): return self.title def get_absolute_url(self): return "/post/{}/".format(self.pk) class Display(models.Model): class Meta: auto_created = True post = models.ForeignKey(Post, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) isdisplayed = models.BooleanField(default=0) def __str__(self): return str(self.isdisplayed) every table gets created except from display. the output is: Migrations for 'blog': blog\migrations\0001_initial.py - Create model Room - Create model Post -
How to send multiple objects through HttpResponse or JsonResponse in django
I have two objects influencer_data and user_list in my views function.I want to send both influencer_data and user_list through the HttpResponse method. My views function is: def index(request): influencers = Influencer.objects.all() influencer_data = serializers.serialize("json",influencers) user_list = UserList.objects.all() user_list = serializers.serialize("json",user_list) context = { 'influencer_data':influencer_data, 'user_list':user_list, } return HttpResponse(influencer_data,user_list, content_type='application/json') When I pass both influencer_data and user_list I get the error __init__() got multiple values for argument 'content_type' When I change the return HttpResponse statement to return HttpResponse(context, content_type='application/json') I get influencer_datauser_list i.e just the key values from the dictionary When I change the return statement to return HttpResponse(json.dumps(context), content_type='application/json') I get the output as: "influencer_data": "[{\"model\": \"influencer_listings.influencer\", \"pk\": 8794, \"fields\": {\"full_name\": \"F A I Z S H A I K H \\ud83c\\udf08\", \"username\": \"mr_faizzz_07\", \"photo\": \"\", \"email_id\": \"\", \"external_url\": \"\", \"location_city\": \"Mumbai\", \"categories\": \"\", \"hashtags\": \"['#foryou', '#blessyou', '#all', '#faizanshaikh', '#keepsmiling', '#blessed', '#look', (The Json object becomes a string) How should I deal with this? -
Overriding the save method of multiple Django classes without making the change in each individual class
I have a django project set up in which I have 6 (and will possibly add more in the future) tables. I need the admin interface setup such that whenever I update or add an object to any of the models, it writes data to a file from the LogEntry class. I have chosen this method because post save signals will run on server start-up (I have dockerized this app and am importing tables into the postgres database from pre-existing csv files) and they throw errors. In order to achieve the functionality desired, I put the following in my models.py file. class ModdedModel(models.Model): def save(self, *args, **kwargs): changes_file = ("new_changes.txt","w") content2 = LogEntry.objects.all() changes_file.write(content2) super(ModdedModel, self).save(*args,**kwargs) I then inherited this model for all subsequent tables that I want to create using the Django ORM. However this error appears, SystemCheckError: System check identified some issues: ERRORS: mdp.Variants.variants: (models.E006) The field 'variants' clashes with the field 'variants' from model 'mdp.moddedmodel'. I assumed maybe there was some namespace error and changed the field name to variantss to check if it would make a difference but I then got this instead Did you rename variants.variants to variants.variantss (a CharField)? [y/N] y You are trying … -
Typescript inlined in Django html
Im trying to combine Typescript and Django. What I've manage to do was to use Django Compressor wich gives me possibility to import compiled typescript file. But what if I needed to inline typescript code in html? E.g: <script> require('path/to/my/file.ts') </script> I found that repo https://github.com/MasterKale/django-brunch-ts-scss and it shows that it is possible but I can't figure it out how can I accomplished that without using Brunch.io -
How to configure django to generate signed urls for media files with Google Cloud CDN?
I am working on a project that requires load media files from Google Cloud CDN. Currently, I am loading the files in the form of urls - cdn.mydomain.com/image.jpg . But this requires to provide public access to the object. I need to generate signed url for secure access of these resources. I have checked django-storages. It provides signed url straight from the storage bucket but does not say anything about signed urls for CDN. How do I generate signed urls for Google Cloud CDN inside django and keep using the django-storages library? -
Unable to submit data to database?
I'm trying to create a blog app with django.When i visit localhost the home page works and when i click on register tab the register page comes and when i click on submit its not submitting the data to database.It returns page not found error. request method:POST .Request URL: http://127.0.0.1:8000/blog/register/register.I think the problem is with url. <!--html code--> {% extends 'layout.html' %} {% block content %} <div class="box"> <h2> <center>Register</center> </h2><br> <form action='register' method='POST'> {% csrf_token %} <label><b>Email:</b></label><br> <input type="email" class="inputvalues" name="email"/><br> <label><b>Username:</b></label><br> <input type="text" maxlength="100" class="inputvalues" name="User_name"/><br> <label><b>Password:</b></label><br> <input type="password" class="inputvalues" name="Paasword1"/><br> <label><b>Confirm Password:</b></label><br> <input type="password" class="inputvalues" name="Paasword2"/><br> <input type="Submit" id="lg"/><br> <center><a href="#" >Already have an account.Login here.</a> </center> </form> </div> {% endblock %} #my main app urls.py code from django.contrib import admin from django.urls import path,include urlpatterns = [ path('blog/',include('blog.urls')), path('admin/', admin.site.urls), ] #blog app urls.py from django.urls import path,include from . import views urlpatterns=[ path('',views.homepage), path('register/',views.register,name='register'), path('login/',views.login), ] #views.py register page code def register(request): if request.method == "POST": email=request.POST['email'] User_name=request.POST['User_name'] Password1=request.POST['Password1'] Password2=request.POST['Password2'] if Password1 == Password2: if User.objects.filter(username=username).exists(): print('13') elif User.objects.filter(email=email).exists(): print("email taken") else: user = User.objects.create_user(username=User_name, password=Password1,email=email) user.save(); else: return render(request,'register.html') When i click on register tab once it returns register.html file at that time the … -
Restructure existing project to have a separate application with shared modules
This is my first job and I am given a task that I am not sure how to approach. Basically, the project is running well on say url www.asmara.com. Now, what is needed is to add a specific user group called HAY which have its own permissions. Then the users will use www.hay.com (or if to hard hay.asmara.com) to access the advanced functionality of the app. I am on python 3.6 and django 1.11 I started create a separate project but relized the existing project have stuff I want to use (solo functions and some classes) and certainly the database models. Current project looks like this: project1: members messaging shared each app has its own models, serializers and views. I want to make use of the models and possibly certain models. I am told to keep my directory separate (hence can't be inside project1, which would have make importing easy). The ideal structure I am advised to come up with is: projec1 --- project2 --- What is the easiest way to access certain functionality and models of project1 from project2, keeping in mind during deployment, they might separate from each other at all -- hence hard coding imports is not … -
SSLError installing with pip
I'm trying to install Django on a windows 10 . Whatever I try to install with pip on cmd, I get those errors Collecting django Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1056)'))': /simple/django/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1056)'))': /simple/django/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1056)'))': /simple/django/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1056)'))': /simple/django/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1056)'))': /simple/django/ Could not fetch URL https://pypi.org/simple/django/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/django/ (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1056)'))) - skipping Could not find a version that satisfies the requirement django (from versions: ) No matching distribution found for django Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1056)'))) - skipping I've tried … -
DJANGO html returning "none" after running python script
I have a DJANGO app (kwtest) that has VIEWS(a+b) and associated URL(s). When I access the first kw_dash (kw_dash.html) URL and press a button it calls a python script (from import) and should return this to the "return_results" (script_return.html) URL. The functionality is working fine but the output is "none" in the browser for "return_results". The script is also continuous and I can only stop by killing the SSH session (at the moment). I have searched for a while for the results and am after guidance (I am new to this). Any help much appreciated. The script is working fine in console. kw_dash.html; {% load staticfiles %} <html> <body> <div class=”button”> <a href={% url 'kwtest:remote_results' %}>Run_Results</a> </div> </body> </html> script_return.html; <html> <head> <title>Remote Results</title> </head> <body> <div> <pre>{{ output }}</pre> </div> </body> </html> viewa; from django.shortcuts import render def kw_dash(request): return render(request, 'kwtest/kw_dash.html', {}) viewb; #- * -coding: utf - 8 - * - from django.shortcuts import render from django.http import HttpResponse from django.http import HttpResponseRedirect import remote_results def remote_results(request): import remote_results output = remote_results.remote_results() return render(request, 'kwtest/script_results.html', { 'output': output }) remote_results.py; import paramiko def remote_results(): hostname ='192.168.xx.xx' port = 22 username='xxxxxx' pkey_file = '/home/test/.ssh/id_rsa' key = paramiko.RSAKey.from_private_key_file(pkey_file) s … -
How to write query, based on the id obtained from UpdateView in django ClassBasedView?
Can't able to view foreign key as value, instead it show id, i want to show the value instead of id when i click edit. I have already used: def str(self): return self.name, in my models. i tried to write def get_object() but its not worked models.py class VehicleName(BaseModel): name=models.CharField(max_length=128) image = models.FileField(upload_to='cars/', blank=True, null=True) brand = models.ForeignKey("autofinance.VehicleBrand",on_delete=models.CASCADE) model_year = models.IntegerField(blank=True,null=True) is_deleted = models.BooleanField(default=False) def __str__(self): return self.name view.py class EditVehicle(UpdateView): model = VehicleName form_class = vehicleForm template_name = 'tayseeradmin/edit_vechile.html' success_url = reverse_lazy('tayseer-admin:view-vehicle') context_object_name = 'picture' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) vehicle = VehicleBrand.objects.get(id=self.object.pk) context['heading'] = 'Edit Vehicle' context['dashboard'] = 'vehicle' return context urls.py path('vehicle/<uuid:pk>/', login_required(views.EditVehicle.as_view(), login_url='tayseer-admin:index'), name='edit-vehicle'), I expect the results viewed as values , not as id at the time of edit. -
Django Form some field always get None in clean_field() or clean()
It's always get None in clean() or clean_field(), but it's in self.data. django 2.x def clean_code(self): code = self.cleaned_data.get('code') phone = self.cleaned_data.get('phone') result, message = sms_validator.validate(phone, code) def clean(self): code = self.cleaned_data.get('code') phone = self.cleaned_data.get('phone') result, message = sms_validator.validate(phone, code) Both of above all run in error: phone = None But if phone = self.data.get('phone') It's can get the value. I want to get the phone value in clean_data -
How to set username as ForeignKey in Django
How to set username as ForeignKey in Django module. is bellow method is correct? user = models.ForeignKey(User, db_column="user") i cannot use ID as ForeignKey because my old db have username as ForeignKey.(I need to migrate the the old Data) -
How to load image under header tag in django?
all other images that are under "img" tag are loading successfully, but i have one image under "header" tag, like this: <header class="pt100 pb100 parallax-window-2" data-parallax="scroll" data-speed="0.5" data-image-src="{% static 'assets/img/serv.jpg' %}" data-positionY="1000"> but this image is not loading, can anybody suggest, how to overcome this issue? when i run the raw template in browser, the image loads without any issue, but unable to making it work with django!