Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you hand off a website built from django to a client?
After you are finished with a website, how do you transfer the website to your client online via internet so that the client can effectively understand and use the website? -
'view' didn't return an HttpResponse object. It returned None instead.` - class based view
I am trying to access the posted form values in a class based Django view (UpdateView). I have it nearly working, but I am getting the error: The view maintenance.views.maintenanceEdit didn't return an HttpResponse object. It returned None instead. I have found many other posts having the same problem with a function based view, which return render(request, 'template.html') fixes the problem, but how can I do the same thing with a class based view? my views.py: class maintenanceEdit(LoginRequiredMixin,UpdateView,): model = Maintenance form_class = EditMaintenance template_name = 'maintenance_edit.html' login_url = 'login' def form_valid(self, form,): instance = form.save(commit=False) complete = form.instance.completed super(maintenanceEdit, self).form_valid(form) In my models.py I have: def get_absolute_url(self): return reverse('equipmentdashboard',) Which brings the user back to the correct page when the form is submitted. But now this is not working... -
Ways to create reusable sets of fields in Wagtail?
I'm evaluating Wagtail to see if I can find a place for it along side Wordpress and Drupal in my company. So far I think it's interesting and really like a lot of it, but there's one thing I would really like and can't find a way to do it. My shop uses a pattern library (a la Atomic Design) and initially I was excited by the StreamField and it's ability to tie directly in to a pattern library, including creating nested patterns (a reusable button class that can be put in a CTA and a Hero Widget. But the stream field doesn't work for required page elements that have to be in a certain location, possibly outside the content flow (hero content, calls to action...). I found this issue: https://github.com/wagtail/wagtail/issues/2048 But it doesn't seem to be resolved and hasn't had activity in a long time. Right now I've found two possible solutions: A stream field with only one block possible, and a min and max of one of them. The drawback is that the UI doesn't seem to be aware of the min/max and you have to save the page before you're told. Also, the form isn't automatically visible, … -
How do I condense annotated queryset results based on a particular field?
Here's a fun one. Maybe someone can figure this out. Say I have a queryset something like the one below and want to get leads by month per company. Company.objects.annotate( month=TruncMonth('leads__date_received') count=Count('leads') ).values('company__name', 'month', 'count') This will give me one dict per month for each company, something like this: {'company_name': 'Amazon', 'month': '2018-01-01', 'count': 333}, {'company_name': 'Amazon', 'month': '2018-02-01', 'count': 444}, {'company_name': 'Amazon', 'month': '2018-03-01', 'count': 555}, This is great but requires further processing if I want to put this in tabular form. What I would like is a result like the following: {'company_name': 'Amazon', '2018-01-01': 333, '2018-02-01': 444, '2018-03-01': 555} This is ideal if I already know the month range and can pull out each column value on the basis of the month key. Anyone know a slick way of condensing results like this? Is there some already-built auxiliary function that can do this? Any simple database tricks? Curious to hear. -
/post/how-to-write-a-pattern-to-accept-this-kind_of_url (In Django)
I'm trying to achieve a product URL as shown below: base_url/product/this-is-sample-of-product-1 URL can have a combination of the hyphen, underscore, a-zA-Z,0-9 (Similar to the url of posts as in wordpress) Please help, How to achieve this in urls.py - Django. I have tried this code in my urls.py but it is not working. url(r'^product/([-\w]+)/$', include('product.urls')), -
unique constrain fails with foreignKey field
I want to make a position model with a foreign key to a category model, but i get a unique constrain error when adding 2 position to one category although the category field is foreignkey model not one-to-one field i tried many things but it didn't work class Category(models.Model): name = models.CharField(max_length=50, unique=True) _type = models.CharField(max_length=20, null=True) class Position(models.Model): name = models.CharField(max_length=50, unique=True) category = models.IntegerField(Category, on_delete=models.CASCADE) -
DRF Reverse Not Finding Proper Route
I am using Django Rest Framework and I cannot get reverse() to return the proper route for testing purposes. I must have made a mistake somewhere along the path of registering my routes but I can't seem to figure out what it is. core/urls.py class CoreRouter(DefaultRouter): def __init__(self): super(DefaultRouter, self).__init__() self.trailing_slash = '/?' router = CoreRouter() router.register(r'works', WorkViewSet, base_name='work') router.registry.extend(fairs_exhibitions_router.registry) urlpatterns = [ re_path(r'^api/(?P<version>(v1))/', include(router.urls)), re_path(r'^api/(?P<version>(v1))/', include('fairs_exhibitions.urls')), ] fairs_exhibitions/urls.py: router = CoreRouter() router.register(r'fairs', FairTagViewSet, base_name='fair') router.register(r'exhibitions', ExhibitionTagViewSet, base_name='exhibition') urlpatterns = [ url(r'^', include(router.urls)), ] (I ommited includes/a couple of unrelated routes) I can hit api/v1/fairs just fine but when i try to use reverse() i cant seem to find the fairs path: reverse(fairs) or reverse(fairs-list) just says it's not found The closest I got was reverse('fair-list') which yielded this error: NoReverseMatch: Reverse for 'fair-list' with no arguments not found. 4 pattern(s) tried: ['api/(?P(v1))/fairs/?\.(?P[a-z0-9]+)/?$', 'api/(?P(v1))/fairs/?$', 'api/(?P(v1))/fairs/?\.(?P[a-z0-9]+)/?$', 'api/(?P(v1))/fairs/?$'] It seems like my issue might have something to do with the ?$ but I cant figure out where that is coming from or how to handle it. -
DisallowedHost at / Invalid HTTP_HOST header when domain name already exists in ALLOWED_HOSTS
i have purchased my domain from godaddy.com and made it work for my digital ocean droplet. afteri added the domain to "sites-available" for nginx and refreshed the page i got the "disallowed host" error. I already have the domain name in ALLOWED_HOSTS but i still see the "disallowed host" error. -
Django React Project structure that scale
I am so exhausted finding repository to get best Django Rest API and ReactJs project structure. I am integrating Django witht ReactJS. I am struggling to structure my project that is easy to scale. Can any Django-React Developer suggest me a porject structure that is easy to scale and manage? Git link would be much appreciated. I found huge Django-React Project and i am confused which one should i follow. I need best one to structure Django-React project and that is scale-able -
Django's str(queryset.query) returns invalid SQL if I compare datetimes
I have a Django queryset that I prepare with queryset.filter(date__gte=datetime(2011,1,1)) If I then call str(queryset.query) I see this in the string: ... WHERE "App_table"."date" >= 2011-1-1 However, this is invalid SQL code as if I run this in Postgresql I get this error: ... WHERE "App_table"."date" >= 2011-1-1 ERROR: operator does not exist: date >= integer HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. Why is this happening and how can I ask Django to output proper SQL code that I can work on? -
Defining part of a mock call as default values
I'm writing a unittest to ensure a mocked method is called with the correct arguments. Part of my unittest looks like this: response = MagicMock(name='response', status_code=200) # Make some calls expected_calls = [ call( "X", "1", domain="mywebsite.com", httponly=True, max_age=1000, path="/", secure=False, ), call( "Y", "2", domain="mywebsite.com", httponly=True, max_age=1000, path="/", secure=False, ), ] response.set_cookie.assert_has_calls(expected_calls) In other words, only the key and value of these call objects changes. How can I get something of the form: default_values = {...} expected_calls = [ call( "X", "1", default_values, ), call( "Y", "2", default_values, ), ] -
Unable to display form fields and objects in django
I am trying to create multiple forms in one template page(dischargedetails.html) using different views. Each form model is having foreignkey Ipd,First form (ProcedureForm) is working fine but the in Second form(investigation Form) not able to display investigation date feild and investigation name field models.py : class Investigation(models.Model): id = models.AutoField(primary_key = True) ipd = models.ForeignKey(Ipd,on_delete = models.DO_NOTHING) name = models.CharField(max_length=60) report = models.TextField(max_length=500) date = models.DateField(("Date"), default=datetime.date.today) class Procedure(models.Model): id = models.AutoField(primary_key = True) ipd = models.ForeignKey(Ipd,on_delete = models.DO_NOTHING) report = models.TextField(max_length=500) date = models.DateField(("Date"), default=datetime.date.today) time = models.TimeField( blank=True,default=now) urls.py : re_path(r'^(?P<ipd_id>\d+)/investigation/$', my_patient.create_investigation, name='create-investigation'), re_path(r'^(?P<ipd_id>\d+)/dischargedetails/$', my_patient.discharge_detail, name='discharge_details'), views.py: @login_required def discharge_detail(request,ipd_id): object = get_object_or_404(Ipd,pk=ipd_id) if request.method =="POST": procedure = ProcedureForm(request.POST) if procedure.is_valid(): procedure.save() return HttpResponseRedirect(request.path_info) else : return HttpResponse(procedure.errors.as_data()) else : prolist=Procedure.objects.all().filter(ipd=ipd_id) procedure = ProcedureForm() return render(request, 'dischargedetails.html',{'object':object,'procedure':procedure,'prolist':prolist}) @login_required def create_investigation(request,ipd_id): object = get_object_or_404(Ipd,pk=ipd_id) if request.method=="POST": investigation = InvestigationForm(request.POST) if investigation.is_valid(): inves = investigation.save(commit = False) inves.object = object inves.save() return HttpResponseRedirect(request.path_info) else: return HttpResponse(investigation.errors.as_data()) else : investigationlist = Investigation.objects.all().filter(ipd=ipd_id) investigation = InvestigationForm() return render(request, 'dischargedetails.html',{'object':object,'investi':investigation,'investilist':investigationlist}) template <form method="post" action="{% url 'create-investigation' ipd_id=ipd.ipd_id %}" enctype="multipart/form-data"> <label>Date</label> <div class="input-group date"> {{ investi.date| add_class:'form-control' }} <label id="addNotesIDhelp" class="error" for=""></label> </div> <div class="form-group"> <textarea id="notesTextId" name = "report" type="text" placeholder="Add Investigation"class="form-control" value … -
iam getting stuck with the data preprocessing code for machine learning application
currently iam developing a machine learning application please help me in this code when i was uploading the big datasets getting an error please help in this code prep_file = Prepross.objects.get_or_create(filename = CurrentFile.objects.order_by('-id')[0].filename, coltype = request.POST.getlist('coltype'), assvar = request.POST.getlist('assvar'), missingvalues = request.POST.getlist('missingvalues'), trainingset_size = request.POST['trainingset_size'], featscaling = request.POST.getlist('featscaling') ) # Get dataframe and change data type context = {} file_name = CurrentFile.objects.order_by('-id')[0].filename coltype = request.POST.getlist('coltype') coltype = dict([i.split(':', 1) for i in coltype]) df = pd.read_csv(os.path.join('media\downloaded', file_name), dtype= coltype) row_count = df.count()[0] # Keep only selected columns assvar = request.POST.getlist('assvar') xcols0 = [s for s in assvar if ":X" in s] xcols = [i.split(':', 1)[0] for i in xcols0] ycol0 = [s for s in assvar if ":y" in s] ycol = [i.split(':', 1)[0] for i in ycol0] cols = xcols + ycol df = df[cols] xcols = ', '.join(xcols) ycol = ', '.join(ycol) missing = request.POST.getlist('missingvalues') missing = ', '.join(missing) trainingset_s = request.POST.getlist('trainingset_size') trainingset_s = ', '.join(trainingset_s) testset_s = 100 - int(trainingset_s) feat = request.POST['featscaling'] # Taking care of missing data if missing == "no": if len(df) != len(df.dropna()): context['selecty'] = 'Your data seem to have Missing Values' else: df = df.dropna() # Return error if columns are not … -
Is there a way to use custom sql queries with various arguments in django?
I'm creating an application that allows a user to filter through millions of records in a database (using dates, post types, etc.). The problem is that the database queries I need to perform are kind of complicated to use Django's ORM so I need to use custom SQL, and I don't have much experience dealing with SQL and this part of Django. If I needed the user specified filters before executing the query, how can I put in custom SQL without knowing how many filters/parameters there might be? And after that, how do I return what I found through that custom query into views so that the results can be displayed on the web page? I've already looked at the Django documentation on raw and custom SQL queries but there isn't a lot of documentation and help on custom SQL queries outside of the Django official documentation, so any help would be appreciated. from django.db import connection def my_custom_sql(self): with connection.cursor() as cursor: cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz]) cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz]) row = cursor.fetchone() return row The example code here is from the documentation. Say the filter had … -
Is there a way to use custom template in editor in django admin?
I have an issue with loading custom template file into editor which resides in django admin. I just simply put the file path into CKEDITOR_CONFIGS like so: CKEDITOR_CONFIGS = { 'default': { 'toolbar': [ [...] ], 'templates_files': [ /path/to/template/template.js' ], 'templates': 'template' } } CKEDITOR.addTemplates( 'template', { templates: [ { title: 'BLEBELLBELBE', description: 'A template that defines two columns, each one with a title, and some text.', html: '<table cellspacing="0" cellpadding="0" style="width:100%" border="0">' + '<tr>' + '<td style="width:50%">' + '<h3>Title 1</h3>' + '</td>' + '<td></td>' + '<td style="width:50%">' + '<h3>Title 2</h3>' + '</td>' + '</tr>' + '<tr>' + '<td>' + 'Text 1' + '</td>' + '<td></td>' + '<td>' + 'Text 2' + '</td>' + '</tr>' + '</table>' + '<p>' + 'More text goes here.' + '</p>' } ] } ); Ckeditor is ignoring the file or just throwing and error on browser console that file can't be loaded. What am I doing wrong? -
python : object.__dict__ not showing all attributes
I am trying to print all the attibutes of an object. The purpose is mainly for debugging. I am using the following code: import json print(json.dumps(object.__dict__), indent=4, sort_keys=True, default=str)) It prints the attibutes of the object. But i was checking the list of all properties of the object using dir(object) I found that __dict__ does not show some properties at all which are listed by dir(). I thought of using dir(object) but it only a list of properties without attributes. So i think: `__dict__` has `incomplete` properties but with attirbutes `dir()` has complete list of properties but no attibutes So what is the best way to get a full dictionary of a attibutes of an object so that i can pretty print and see using json.dumps EXAMPLE I am working in a django project. And this is with related to db connection so the example is of a variable names db_con which is of the following object <django.db.backends.postgresql.base.DatabaseWrapper object at 0x7f29dee47a58> __dict__ way import json print(json.dumps(db_con.__dict__), indent=4, sort_keys=True, default=str)) The output is { "_thread_ident": ATTRIBUTE_VALUE "_thread_sharing_count": ATTRIBUTE_VALUE "_thread_sharing_lock": ATTRIBUTE_VALUE "alias": ATTRIBUTE_VALUE "autocommit": ATTRIBUTE_VALUE "client": ATTRIBUTE_VALUE "close_at": ATTRIBUTE_VALUE "closed_in_transaction": ATTRIBUTE_VALUE "commit_on_exit": ATTRIBUTE_VALUE "connection": ATTRIBUTE_VALUE "creation": ATTRIBUTE_VALUE "errors_occurred": ATTRIBUTE_VALUE "execute_wrappers": ATTRIBUTE_VALUE "features": … -
Python Django multiple request parameters
I am new to python & django and am trying to build a simple web application. I am running into the below issue I am passing the following code def view(request, cases_id, transactions_id): item = Cases.objects.get(pk=cases_id) item2 = Transactions.objects.get(pk=transactions_id) return render(request, 'view.html', {'item': item, 'item2': item2}) and getting the following error: view() missing 1 required positional argument: 'transactions_id' -
Docker up command exited with code 0 on another machine
Docker container for my app works fine on my system, while it doesn't on others'. I tried the following commands to re-run my docker container on a different machine: $docker-compose build $docker-up (this is where it fails !) Docker FROM python:3.6.8 MAINTAINER angy@localhost COPY ./ /app WORKDIR /app RUN pip install -r requirements.txt #CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] docker-compose.yml version: '3' services: python: build: context: . dockerfile: Dockerfile volumes: - ./:/myapp ports: - "8000:8000" Starting angy_proj_python_1_b395bdd740ea ... done Attaching to angy_proj_python_1_b395bdd740ea angy_proj_python_1_b395bdd740ea exited with code 0 -
Display all facets that were enabled in previous page
I have a book catalogue which I'm trying to filter search through. Each book falls under topic: ("english" "science" etc) and has a subcategory subcategory: (english: [poetry, plays], science: [chemistry, mechanics]). Each book item also has 2 attributes: book_format ("paperback" ,"hardcover" etc) language Currently the first 2 filters based on topic and subcategory work fine. Under format and language I've found a bug that enables a previously unavailable facet. For example if I chose "science book -> chemistry" the facet_count returns 0 "paperback books" so paperback is unavailable. But when I any other book format in the format field it enables paperbacks. I've debugged and traced the error to oscar.apps.search.facets in munge_field_facet the 'disabled' key is set to True or False based on: 'disabled': count == 0 and not is_faceted_already is_faceted_already is always true, this is because it is dependent on whether any facet in that field has been selected. In my case since I chose "hardcover" in the book_format field all of the facets in that field are enabled. I've checked the docs and various forums on faceting and it seems no one has needed to choose multiple facets whilst keeping previously disabled facets disabled. Here is the problem … -
Reduce 'waiting' time for a GET request to API
I am using Angular for frontend and Django for backend. I am referencing an API with particular graph data I am trying to retrieve. I think I have done it in an efficient way and have tried researching the best ways to do it. But the timings still show 5000-6000ms in waiting. Is this because of the angular to django link before the request is actually sent? I am doing it this way as I have an authorization key I wanted to keep secure in the backend. Code is long and in many files, I will try to explain: -Django get request to retrieve data for 3 graphs, this view also transforms the data into dictionaires and then returns keys and values separately as a response.-This is all coming from the Angular frontend which calls this upon loading the page to view the graphs. I expect/want a quick request and subsequent page loading but the page loads and then the graphs don't load for another few seconds. Any information would be appreciated. -
Upload image while user is filling in the form and validate the uploaded image
I have a django-form where a user can rate a product. To make sure the user has bought the product he has to upload a picture of the invoice. Every invoice has a bar code so what I want to achieve is to analyze the uploaded picture if there is a bar code. This should happen while the user is filling in the other fields of the form. My question is: is this even possible and if yes how can I upload a Image without pressing the submitbutton of the form. I'm in a early prototyp phase of my project so at the moment its enough when the images are only uploaded to a directory without validation. Please let me now if you need more information -
ValueError at /users/index/ Ensure you specified correct input image, input type, output type and/or output image path
I am building of program using opencv. I get this "Ensure you specified correct input image, input type, output type and/or output image path" error when I pass a variable through the function If I mentioned the image path like "media/image.jpeg" then everything works properly. I have tried using manually like detect("media/image.jpeg") this which works. If I put any variable like detect('"' + uploaded_file_url + '"') it doesn't work. Views.py file from .FirstDetection import detect from django.core.files.storage import FileSystemStorage def index2 (request): global name global uploaded_file_url name = "name" uploaded_file_url = "media/image.jpeg" if request.method == 'POST' and request.FILES['pic']: pic = request.FILES['pic'] fs = FileSystemStorage() filename = fs.save(pic.name, pic) uploaded_file_url = fs.url(filename) name = detect("media/image.jpeg") mylist = [] for n in name: mylist.append(n) return render(request, 'index.html', { 'uploaded_file_url': uploaded_file_url, 'd2' : mylist }) return render(request, 'index.html')''' **Detection.py file** from imageai.Detection import ObjectDetection import os def detect(image): # execution_path = os.getcwd() os.chdir("/Users/sifatulshohan/Documents/CSE-327/Django_project/nsu.nbm.summer2019.cse327.1.t3/Django") media_path = os.getcwd() if os.path.exists("/Users/sifatulshohan/Documents/CSE-327/Django_project/nsu.nbm.summer2019.cse327.1.t3/Django/media") : os.chdir("/Users/sifatulshohan/Documents/CSE-327/Django_project/nsu.nbm.summer2019.cse327.1.t3/Django/media") execution_path = os.getcwd() detector = ObjectDetection() detector.setModelTypeAsRetinaNet() detector.setModelPath( os.path.join(execution_path , "resnet50_coco_best_v2.0.1.h5")) detector.loadModel() url = '"' + "'" + image + "'" + '"' detections = detector.detectObjectsFromImage(input_image=os.path.join(media_path , image), output_image_path=os.path.join(execution_path , "imagenew.jpeg")) for eachObject in detections: name = eachObject["name"] # probability = eachObject["percentage_probability"] if(eachObject["percentage_probability"] … -
How to implement a progress bar based on the execution time of python function called in django views.py?
I'm executing a python function called through Django views.py. The python function takes about 3 to 10 minutes to complete. Based on the execution time of the above python function, how do I show the progress bar in front end? -
How to save ModelForm fields that are disabled in a template? (Not included in POST request)
I have created a ModelForm and an UpdateView to update the model's values. To simplify, let's say I have formfields A,B and C. My template displays A,B and C, but users can only edit A and B. C is calculated based on the values of A and B (server-side only). I am calculating C in the clean_C method of the modelform. If I set C to 'disabled' in my template, the value is not updated in my model. (I'm guessing this is because it is not included in the POST data?) If I set C to readonly, it saves correctly. Is there a way to still save C while keeping the field disabled? (to clarify, there is nothing in my model/modelform that disables the field, this is only in the template) It looks like the clean_C method runs regardless of the disabled/readonly flag in the template, and the appropriate value is included in the cleaned_data dictionary in the modelform's clean method. I've been digging through the Django source code to figure out why this happens. Can someone point me to where the data from cleaned_data is saved to the ModelForm / Model? -
Multiple pdf file should upload
While selecting Multiple pdf file is selected but while saving only one file is saving views.py def pdf_upload(request): pdf = Client_files.objects.all() client = Client.objects.all() process = Client_Process.objects.all() print(process) print(client) if request.method == 'POST': form = Upload_files(request.POST,request.FILES) if form.is_valid(): form.save() return redirect('/pdf/upload/') else: form = Upload_files() return render(request,'uploadpdf.html',{'form':form,'pdf':pdf,'client':client,'process':process,}) models.py class Client_files(models.Model): Date = models.DateTimeField(default=datetime.now, blank=True) client = models.ForeignKey(Client, on_delete=models.CASCADE,null=True) client_process = models.ForeignKey(Client_Process, on_delete=models.CASCADE,null=True) File_Name = models.FileField() Pages = models.IntegerField(null=True) Count = models.IntegerField(null=True) Status = models.BooleanField(default = False) class Meta: db_table : 'client_files' Attached the views and models,while selecting file i can select multiple files but while uploading i can only upload one file