Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why Django raising ValueError?
This is my view.py file under my project folder. When I add a value in ToDo list it raises this error? "The view my_day.views.index didn't return an HttpResponse object. It returned None instead." from django.shortcuts import render, redirect from .models import List from .form import ListForm from django.contrib import messages # Create your views here. def index(request): if request.method == "POST": form = ListForm(request.POST or None) if form.is_valid(): form.save() all_items = List.objects.all messages.success(request, ('Task Added')) return render(request, 'index.html', {'all_items': all_items}) else: all_items = List.objects.all return render(request, 'index.html', {'all_items': all_items}) -
How to secure cross domain POST method?
My goal is to make the POST request from second.com to first.com. And I need to secure the Django server (first.com) to allow and authorise POST request and respond to second.com (Javascript client) My current plan is to get the csrf token from first.com by making the GET method. def api_token(request): csrfmiddlewaretoken = get_token(request) return JsonResponse({'status': True, 'csrfmiddlewaretoken': csrfmiddlewaretoken}) And then make the post method to first.com to get the response. def api_res(request): return JsonResponse({'status': True}) This is my js code look like fetch("http://first.com/api/res/", { method: 'post', headers: { "X-CSRFToken": response.csrfmiddlewaretoken, "Accept": "application/json", "Content-Type": "application/json", "credentials": "include" }, body: JSON.stringify({"hello": "what"}) }) .then(res => res.json()) .then(response => console.log(response)) There is no error but the api/res endpoint result is not working. Meaning I get Request Method: OPTIONS in the chrome dev tool. Please some one explain what is going on? This is my Djago cors settings. CORS_ORIGIN_WHITELIST = ( 'second.com' ) CSRF_TRUSTED_ORIGINS = [ "second.com", ] CORS_ALLOW_METHODS = ( 'GET', 'POST', ) CORS_ALLOW_CREDENTIALS = True -
Django Development server displaying wrong project data
I am able to access the django development server 127.0.0.1:8000 even without running "python manage.py runserver". It is displaying the previously created project website. Even when I run manage.py runserver from a different project it still show the data from previous project. Why is this happening? How to recover? -
Django REST: GET request 404 error on url path when filtering specific data entries
Currently I cannot get specific elements by id on the path http://127.0.0.1:8000/campus/room/details urls.py from django.urls import path, re_path from django.contrib import admin import Registration.views as regApp # Ignore this error, it compiles import Campus.views as campusApp import Room.views as roomApp import Booking.views as bookingApp urlpatterns = [ path(r'admin/', admin.site.urls), #Admin Panel path(r'booking', bookingApp.AllBooking.as_view()), # Room Details list per Room per campus path(r'registration', regApp.AllUser.as_view()), #UserRegistration path(r'campus/', campusApp.AllCampus.as_view()), #Campus list path(r'campus/room/', roomApp.AllRoom.as_view()), #Rooms list per Campus path(r'campus/room/details', roomApp.AllRoomDetails.as_view()), #Room Details list per Room per campus re_path(r'^booking/(?P<pk>\d+)', bookingApp.BookingView.as_view()), re_path(r'^registration/(?P<pk>\d+)', regApp.UserView.as_view()), #Figure out what this line does re_path(r'^campus/(?P<pk>\d+)', campusApp.CampusView.as_view()), re_path(r'^campus/room/(?P<pk>\d+)', roomApp.RoomView.as_view()), # re_path(r'^campus/room/details/(?P<dk>\w)/$', roomApp.RoomDetailsView.as_view()), re_path(r'^campus/room/details/(?P<pk>\w+)', roomApp.RoomDetailsView.as_view()), ] models.py from django.db import models # from ..Campus import Campus # Create your models here. class Room(models.Model): campus = models.ForeignKey('Campus.Campus', on_delete=models.CASCADE) floorNumber = models.CharField(max_length=2) roomNumber = models.CharField(max_length=5) roomID = models.CharField(max_length=10, unique=True) def __str__(self): return self.roomID class RoomDetails(models.Model): roomDetailsID = models.ForeignKey(Room, max_length=10, on_delete=models.CASCADE, to_field='roomID') capacity = models.CharField(max_length=3) whiteboard = models.BooleanField(default=False) projector = models.BooleanField(default=False) class Meta: verbose_name_plural = "Room Details" def __str__(self): return self.roomDetailsID_id views.py from django.shortcuts import render from rest_framework import status from rest_framework.generics import ListAPIView from rest_framework.response import Response from rest_framework.views import APIView from .models import Room, RoomDetails from .serializer import RoomSerializer, RoomDetailsSerializer # Create your views … -
(django) Get external pdf from url and serve in a view response
How can i do this? I have a view in djang that need to download a pdf from external service and return it as response in a django view (like a proxy?) response = urlopen(urlPdf) return FileResponse(response, as_attachment=True, filename='hello.pdf') -
Attaching logged in user to a class based form and model
views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import UploadDocument from .models import Document def upload_document(request): if request.method == 'POST': form = UploadDocument(request.POST, request.FILES) if form.is_valid(): # file is saved instance = Document(passport=request.FILES['passport']) instance.save() instance = Document(id_license=request.FILES['id_license']) instance.save() instance = Document(User=request.user) instance.save() # needs to add instance of User from cache return HttpResponseRedirect('/success/url/') else: form = UploadDocument() return render(request, 'verification/verificate.html', {'form': form}) forms.py from django import forms class UploadDocument(forms.Form): passport = forms.ImageField() id_license = forms.ImageField() models.py from django.conf import settings from django.db import models class Document(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) passport = models.ImageField() id_license = models.ImageField() Exception Value: NOT NULL constraint failed: verification_document.user_id I want to create a form that allows uploading documents, for verification purpose. How to attach a loged in User? -
Add Github Markdown Syntax Highlighting In The Browser
In python, I am taking markdown text and putting it through github markdown API so that I can render the result to a page. Below self.body would be rendered on the page. headers = {'Content-Type': 'text/plain'} r = requests.post('https://api.github.com/markdown/raw',headers=headers, data=self.body_markdown, verify=False) self.body = r.text When code snippets get rendered on the page they are just regular text with no syntax highlighting. I would like to use github's syntax highlighting to bring some life to the code snippets. For example, a code snippet run through the markdown API would result in HTML like this, which clearly has some structure to it with class names. <div class="highlight highlight-source-python"><pre><span class="pl-k">import</span> django x <span class="pl-k">=</span> <span class="pl-c1">2</span> <span class="pl-c1">print</span>(x)</pre></div> Is there a library or some other source that would allow interaction with this DOM structure to render some syntax highlighting/formatting? -
Django trying to save value to database but value turns into NULL when i'm trying to save
I'm trying to run a command using subprocess which runs fine and then it should spit out the value using a print function, which also works perfectly. cmd = subprocess.check_output(["golemcli", "tasks", 'create',unique_filename]).decode(sys.stdout.encoding) test = print(cmd) This will print something like "cc490086-d851-11e8-9ca6-a6389e8e7978" Now I want to save that into my database. I've created a Model which looks like class Usertasks(models.Model): TaskID = models.CharField(max_length=40) user = models.CharField(max_length=30) and this is how my views save the data. r = Usertasks(user=request.user, TaskID=test,) r.save() But when I try to save the data from the print it turns into a NULL value? My Django complains about following Exception Value: NOT NULL constraint failed: myproject_usertasks.TaskID How can I fix this? -
how to generate random integers with length 8 and unique
How does one generate integer of 8 length unique integers for CharField() I want to use this to generate barcode id Eg maybe a function? I have seen the uuid.uuid4 but it's too much for what I needed. or maybe there is a way to cut it down to 8 digits only? -
Django with custom 404 will crash on the home page where in urls prefix_default_language=True
Django with custom 404 will crash on the home page where in urls.py prefix_default_language=True my urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls import url from django.conf.urls.i18n import i18n_patterns from django.conf.urls.static import static from django.conf import settings from django.contrib.auth import views as auth_views from manager import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf.urls.static import static from django.conf.urls import handler404, handler500 urlpatterns = i18n_patterns( url(r'^$', views.home, name='home'), path('admin/', admin.site.urls), url(r'^logout/$', views.disconnect_user, name='logout'), path('ckeditor/', include('ckeditor_uploader.urls')), url(r'^login/$', auth_views.login, name='login'), url(r'^oauth/', include('social_django.urls', namespace='social'), name='fb-login'), # <-- url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^', include('manager.urls')), prefix_default_language=True, ) handler404 = 'manager.views.handler404' my 404 def def handler404(request, exception, template_name='error_pages/404.html'): response = render(request, template_name) return response So I found out that if I define a 404 page on the homepage without language prefix i will land on 404 page with no error in the logs NOTE it happens only on production on development doesn't occur -
Django Process Form data in views.py on submit
I Want to process my form data and view and update my mongo db if name not present else if name present update the DB. Before that i want to make sure if the entere subject is proper.. using some regex. But when i add name and subject in below form codee nothing is happening. How do i get the form data in view and do the proper check. And where should i do the input validation in views or form.html ?? if entered data is not proper format throw error ? how can i do this ? form_template.html <div class="container"> <div class="col-md-5"> <div class="form-area"> <form id="add-form" method="POST" action="{% url 'myapp:add_data' %}" role="form"> <br style="clear:both"> <h4 style="margin-bottom: 25px; text-align: center;"> New Data</h3> <div class="form-group"> <input type="text" class="form-control" id="name" name="name" placeholder="Name" required> </div> <div class="form-group"> <input type="text" class="form-control" id="sub_list" name="sub_list" placeholder="Sub List comma separated" required> </div> <button type="button" id="submit" name="submit" class="btn btn-primary pull-right">Submit Form</button> </form> </div> </div> </div> </div> myapp/url.py url(r'^new_data$', views.add_data, name='add_data'), And below is my view function def add_data(request): print "Herfe" if request.POST: print "coming here" I want validate user entered input is proper messages.success(request, 'Form submission successful') return render(request, '/index.html') -
Django model - save value as CharField and retrieve from foreignerKey
I'm using django and I have a specific problem. I have a model with a value (CharField) and I want to transform this CharField to ForeignerKey. I can't save the foreignerKey in my database because it's a volatile data and it's possible to delete and create an other foreignerKey and the relation will be brocken. So I can't use a foreignerKey between but I have an value which doesn't change and I store this value and I want to transform this value to the model. I want to use my model like that : MyModel.objects.get('hereMyModel2Retrieve'__value1='toto') for exemple. But 'hereMyModel2Retrieve is a CharField actually... Do you understand ? I don't know if it's possible. I looked to use a custom model.Field but I don't know if it's the solution. thanks -
django, reverse lookup in teams and employees having manytomany relationship
models.py class Employee(models.Model): employee_id = models.CharField(max_length=30,unique=True) class EmployeeConfig(models.Model): employee = models.ForeignKey(Employee,on_delete=models.CASCADE) region = models.CharField(max_length=30) live = models.BooleanField() #only one config is live class Team(models.Model): team_name = models.CharField(max_length=10, unique=True) employees = models.ManyToManyField(Employee) Every employee can be part of multiple teams. I want to create context with queryset as employee_id, team_names, region (live config). Questions: Is the above structure correct for my usecase ? How to write view to display "employee_id, region, team_names", for all employees, their corresponding live config and list of teams they are part of? -
Optimizing django db queries
I am trying to optimize my db queries(mysql) in a django app. This is the situation: I need to retrieve some data about sales, stock about some products on a monthly basis. This is the function def get_magazzino_month(year, month): from magazzino.models import ddt_in_item, omaggi_item, inventario_item from corrispettivi.models import corrispettivi_item, corrispettivi from fatture.models import fatture_item, fatture, fatture_laboratori_item from prodotti.models import prodotti qt = 0 val = 0 products = prodotti.objects.all() invents = inventario_item.objects.all().filter(id_inventario__data__year=year-1) fatture_lab = fatture_laboratori_item.objects.all().order_by("-id_fattura__data") for product in products: inv_instance = filter_for_product(invents, product) if inv_instance: qt += inv_instance[0].quantita lab_instance = fatture_lab.filter(id_prodotti=product).first() prezzo_prodotto = (lab_instance.costo_acquisto/lab_instance.quantita - ((lab_instance.costo_acquisto/lab_instance.quantita) * lab_instance.sconto / 100)) if lab_instance else product.costo_acquisto return val, qt The problem is where I need to filter all the data to get only the product I need. It seems that the .filter option makes django requery the database, although all of the data is there. I tried making a function to filter it myself, but although the queries diminish, loading time increases dramatically. This is the function to filter: def filter_for_product(array, product): result = [] for instance in array: if instance.id_prodotti.id == product.id: result.append(instance) return result Has anyone ever dealt with this kind of problem? -
Django: unsupported operand type(s) for +: 'decimal.Decimal' and 'dict'
I am in my views.py and want to perform a mathamatical calculation for my accounting project... So I have done something like this: @login_required def ledger1_detail_view(request,pk2, pk3): ledger1_details = get_object_or_404(ledger1, pk=pk2) selectdatefield_details = get_object_or_404(selectdatefield, pk=pk3) qs = journal.objects.filter(User=request.user, Company=company_details.pk, By=ledger1_details.pk, Date__gte=selectdatefield_details.Start_Date, Date__lte=selectdatefield_details.End_Date) qs2 = journal.objects.filter(User=request.user, Company=company_details.pk, To=ledger1_details.pk, Date__gte=selectdatefield_details.Start_Date, Date__lte=selectdatefield_details.End_Date) total_debit = qs.aggregate(Sum('Debit')) total_credit = qs2.aggregate(Sum('Credit')) closing_balance = ledger1_details.Opening_Balance + total_debit - total_credit context = { 'ledger1_details' : ledger1_details, 'selectdatefield_details' : selectdatefield_details, 'total_debit' : total_debit, 'total_credit' : total_credit, 'journal_debit' : qs, 'journal_credit' : qs2, 'closing_balance' : closing_balance, } return render(request, 'accounting_double_entry/ledger1_details.html', context) The problem is in this line of code: closing_balance = ledger1_details.Opening_Balance + total_debit - total_credit I am getting this error: TypeError: unsupported operand type(s) for +: 'decimal.Decimal' and 'dict' This are my models: class ledger1(models.Model): Creation_Date = models.DateField(blank=True, null=True) name = models.CharField(max_length=32) group1_Name = models.ForeignKey(group1,on_delete=models.CASCADE,blank=True,null=True) Opening_Balance = models.DecimalField(max_digits=19,decimal_places=2,blank=True) class journal(models.Model): Date = models.DateField() By = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Debitledgers') To = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Creditledgers') Debit = models.DecimalField(max_digits=10,decimal_places=2) Credit = models.DecimalField(max_digits=10,decimal_places=2) class selectdatefield(models.Model): Start_Date = models.DateField(blank=True, null=True) End_Date = models.DateField(blank=True, null=True) Do anyone have any idea about how to do this type of mathematical calculation in django views??? -
How to store python script data into Django model
I've already written a script that parses JSON data from a particular url and stores them into a list. After that I'm able to pass that as an argument to be displayed in my template. My end goal is to display a table on the template from this JSON data (of which I have currently included only one parameter), for which I believe I need to pass that list into a Django Model. def index(request): is_cached = ('raw_json' in request.session) print(is_cached) if not is_cached: # g = {'starttime': '2014-01-01', 'endtime': '2014-01-02', 'minmagnitude': '5'} g='' url1 = ul.urlencode(g) # print(url1) main_api = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&' final_url = main_api + url1 # print(final_url) raw_json = requests.get(final_url).json() string_json = json.dumps(raw_json) # print(raw_json) with open('test.txt', 'w') as file: file.write(string_json) count = raw_json['metadata']['count'] print('Count: ' + str(count)) maglist = [] placelist = [] for cou in range(0, count): mag = (raw_json['features'][cou]['properties']['mag']) maglist.append(mag) # magdict = dict(list(enumerate(maglist))) place = (raw_json['features'][cou]['properties']['place']) placelist.append(place) # placedict = dict(list(enumerate(placelist))) # print(placedict) with open('test2.txt', 'w+') as t1: for features in raw_json['features']: coordinates = (features['geometry']['coordinates']) id = (features['id']) t1.write("id: %s \n" % (id)) t1.write("coordinates: %s \n" % (coordinates)) # print(singfeature) for properties, value in features['properties'].items(): t1.write("%s : %s \n" % (properties, value)) # t1.write("\n") … -
'Post' object has no attribute 'properties'
I am using Django 1.11 and Python 2.7 with Google Appengine's NDB Library. I want to serialize my NDB model. I am following this. models.py class DictModel(ndb.Model): def to_dict(self): return dict([(p, unicode(getattr(self, p))) for p in self.properties()]) class Post(DictModel): text = ndb.StringProperty() date = ndb.DateProperty(auto_now_add=True) url = ndb.StringProperty() url_title = ndb.StringProperty() url_text = ndb.StringProperty() privacy = ndb.StringProperty() tags = ndb.StringProperty() @classmethod def query_post(cls, ancestor_key): return cls.query(ancestor=ancestor_key).order(-cls.date) views.py @login_required() def get_user_profile(request, username): user = User.objects.get(username=username) ancestor_key = ndb.Key(Post, username) posts = Post.query_post(ancestor_key) print(posts) return HttpResponse(json.dumps([p.to_dict() for p in posts]), content_type='application/json') -
Django custom validation error for unchanged update form
I have a form that has three CharFields. It gets loaded with an existing object. I am trying to write a custom validation that will return a 'No changes made' errorif a user tries to submit the form without making any changes. Is there a way to compare initial form and updated form without going through each field? Something like: form = Form(instance=id) if request.POST.form == form: raise ValidationError( _('No changes made to name.'), code: 'No_changes' ) -
Django how to tell if signal was called in a request or not
I'm using Django 1.10 Is there a way to tell in a signal whether the 'save()' that triggered that signal was called within the view Request or by 'manual' save()? I have a signal that does some action. I want to do different action, depending if I'm in a middle of request or not (updating items in Celery task) -
Django : Allow user to select the right forms for registering
I'm new to Django and I would like to create a "modular registering form". The aim of this form is to be able to select the needed form (related to the user type) to complete the registration of a new user. models.py class UserTypes(models.Model): USER_TYPES = ( ('simple', 'simple'), ('advanced', 'advanced') ) user_type = models.CharField(max_length = 10, choices = USER_TYPES) class FirstClass(models.Model): username = models.CharField(max_length=100, null=True) first_name = models.CharField(max_length=100, null=True) last_name = models.CharField(max_length=100, null=True) class SecondClass(models.Model): link_to_first_class = models.OneToOneField(FirstClass, on_delete=models.CASCADE, null=True) other_informations = models.CharField(max_length=200, null=True) forms.py class UserTypesForm(forms.ModelForm): class Meta: model = UserTypes fields = '__all__' class FirstClassForm(forms.ModelForm): class Meta: model = FirstClass fields = '__all__' class SecondClassForm(forms.ModelForm): class Meta: model = SecondClass fields = '__all__' exclude = ('link_to_first_class',) views.py @transaction.atomic def modular_register(request): if request.method == 'POST': user_types = UserTypesForm(request.POST) first_form = FirstClassForm(request.POST) second_form = SecondClassForm(request.POST) if user_types_form.is_valid() and first_form.is_valid() and second_form.is_valid(): first_form.save() first_class_instance = FirstClass.objects.filter(username = first_form.data['username'])[0] second_class = SecondClass(link_to_first_class = first_class_instance, other_informations = second_form.data['other_informations']) second_class.save() messages.success(request, 'Account created successfully') return redirect('modularregister') else: user_types_form = UserTypesForm() first_form = FirstClassForm() second_form = SecondClassForm() return render(request, 'blog/modularregister.html', {'user_types_form':user_types_form, 'first_form': first_form, 'second_form' : second_form} ) template <form method="post" > {% csrf_token %} <table> {{ user_types_form.as_table }} {{ first_form.as_table }} {{ second_form.as_table }} … -
How can I connect android app to django backend
I am working on an android app and I want to use Django in Back-end, I found a solution is to use Django REST Framework but I don't know how to connect Django to android . I thin I must modify settings.py but I don't really know how to do it. Is there any help please and thanks for you all in advance! -
How do I pull data from a nested field in elasticsearch django?
I have my Response and Question table linked together by an FK. documents.py: responses = Index('responses') @response_index20.doc_type class ResponseDocument20(DocType): Question = fields.NestedField(properties={ 'Statement': fields.TextField(), 'pk': fields.IntegerField(), }, include_in_root=True) class Meta: model = Response fields = [ 'Response', ] related_models = [Question] views.py: if queryR == "questions": responses = ResponseDocument20.search().query("nested", path="Statement", query=Q("wildcard", Question__Statement=q)).extra(size=10000) #ES elif queryR == "responses": responses = ResponseDocument20.search().query("wildcard", Response=q).extra(size=10000) #ES I am able to pull the Response field no problem using this: .query("wildcard", Response=q). But i want to also pull data from Statement field under Question, not sure how the code is meant to look like: .query("nested", path="Statement", query=Q("wildcard", Question__Statement=q)) Keep getting an error or it just returns 0 data. -
Bulk update data in Django Rest Framework & Swagger integration
I have a simple model that and I want allow users to make a Buld Update. I tried this: class UpdateFooViewSet(mixins.UpdateModelMixin, GenericViewSet): queryset = Foo.objects.all() serializer_class = FooSerializer def update(self, request, *args, **kwargs): serializer = FooSerializer(data=request.data, many=True) return super(UpdateFooViewSet, self).update(request, *args, **kwargs) Where: class FooSerializer(ModelSerializer): class Meta: model = Foo fields = '__all__' And: drf_router = SimpleRouter() drf_router.register(r'update_foo', UpdateFooViewSet) When I open My swagger docs I can see new entries for my Foo model: PUT /foo/update_foo/{id}/ PATCH /foo/update_foo/{id}/ The problem is that both require a specific ID and neither support a List of Foos as input. How can I make them support a list to allow the desire Bulk Edit? -
Use of class MyDict(dict), do it really make any difference by passing the inherited class?
What is the use of MyDict class and from where this .content method came from, any help will be appreciated class MyDict(dict): pass company_settings_dict = instance.as_company_console_settings() message = MyDict() notification_type = "CompanyConsoleSettings" data = {"data": company_settings_dict, "notification_type": "%s" % (notification_type), "is_new": False} message.content = {"message": "%s" % (json.dumps(data)), "room": instance.company.id} -
Please Wait screen stucks while loading a page in django
I have a page that has a submit button. When i click submit button, it should call a view that will create an excell file. When i click submit button the excell file is suddenly created. But Please Wait... box appears in the page. And it freezes. Is there a way to set a timeout for just to this view and forwar it to another page if timeout happens. def print_permission_document_multiple(request, doctype): if request.method == 'GET': date = str(nicosia_date(datetime.today()).date()) studentclass = "6C" studentno = "10271515" studentname = "testname" studentsurname = "testsurname" if doctype == "doctype-studentlatepermission": workbook = load_workbook(os.path.join(settings.BASE_DIR, "export_templates", "x101.xlsx")) elif doctype == "doctype-studentschoolexitpermission": workbook = load_workbook(os.path.join(settings.BASE_DIR, "export_templates", "x102.xlsx")) elif doctype == "doctype-studentinschoolpermission": workbook = load_workbook(os.path.join(settings.BASE_DIR, "export_templates", "x103.xlsx")) worksheet = workbook.active date_cell = worksheet["F%d" % (6,)] time_cell = worksheet["F%d" % (7,)] class_cell = worksheet["B%d" % (12,)] no_cell = worksheet["C%d" % (12,)] namesurname_cell = worksheet["D%d" % (12,)] date_cell.value = date time_cell.value = "" class_cell.value = studentclass no_cell.value = studentno namesurname_cell.value = studentname+" "+studentsurname file_name = os.path.join(settings.BASE_DIR, "export_templates", "nepericon.PNG") img = Image(file_name) worksheet.add_image(img, 'A3') tmp_file = tempfile.NamedTemporaryFile() workbook.save(tmp_file.name) response = HttpResponse(smart_str(tmp_file.read()), content_type='application/vnd.ms-excel') response["Content-Disposition"] = 'attachment; filename="x102.xlsx"' return response