Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can not update the profile photo in Django
I'm developing a social network. In this social network there is how to update the profile photo, such as Facebook, for example. But when the user updates their photo, it is not shown in the frontend. user_tags_extras.py: def user_photo(context, user): try: if user.image == None or user.image == "": return static("icon/user.png") else: return "data:image/png;base64, " + user.image except: return static("icon/user.png") Models.py: class User(PermissionsMixin, AbstractBaseUser): name = models.CharField(max_length=200, verbose_name='Name', null=True) email = models.EmailField(max_length=256, unique=True, verbose_name=_('e-mail'), blank=True, null=True) image = models.TextField(verbose_name=u'Profile Photo', default='') HTML: <img alt="author" src="{% user_photo request.user %}" class="avatar avatar_template_base"> -
Django adding record to manytomany field
I have a problem with creating new record and adding it to the manytomanyfield. With code that I have I can add new Service. And it is working fine. Question is how to pass argument Car_id and to add new Service to services. My models.py: class Service(models.Model): mileage_number = models.DecimalField(max_digits=8, decimal_places=0) cash_float = models.DecimalField(max_digits=6, decimal_places=2) note_text = models.CharField(max_length=256, null=True) title_text = models.CharField(max_length=32) created_date = models.DateField(default=timezone.now) def __str__(self): return f"{self.title_text}" class Car(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) mark_text = models.CharField(max_length=32, null=False, default='mark') model_text = models.CharField(max_length=32, null=False, default='model') services = models.ManyToManyField(Service) refueling = models.ManyToManyField(Fueling) def __str__(self): return f"{self.mark_text} {self.model_text}" My urls.py: path("", views.index, name='index'), path('register', views.register, name='register'), path('logout/', views.LogoutView.as_view(), name='logout'), path('car/<int:Car_id>/', views.CarView, name="car"), path('car/<int:Car_id>/serv/<int:Service_id>/', views.ServiceView, name="service"), path('car/<int:Car_id>/fuel/<int:Fuel_id>/', views.FuelView, name="fuel"), path('add_car/', views.CarEntry.as_view(), name="add_car"), path('car/<int:Car_id>/add_service', views.ServiceEntry.as_view(C_id='Car_id'), name="add_service"), My html: <div class="mx-auto" style="width: 300px;"> <form method="post" class="form" > {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit" class="btn btn-primary" style="width: 300px;"> Submit </button> {% endbuttons %} </form> My views.py class ServiceEntry(CreateView): model = Service success_url = "/" template_name = "Site/add_service.html" fields = [ 'mileage_number', 'cash_float', 'note_text', 'title_text', 'created_date', ] enter code here -
django rest framework serializer skip relation table
My models are Purchase, Item, ItemGroup, Store These are the relevant fields of the models: class Store(models.Model): name = models.CharField(max_length=100) class ItemGroup(models.Model): name = models.CharField(max_length=100) store = models.ForeignKey(Store) class Item(models.Model): name = models.CharField(max_length=100) group = models.ForeignKey(ItemGroup) class Purchase(models.Model): item = models.ForeignKey(Item) date = models.DateTimeField() I want to write a serializer for Purchase. For each purchase, I want the following output: {"item": "item_name", "store": "store_name"} (Also there are some additional Purcahse fields, but these are easy to fetch). I've tried to follow the relations using the django double underscore __ style, but this does not work: class PurchaseSerializer(serializers.ModelSerializer): class Meta: model = Purchase fields = ('item', 'item__group__store') -
django error: invalid literal for int() with base 10: b'01/12/1990'
I have created a Profile and Blog model in my django application. here is the models.py file below: from django.db import models # Create your models here. class Profile(models.Model): name = models.CharField(max_length=30) description = models.TextField() number = models.CharField(max_length=10) dob = models.DateField() #error might be occuring here def __str__(self): return '%s %s' % (self.name, self.number) class Blog(models.Model): title = models.CharField(max_length=30) content = models.TextField() blog_document = models.FileField(upload_to='documents/', null=True, blank=True) def __str__(self): return self.title And in my admin panel, for profile model: I want to view two or more columns in the table, something like this: However this line is giving me the error since I do not know how to present more than one column appear in the Profile table: def __str__(self): return '%s %s' % (self.name, self.number) Please help! what would be the correct solution for implementing two or more fields in the Profile table(admin panel). Thanks in advance! -
Python package for listing zip-code and its details (country-wise)
Is there a python package that gives the list of all zip-codes and its city in country-wise. I tried with zipcodes package but it return results only from US,i need all countries codes and its details. -
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?