Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: matching URL patterns to display data results in a 404
I am trying to use the URL pattern match to display data dynamically in my template. The goal is to display data based on organization type of which I have 3: Manufacturers, Suppliers, and Distributors. So, if the URL matches /profiles/man_dash/manufacturers/ display data for all Manufacturers. Below is my code: View def man_org_list(request, member_type=None): member_type_map = { 'manufacturers': 'Manufacturer', 'suppliers': 'Supplier', 'distributors': 'Distributor' } member_type = member_type_map.get(member_type, None) if member_type is None: raise Http404 queryset = Organization.objects.filter(member__member_flag=1, member__member_type=member_type).order_by('id') return render(request, 'profiles/man_dash.html', {'object_list': queryset}) urls.py urlpatterns = [ url(r'^$', views.org_list, name='org_list'), url(r'^(?P<id>\d+)/$', views.org_details, name='org_details'), url(r'^man_dash/<str:member_type>/', views.man_org_list, name='man_org_list') ] Code block I want to display: {% for org in object_list %} <tr> <th scope="row">{{ org.id }}</th> <td>{{ org.org_name }}</td> <td>{{ org.org_type }}</td> {% for member in org.member.all %} <td>{{ member.member_flag }}</td> {% endfor %} {% for c_score in org.c_score.all %} <td>{{ c_score.completeness_score }}%</td> {% endfor %} <td><a href="{% url 'org_details' org.id %}" target="_blank">View</a></td> </tr> {% endfor %} For some reason, I keep getting 'The current path, profiles/man_dash/manufacturers/, didn't match any of these.' error. -
django-mysql connection inside docker-compose giving connection refused
Dockerfile FROM python:3.6 ENV PYTHONUNBUFFERED 1 WORKDIR /usr/src/govtcareer_api COPY ./ /usr/src/govtcareer_api RUN pip install -r requirements.txt CMD ["/bin/bash"] docker-compose.yml version: "3" services: govtcareer_api: container_name: govtcareer build: . command: "bash -c 'python manage.py migrate --no-input && python manage.py runserver 0.0.0.0:8000'" working_dir: /usr/src/govtcareer_api ports: - "8000:8000" volumes: - ./:/usr/src/govtcareer_api links: - db db: image: mysql environment: - MYSQL_ROOT_PASSWORD=Thinkonce - MYSQL_USER=soubhagya - MYSQL_PASSWORD=Thinkonce - MYSQL_DATABASE=freejobalert ports: - "3306:3306" django database connection: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'freejobalert', 'USER': 'soubhagya', 'PASSWORD': 'Thinkonce', 'HOST': 'db', 'PORT': '3306', }, } errors: govtcareer | Traceback (most recent call last): govtcareer | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection govtcareer | self.connect() govtcareer | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect govtcareer | self.connection = self.get_new_connection(conn_params) govtcareer | File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 227, in get_new_connection govtcareer | return Database.connect(**conn_params) govtcareer | File "/usr/local/lib/python3.6/site-packages/MySQLdb/__init__.py", line 85, in Connect govtcareer | return Connection(*args, **kwargs) govtcareer | File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 204, in __init__ govtcareer | super(Connection, self).__init__(*args, **kwargs2) govtcareer | _mysql_exceptions.OperationalError: (2003, 'Can\'t connect to MySQL server on \'db\' (111 "Connection refused")') govtcareer | govtcareer | The above exception was the direct cause of the following exception: govtcareer | govtcareer | Traceback (most recent call last): govtcareer | File "manage.py", line … -
DoesNotExist in Django with docker-compose
I use docker-compose to manage a django app and it's database. My problem is when I add some type off object in the database I have a DoesNotExist error : error message. What I don't understand is that the data IS in the database and i can request it from the django app docker without any problem. I don't have the issue when I run the app in dev mode with python manage.py runserver with a local database. Here is my docker-compose.yml : version: '3' services: dojodb: image: mysql:5 environment: MYSQL_ROOT_PASSWORD: password MYSQL_USER: root MYSQL_DATABASE: dojodb volumes: - dojodbvolume:/var/lib/mysql dojo: build: . environment: - SQLHOST=dojodb - SQLPORT=3306 - SQLUSER=root - SQLPWD=password - DBNAME=dojodb ports: - "8000:8000" depends_on: - dojodb volumes: dojodbvolume: I really don't see where the problem comes from. -
E-Commerce Platform for Research Purpose
I would like to simulate a webshop for an economic experiment. It should be modular and atomic, so that other researchers are not limited to the basic functions, but are allowed to extend the features by modifying the code or by writing plugins. For example, I would like to support ecological price decisions, through co2 pricing, informations about ecological impacts etc. and this should be easy to "play" in treatments or to be changed in the backend, similar to otree / ztree. I think that python / a django-based shop is good for it. But what framework would you recommend for the beginning, Django-shop, saleor, Oscar... Any tips? -
Circles not getting aligned properly on the chart D3 Django
Here is the attempt I have made in order to fulfill my visualization. <!DOCTYPE html> <meta charset="utf-8"> <style> /* set the CSS */ .line { fill: none; stroke: steelblue; stroke-width: 2px; } </style> <body> <!-- load the d3.js library --> <script src="https://d3js.org/d3.v4.min.js"></script> <script> var real = {{values.real0|safe}}, pred = {{values.got0|safe}}; // set the dimensions and margins of the graph var margin = {top: 20, right: 20, bottom: 30, left: 50}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; // parse the date / time var parseTime = d3.timeParse("%d-%b-%y"); // set the ranges var x = d3.scaleLinear() .range([0, width]) .domain([0, Object.keys(real).length]) ; var y = d3.scaleLinear() .range([height, 0]) .domain([0, 1]); // define the line var valueline = d3.line() .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.close); }); // append the svg obgect to the body of the page // appends a 'group' element to 'svg' // moves the 'group' element to the top left margin var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // Add the valueline path. // svg.append("path") // .data([real]) // .attr("class", "line") … -
Trying to pass form from generic.FormView to generic.DetailView
I'm new in Django and it's just a test for further model. I'm trying to pass a form from generic.FormView to generic.DetailView, and exhibit the datas inserted in the previous HTML (associated with the FormView) to another HTML (associated with the DetailView). I've thought it probably a problem with the link between the view.py and urls.py. The codes are: views.py: class IndexView(generic.FormView): template_name = 'dutos/index.html' form_class = GetDate success_url = 'dutos/detail.html' #def form_valid(self, form): #return HttpResponse(self.success_url) #return super.form_valid(form) class DetailView(generic.DetailView): model = Dutos template_name = 'dutos/detail.html' urls.py: from django.urls import path from .views import views urlpatterns = [ path('', views.IndexView.as_view(), name="index"), path('detail/', views.DetailView.as_view(), name="detail"), ] index.html: <!DOCTYPE html> <html> <head> <title>Template</title> </head> <body> <h1>Teste HTML</h1> <div class="container-fluid" id="wrapper"> <div class="row"> <form action="/detail/" method="post"> {% csrf_token %} {{ form.non_field_errors }} <div> <div class="fieldWrapper"> {{ form.dateDataInicial.errors }} <label for="{{ form.dateDataInicial }} Data Inicial: </label> {{ form.dateDataInicial }} </div> <div class="fieldWrapper"> {{ form.dateDataFinal.errors }} <label for="{{ form.dateDataFinal }} Data Final: </label> {{ form.dateDataFinal }} </div> <input type="submit" value="Pesquisar"> </div> </form> </div> </div> </body> </html> detail.html: <!DOCTYPE html> <html> <head> <title>Template</title> </head> <body> <h1>Template HTML</h1> {{form.cleaned_data['dateDataInicial']}} {{form.cleaned_data['dateDataFinal']}} </body> </html> I've already change the "{{form.cleaned_data['dateDataInicial']}}" to "form.dateDataInicial", or just cleaned everything and put "Test" to … -
send email with attachment in Django
I'm using EmailMultiAlternatives to send email with html content, I also need to send .docx file as an attachment in the mail. I used message.attach_file('/tmp/file.docx') but I getting error as "No such file or directory is found" even though path is correct. I also tried with EmailMessage using message.content_subtype to include html_content, but still the same error with .docx attachment. I also want to try message.attach('filename', content, 'mimetype')--> here I don't know what exactly to include in the contentspace. How do I solve this? Email Client is Outlook Django Version - 1.11 Python Version - 3.6 -
All of POST request repeat execute in Django
when i send a form by post request to Django, the Django frame aways double execute the request, include insert data to mysql Database,and not has any exception,i run the command 'python manage.py check',the result is "System check identified no issues", i checked my code,but not found any questions! i also can't find any answers in the website, who can help me!Thanks! here is the log info. enter image description here -
Django filter by aggregate preserving details
I have a fairly simple task to filter models using an aggregate value, for example: class A(models.Model): title = models.CharField() address = models.CharField() page_count = models.IntegerField() Now I need to select all A titles that have a sum of page_count equal to for example 2 for the same address. It would be easy if I would not need the title: A.objects.all().values('address').annotate(pages=Sum(page_count)).filter(pages=2) But what if I need for every "row" to select all As which are "included" in this row. Is this possible in one query? prefetch_related maybe? -
Draw two scatter plots with D3
I am trying to visualize my data with the help of D3. I am a bit new to this library and giving my best to understand. Here is the template that I have tried till now: <head> <script src="http://d3js.org/d3.v4.min.js"></script> </head> <body> <script> // var total = $.parseJSON({{values|safe}}); var real = {{values.real0|safe}}, pred = {{values.got0|safe}}; // console.log(real,pred); var width = window.innerWidth -200, height = window.innerHeight+400; // var data = [10, 15, 20, 25, 100]; var svg = d3.select("body") .append("svg") .attr("width", Object.keys(real).length) .attr("height", height); var xscale = d3.scaleLinear() .domain([0, Object.keys(real).length])///d3.max(data)]) .range([0, width]); // console.log(Object.keys(real).length); var yscale = d3.scaleLinear() .domain([0, 1]) .range([height/2, 0]); var x_axis = d3.axisBottom() .scale(xscale); var y_axis = d3.axisLeft() .scale(yscale); svg.append("g") .attr("transform", "translate(50, 10)") .call(y_axis); var xAxisTranslate = height/2 + 10; svg.append("g") .attr("transform", "translate(50, " + xAxisTranslate +")") .call(x_axis) </script> I got till this: I want to visualize data in the form of scatter data. Where the real values has 3 values 0,0.5, and 1. I have caught the values using django. The following is my views.py function: @csrf_exempt def realpred(request): df_real_pred = pd.read_csv('test.csv', sep=',', index_col=0) print(df_real_pred.columns) data = { 'values': df_real_pred.to_dict(orient='list') } print(data) return render(request, 'tt/realpred.html', data) Here is the sample data of the csv: Test.csv I want to … -
Django - redirecting to home page if no url matched
Basically, my goal is to redirect the user to the view that renders index.html if nothing from URLConf matched the requested url. Then, on the clientside, I would manage routing as appropriate or show 404 page. So basically, the question is, how to implement this redirecting in Django? I have tried this: url(r'^(.*)$', views.index), ...some other urls ...and not surprisingly, (.*) means that ALL urls are redirected to index.html, no matter if there it matches any other URL or not. So should I just place this in the very end of the url list? I have a feeling that I should use some sort of middleware, or maybe Django has a native way to address this issue? An umpleasant side-effect of this would be for users of my rest app. Each time they all an invalid URL, they would get HTML (that would in effect be the HTML for home.html) instead of json or 404 error. Well, nothing ugly about index.html code, and yet it sounds like a bad idea. So would I separate this logic so that the users of REST app get 404 error instead of being redirected to index.html? This is much about coding patterns, not Django … -
Django, suiting model structure
Hi can't figure out a suitable data structure for my models. These are my requirements: Each UserModel is represents a single Referee A RefereeTeam is made of two Referees One Game can have one referee or a RefereeTeam A Referee or a RefereeTeam can request any Game (to supervise it) Each Game can have arbitrary Requests Each Game can have only one appointed Referee or Team States are ('Declined', 'Open', 'Appointed') for each request My current models are just not maintainable. -
Why did Django pagenotAnTntger except generated?
I have sever Error! I want to make projectBoard homepage When I click the title of writings, I want to show the detail of the writings. but pageNotAnInteger except generated In the projectMain.html {{ post.file_title }} through this sentence, I wanted to go to the detail of the writing. but, I coudn't. I thought these process click the title of the writing. In projectMain.html, code, {{ post.file_title }} , is executed. 3. then, ' urlpattern url(r'^project/(?P.+)/$', views.fileDetail, name='fileDetail'),' is executed 4. In views.py, function fileDetail() is executed and execute projectDetail.html will be rendered but caused pageNotAnIntegerError How can I fix it? projectMain.html {% extends 'Project/projectBase.html' %} {% block content %} <div class="container"> <!-- Page Heading/Breadcrumbs --> <div class="row"> <h1 class="col mt-4 mb-3">Project </h1> <div class="col mt-4 mb-4 input-group"> <input type="text" class="form-control" placeholder="Search for..."> <span class="input-group-btn"> <button type="submit", class="btn btn-secondary">Go!</button> </span> </div> </div> <a href="{% url 'newFile' project_name=project_name%}"> <p> FileUpload </p> </a> <a href="{% url 'branchAdminCertification' project_name=project_name%}"> <p> Set mainBranch </p> </a> <div class="row"> {% for post in posts %} <div class="col-lg-4 col-sm-6 portfolio-item"> <div class="card h-100"> <div class="thumbnail-wrapper"> <div class="thumbnail"> <h4 class="card-title"> <a href="{% url 'fileDetail' file_title=post.file_title %}"> {{ post.file_title }} </a> </h4> </div> </div> <div class="card-body"> <p>{{post.origin_date}}에 게시</p> <p>작성자 … -
python Django ASP.NET Identity password hasher equivalent
I have setup task to authenticate django application users against .NET Identity database. I found many related topics, but they was either too old or not solving exaclty what I need - password hasher equivalent for Django. So I end up learning this source https://github.com/aspnet/AspNetIdentity/blob/master/src/Microsoft.AspNet.Identity.Core/Crypto.cs And did write my django version. The code works for me with django 2.1.1 and .NET 4.5 from django.contrib.auth.hashers import pbkdf2 import hashlib from base64 import b64decode identity_PasswordHash = "AOOVvPns8Nov6CsJDTAWz+QDOEO2csh60m5aYyX2Vn7LsNDhiiZ5UaSDWr5izwWeHA==" pwd_plain = 'Hellow123'; def dotnet_identity_check_password(password, hash): binsalt = b64decode(hash)[1:17] binpwd = b64decode(hash)[17:] genpwd = pbkdf2(password, binsalt, 1000, digest=hashlib.sha1, dklen=32) if genpwd == binpwd: return True return False if dotnet_identity_check_password(pwd_plain,identity_PasswordHash): print("OK") else: print("Fail") -
Adding an online compiler like code academy to my Django website
I'm trying to build a website using Django and looking for a way to add it an online compiler like in code academy. Is there a simple way like a Django app that I can plugin into my website or any python API which would let me do that? -
Django queryset grouping
Say I have these pseudo models class Client(models.Model name = ... class Property(models.Model): client = models.ForeignKey(Client ...) name = ... type = ... value = ... For example, I have 2 clients. Each have 2 Property records. It is possible for 2 clients to own the same property, but have unique property records as each client may own a different portion of the property (value). How can I produce a results such that it returns something like: propertyA, {clientA, value}, {clientB, value} propertyB, {clientA, value} where the property is grouped on the name and type of the property? Many thanks -
Django custom login page condition not working
I have 2 login page - login_admin and login_user for admin and normal user respectively. When user enter username and password in login_admin and login_user page, it will check whether user is_staff is True or False. If user is_staff = True, then allow the user login admin page. My problem is: The user can't login to admin page although is_staff = True. The user is able to login to normal user page although is_staff = True. I don't know where is the problem. Here is my code in views.py: def login_admin(request): context = {} if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] if username and password: user = authenticate(username=username, password=password) if user: if not request.user.is_staff: login(request, user) return redirect('/home/') else: context['error'] = "You are authenticated but are not authorized to access this page. Would you like to login to a different account?" return render(request, 'registration/login.html',context) else: context['error'] = "Invalid username or password!" return render(request, 'registration/login.html',context) return render(request, 'registration/login.html') def login_user(request): context = {} if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] if username and password: user = authenticate(username=username, password=password) if user: if not request.user.is_staff: login(request, user) return redirect('/cust/home/') else: context['error'] = "Invalid username or password!" return … -
Apache service wont start through windows services
Using Apache2.4 I could able to start the server and listen on port 8080 through powershell or cmd. I created a windows service using httpd.exe -k install and I could see the service installed as Apache2.4. When I try to start the server through the windows service it fails with below error, whereas I could able to start the apache server from cmd(run perfectly). Error output here -
MultiValueField django unexpected keyword argument error
I want to set field to enter concentration and the units for it. So I have in my model: class Cbc(models.Model): ... hgb = models.PositiveSmallIntegerField() in my form: class CbcForm(forms.ModelForm): ... class Meta: field_classes = { 'hgb' : ConcentrationField, } ... 23 class ConcentrationField(forms.MultiValueField): 24 def __init__(self, **kwargs): 25 _widget = WidgetConcentration 26 fields = ( 27 forms.DecimalField, 28 forms.ChoiceField(choices=(('g/L', 'g/L'), ('g/dL', 'g/dL')), initial='g/L'), 29 ) 30 super().__init__(fields=fields, widget = _widget, **kwargs) 31 32 def compress(self, values): 33 if values[1] == 'g/dL': 34 return values[0] * 10 35 return values[0] but I have an error: TypeError: __init__() got an unexpected keyword argument 'min_value' Does anyone know how to deal with it? -
How to override autocomplete_fields style in Django 2.0?
I use autocomplete_fields to search and select my many to many items in admin view. Using this widget I am unable to override size of box. Instead with other simple fields (textbox, textarea, etc) I can specify style in my forms.py page in this way: forms.py class ModelBAdminForm(forms.ModelForm): class Meta: model = ModelB fields = ['name', 'description', 'm2m_fields'] widgets = { "name": forms.TextInput(attrs={'min-width': '400px'}), "description": forms.Textarea(attrs={'cols': '20'}), "m2m_fields": forms.SelectMultiple(attrs={'min-width': '400px'}) } admin.py @admin.register(ModelB) class ModelBAdmin(admin.ModelAdmin): list_display = ('name', 'description') search_fields = ('name', 'description') date_hierarchy = 'created_at' autocomplete_fields = ('m2m_fields',) form = forms.ModelBAdminForm Analyzing the html I saw the combobox uses a "select2" class. How can I increase min-width of the MultiSelect box? -
Incorrect datetime format in Django
I have a django project in which one of my models has a dateField named start_time. In my views.py I created a DetailView, and try to retrieve the timestamp like: s = self.object.start_time.strftime('%d-%b-%Y') On my Raspberry Pi, it gives the expected result. print(s) 22-Nov-2018 However on my Ubuntu 18 computer it gives: print(s) 22-nov.-2018 How can I get my Ubuntu machine to give the same (expected) result as the Raspberry Pi? They both run Django 2.1.3. -
customizing serialized object in django
i have a response for an api, "mailinglist": [ { "id": 690, "name": "Donotdelete", "count": "3", "mailing_list": 109, "person": [ { "id": 939, "first_name": "Aladdin", "last_name": "Abdul", "email": "aladdin@sharklasers.com", "mailinglist_id": 109 } ] }, { "id": 691, "name": "Donotdelete", "count": "3", "mailing_list": 109, "person": [ { "id": 938, "first_name": "smitha", "last_name": "sraj", "email": "smithasraj.kp@gmail.com", "mailinglist_id": 109 } ] } ] using nested serializer method.but i have to change this response to "mailinglist": [ { "id": 690, "name": "Donotdelete", "count": "3", "mailing_list": 109, "person": [ { "id": 938, "first_name": "smitha", "last_name": "sraj", "email": "smithasraj.kp@gmail.com", "mailinglist_id": 109 } ] } ] the common fields like name count mailing list should be outside the array.Is there any option to do this? Can we iterate the serializer data object and can be customize it? -
Django testing kwarg input to form.save()
In Django testing, form.save gets a kwarg. How can I test this? def save(self, **kwargs): user = super(UserCreationForm, self).save(commit=False) user.email = kwargs.pop('email') user.set_password(self.cleaned_data['password1']) user.save() return user -
Passing value from one field to other field in django form
I have two django models ModelA and ModelB. class ModelA(models.Model): fieldA1 = models.CharField() fieldA2 = models.CharField() fieldA3 = models.ManyToManyField('ModelC') class ModelB(models.Model): key = models.CharField() value = models.CharField() and a django form: class MyForm(forms.ModelForm): A_fields =[field.name for field in ModelA._meta.get_fields()] key= forms.ChoiceField(label='Key',choices = [(str(l),str(l)) for l in A_fields]) value= forms.MultipleChoiceField(label='Value',choices = 'Need Help here'). 'I have used MultipleChoiceField because if key == fieldA3 then there could be multiple choices for this field.' class Meta: model = ModelB fields = ('key', 'value') Since choices for 'key' field are the field names of ModelA. I want that based on the key selected (which will be some field name of ModelA), choices shown for the 'value' field in MyForm must be all the values stored in that particular field of ModelA. I know how to fetch values stored in a particular field of ModelA.I have to use the following command. field_values = ModelA.objects.values('Field for which i want values') How do i approach this problem? Thanks in advance. -
Django Rest Framework validate method not working
This is my first task that I'm doing in Rest Framework.I referred a video tutorial to do this and it's weird why my validate method in serializer not working even if I totally copied the code from the video. Below is my view function: class UserLoginAPIView(APIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data return Response(new_data, status=HTTP_200_OK) //I'm getting this response return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) and my serializer: def validate(self, data): print("***************validating*******************") //This line is not being printed # user_obj = None email = data.get("email", None) username = data.get("username", None) password = data["password"] if not email and not username: raise ValidationError("A username or email is required to login.") user = User.objects.filter( Q(email=email) | Q(username=username) ).distinct() user = user.exclude(email__isnull=True).exclude(email__iexact='') print(user, "-------------*********************") if user.exists() and user.count() == 1: user_obj = user.first() else: raise ValidationError("This username/email is not valid.") if user_obj: if not user_obj.check_password(password): print("wrong pwd", "**************************************") raise ValidationError("Incorrect credentials! Please Try again!") data["token"] = "SOME RANDOM TOKEN" return data As the first line in validate method not being executed, how am I getting the response(200_OK)? Please help me with this..