Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: expected string or bytes-like object while trying to set DateTimeObject
I have defined a Model Field as: SomeModel(models.Model) some_date = models.DateTimeField(default=timezone.now) Now when i am trying to save the model providing a date to some_date it gives error expected string or bytes-like object @ /django/utils/dateparse.py in parse_datetime, line 106 test_date = timezone.now() SomeModel(somedate = testdate) # SomeModel.save() it says expected string or bytes-like object where as test_date = datetime.datetime(2019, 11, 20, 20, 9, 26, 423063, tzinfo=pytz.timezone("America/New_York") SomeModel(somedate = testdate) SomeModel.save() works -
Django and Angular POST credentials were not provided
error when i try to login to my proyect, im using postman for test the login and send me error "detail": "Authentication credentials were not provided." my url.py urlpatterns = [ url(r'^api-login-user$', views.LoginUserView.as_view()), url(r'^', TemplateView.as_view(template_name='angular/index.html')), url(r'^', include(router.urls)), url(r'^auth/', ObtainAuthToken.as_view()), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] my view.py class LoginUserView(APIView): def post(self, request, *args, **kwargs): username = request.data.get('username') password = request.data.get('password') user = authenticate(username=username, password=password) if user: payload = jwt_payload_handler(user) token = { 'token': jwt.encode(payload, SECRET_KEY), 'status': 'success' } return Response(token) else: return Response( {'error': 'Invalid credentials', 'status': 'failed'}, ) my settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.IsAdminUser' ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', } -
Is there a way to pass a variable "through" the allauth process?
I have a website that requires a account creation for two different kinds of users. Users will create an account by one path, and admins will create an account by another pass. I am using django-allauth for my authorization process. I am looking for a way to pass an "?admin=true" parameter through the process so that I can write it into the user record. Is there an easy way to do this, like a setting? I am still getting my feet wet with django. When I open the allauth code, I feel like it is on a different level. Do I just need to suck it up and pass a parameter from "accounts/signup" to the authorization email to the email authorization page? Or is there a way to pass supplemental infomation through? -
Django 2: where to add urlencode to correctly parse plus signs
I get a q variable as follows: q = self.request.GET.get('q') However if the value of the parameter value passed has a + sign this is lost. How/where do I encode the URL to convert, for example, + signs to %2B? -
How to modify the Login view in inherited class in django?
I want to handle "confirm form resubmission" pop ups, when the user refresh the login page with incorrect data. I'm using a class named: UserLogin inherited from LoginView('django built-in'), I know that I need to write a method in my own class to handle this issue, and I did it with HttpRespone for my Registration view. who can I solve it for my Login View? -
I can't connect MySQL version 8 to Django 2.2 project
I have tried pretty much everything, including scouring StackOverflow to solve this issue yet I still seem to be faced with the problem. I am trying to connect my Django 2.2.6 project to my MySQL version 8 database with zero luck. I have changed the settings.py file to contain the following key value pairs in the databases dictionary: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'portfoliodb', 'USER': 'c**********s', 'PASSWORD': 'XXX', 'HOST': 'localhost', 'PORT': '3306', } } typing python manage.py runserver returns the following error: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? I do in fact have mysqlclient, typing pip install mysqlclient returns the following: requirement already met (1.4.4) I have also tried pip install pymysql And then edited the init.py file to have the following code: import pymysql pymysql.install_as_MySQLdb() Whilst keeping my databases variable the same as above. Doing this produces the following error: django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3. I have the MySQL python connector downloaded and installed onto my system. I have tried giving the empty ALLOWED_HOSTS variable within settings.py an argument of my localhost. The MySQL server is running fine outside of Django and can be accessed on the terminal … -
How can I change the style of marker with Leaflet/Javascript
I have a jquery function that retrieves GeoJSON data from a webpage (created using a GeoDjango server. I want to be able to change the style/color of the marker that it adds. However, when I use the below code, it still shows the standard blue colored marker. New to javascript and leaflet so I'm probably doing something stupid. Eventually, I want to be able to change the style/color based on if the station begins with a "A" or "B" as seen in the geoJSON file below. index.html <!DOCTYPE html> <html> {% load static %} {% load leaflet_tags %} <head> <title>stations</title> {% leaflet_js %} {% leaflet_css %} <script src="{% static 'dist/leaflet.ajax.min.js' %}"></script> <script src="{% static 'dist/leaflet.ajax.js' %}" ></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> </head> <body> <div id="stations" style="height: 450px; width: 100%;"></div> <!--Sets size of map--> <!--{% leaflet_map "cnlnet" %}--> <script> var map = L.map('stations', { center: [42.4444, -76.5019], zoom: 9.5, }); <!--Added OSM base layer below--> var osm = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 20, attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>' }); osm.addTo(map); var stationsUrl = 'stations.data'; $.getJSON(stationsUrl, function (data) { points = L.geoJson(data, { style: function(feature, latlng){ return L.marker(latlng, { icon: L.icon({ iconUrl: "static/img/red.png", iconSize: [28,32], iconAnchor: [12,28], popupAnchor: [0,-25] }) }); } }).addTo(map); }); </script> {% … -
Referencing multiple Django projects from a single monorepo
I want to be able to write shared functions that can be accessed in one-off batch scripts and also by the running Django service (to use the ORM) Currently, I have this in the _init__.py under the my_proj module. if 'DJANGO_SETTINGS_MODULE' not in os.environ: os.environ['DJANGO_SETTINGS_MODULE'] = 'my_proj.blah.blah.settings' import django django.setup() This works fine for one project. However, now I want to do reference the ORM functions from another project, "other_proj". Is there a way to "django.setup()" multiple projects at once? Or, at least, a way to easily toggle the setup between the two projects? Or is there a better way altogether? (I realize I could create a client library to hit the services while they are running, but would prefer to remove that overhead) -
How to represent mpld3 plot(s) in other html file
I am making a plot based on excel-data which is working fine butI'm having problems with the representation of the plot that is made. Currently I'm showing the plot with mpld3.show() import matplotlib.pyplot as plt, mpld3 def speedPlotter(df): ax = plt.gca() df.plot(kind='line',x='time',y='Speed',ax=ax) df.plot(kind='line',x='time',y='Speed1', color='red', ax=ax) df.plot(kind='line',x='time',y='Speed3', color='blue', ax=ax) df.plot(kind='line',x='time',y='Speed5', color='yellow', ax=ax) df.plot(kind='line',x='time',y='Speed7', color='orange', ax=ax) mpld3.show() It plots the dataframe as follows: Now it shows the plot in an ugly plain html page. I want to extend an existing base.html with the plot that has been made but I'm unsure how I should approach it. Is mpld3.fig_to_html(figure) what I should be looking for? -
Access Django model name from admin url pattern
Given an url like: http://127.0.0.1:8000/admin/foo/ How can I access the foo variable from the request, using the request.resolver_match.kwargs ? What kwarg does the admin give too foo? Tried different keys like class, content_type, slug, model, but none of them work. -
Why does ugettext_lazy in rest_auth return a strange value?
I tried to response using ugettext_lazy with this code. return Response({"detail": _("New password has been saved.")}) And the response value I expected is {"detail": "New password has been saved." But the actual return value is { "detail": [ "N", "e", "w", " ", "p", "a", "s", "s", "w", "o", "r", "d", " ", "h", "a", "s", " ", "b", "e", "e", "n", " ", "s", "a", "v", "e", "d", "." ] } Why are all characters returned separated value and wrapped in a list? -
Django nullable ForeignKey causes ProgrammingError
This problem is driving me nuts - I can't spot what's going on so I was hoping that someone would be able to point out what I'm missing here. I've got two sample models, FootballClub, FootballPitch, as defined below. class FootballClub(models.Model) name = models.CharField(max_length=100) class Meta: ordering = ['name'] def __unicode__(self): return self.name class FootballPitch(models.Model): name = models.CharField(max_length=100) owning_club = models.ForeignKey(FootballClub) I've made a modification to the FootballPitch class, more specifically the owning_club field, to add null=True to it, so the class now looks like this; class FootballPitch(models.Model): name = models.CharField(max_length=100) owning_club = models.ForeignKey(FootballClub, null=True) (I don't need to manage this model through a form so I don't care that blank=True is not set). I have also run makemigrations and migrate on this model. When trying to list out all instances of FootballPitch that have owning_club set to null (using FootballPitch.objects.filter(owning_club__isnull=True)) I get the following error; Programming Error: relation "footballclub_footballpitch" does not exist LINE 1: ...d", "footballclub_footballpitch"."name",FROM "footballclub_f... Anyone have any ideas what is going wrong? (Django 1.8.18 and Python 2.7 and postgres 9.8 for reference) Thanks in advance! -
login not showing on the browser view of the API
I have successfully created database, serialisers, views to use the API with my FE application. Now I needed to restrict access to all endpoints to only logged in users. I am use simple JWT library on Django to manage tokens. As a consequence, I cannot simply check data with postman or the PI in the browser view without using token with every single request. This would be fine, but in the browser view I cannot see now any login link (top right corner), hence I simply cannot use it any longer. But this link should be there. What controls the appearance. Help would be greatly appreciated -
I want to manage errors I receive in django forms on html page the way I want
have created a from with some validations. I want to display an error on HTML properly, eg. If I am receiving an error for the password field I want to display it in front of that field. I am sharing my code as well as a screenshot of the page after I receive an error on the form. In short I want to manage the form errors on HTML the way I want. forms.py class UsersForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput,validators=[validators.MinLengthValidator(8),]) password_1 = forms.CharField(widget=forms.PasswordInput,label='Confirm Password') class Meta: model = Users fields = ('username','first_name','last_name','date_of_birth') labels = { 'date_of_birth': ('D.O.B'), } widgets = { 'date_of_birth': DateInput(attrs={'type': 'date'}) } views.py def create_user(request): if request.method == 'POST': form = UsersForm(request.POST) u = User.objects.get(username=request.user.get_username()) if request.POST.get('password') != request.POST.get('password_1'): messages.error(request,'password mismatch, try again') return render(request,'login.html',{'form':form}) elif form.is_valid(): cUser = Users.objects.create(username=form.cleaned_data['username'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], password=make_password(form.cleaned_data['password']), date_of_birth=form.cleaned_data['date_of_birth'], created_by= u,) cUser.save() else: return render(request,'login.html',{'form':form}) form = UsersForm() context = {"form":form} return render(request,'login.html',context) login.html <!DOCTYPE html> <html> <body> <pre><center> <h1>User Creation Form</h1> <form action = '' method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" name="register"> <h3> {% for message in messages %} {{ message }} {% endfor %} </h3> </form> </center></pre> </body> </html> -
Save unzipped file (folder) in model from local folder
I am creating a website in which the user uploaded a zip file. This zip file is the unzipped, saved inside my project folder. Then I want to retrieve these files and saved it into my Model. I managed to unzip the file in a folder inside my DJango project but now I do not know how to pass them into my views so that they can be saved in the Models. views.py def homeupload(request): if request.method == "POST": my_entity = Uploading() my_zip_file = request.FILES["my_uploads"] with zipfile.ZipFile(my_zip_file, 'r') as zip_ref: zip_ref.extractall('media/documents/') my_entity.my_uploads = "RETRIEVE THE UNZIPPED FILE FOLDER FROM media/documents/" my_entity.save() messages.success(request, "File uploaded correctly") return redirect('homeupload') return render(request, 'uploadings/homeupload.html') models.py class Uploading(models.Model): my_uploads = models.FileField(upload_to="documents/") -
How to set the range of the primary-key of django objects based on the foreign key range and is it advisable?
I have the below models: class Author(model): name = CharField(...) class Post(mode): author = ForeignKey(Author) title = CharField(...) Suppose we have at most 100 authors. So the primary key of the autors would be in the range of 1 to 100 I want the primary keys of the post model be based on the primary key of the author of the post. I mean, if the author's primary key is 34, then his/her posts primary keys be 34000001, 34000002, 34000003 is advisable to do this and how can I do it? -
Classification using a django app creating 'UnicodeDecodeError' error
I am getting a csv file as an input from the user and then loading a saved pickle file to perform classification. But i am getting errors like: UnicodeDecodeError at /home_/Link5/classification/ 'charmap' codec can't decode byte 0x81 in position 47: character maps to < undefined > Template file(Link5.html): <h3>Upload your file here for classification</h3> <form method="post" action="{% url 'classification' %}" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="file" accept=".csv"> <button type="submit">Upload File</button> </form> views.py: from django.shortcuts import render from django.shortcuts import HttpResponse import numpy as np import pandas as pd import pickle import os from sklearn.preprocessing import StandardScaler from sklearn.metrics import confusion_matrix def classification(request): if request.method == 'POST': file = request.FILES['file'] dataset=pd.read_csv(file) x=dataset.iloc[:,[2,3]].values y=dataset.iloc[:,4].values sc=StandardScaler() x=sc.fit_transform(x) #decision_tree_model_pkl = open('decision_tree_classifier.pkl', 'rb') decision_tree_model_pkl=open(os.path.dirname(os.path.realpath(__file__)) + 'decision_tree_classifier.pkl', "r") decision_tree_model = pickle.load(decision_tree_model_pkl) y_pred = decision_tree_model.predict(x) cm=confusion_matrix(y,y_pred) ans='<H1>TP=%d <br> TN=%d<br> FN=%d<br> FP=%d</H1>' % (cm[0][0],cm[1][1],cm[0][1],cm[1][0]) return HttpResponse(ans) return HttpResponse('') urls.py: from django.urls import path from Link5 import views urlpatterns = [ path('', views.Link5, name='Link5'), path('classification/', views.classification, name='classification'), ] -
How to change admin detail view?
I have a question about Django-Admin Detail View. I have some items in admin Django, and when I click on them, it will show up detail of that specific item. Every item has some status, which could be changed by the user. And now I am getting to the problem... I want to show only relevant fields, buttons, etc. which will depend on item status or type of person. Which part of code will I put in admin.py under the specific class to make it work? I tried something like this for superuser but it will not work. Can you please show me how to display only some fields based on user status or item status(field name: Status ... in models) class JournalEntriesAdmin(admin.ModelAdmin): list_display = ('EngagementCode', 'EngagementManager', 'EngagementIncharge') list_filter = ('published', 'EngagementCode') search_fields = ('EngagementCode', 'EngagementManager', 'EngagementIncharge') def show_relevant(self, obj): if request.user.is_superuser: fieldsets = ( (None, { # label 1: None 'fields': ( # dictionary ('EngagementCode', 'EngagementManager'), ) }), ('More details', { # under label 2 : More details 'classes': ('collapse',), # css-class : minimized 'fields': ( ('published'), ) }) ) -
TypeError: __str__ returned non-string (type NoneType) in django template
I am working on django models and templates. while rendering the html, got following error. Please any one, is this error from models or django templates. File "/dj2.1/lib/python3.6/site-packages/django/template/base.py", line 978, in render_value_in_context value = str(value) TypeError: __str__ returned non-string (type NoneType) -
Django: How to populate ForiegnKey field with a related name?
I have two models one BookModel and another AuthorModel. I basically want to create a foreign key field to BookModel for referencing it to the AuthorModel. And I have been able to establish this successfully. But when I retrieve an object/record of the BookModel I get the author id instead of the whole author object. How do I do that? Here's what I've in my code In models.py: class AuthorModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField('Name', max_length=255) pen_name = models.CharField('Pen Name', max_length=255) class BookModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField('Book Name', max_length=255) author = models.ForeignKey(Author, on_delete=models.CASCADE, blank=True, default='', related_name='book_authorid') In serializers.py: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('id', 'name', 'pen_name') class BookSerializer(serializers.ModelSerializer): author = AuthorSerializer() class Meta: model = Book fields = ('id', 'name', 'author') -
Error: 'django.contrib.sites.models.Site.settings.RelatedObjectDoesNotExist: Site has no settings.'
On running python manage.py runserver I get no errors. System check identified no issues (0 silenced). October 09, 2019 - 07:58:46 Django version 2.2.4, using settings 'saleor.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. But when homepage is loaded I get this RelatedObjectDoesNotExist Error django.contrib.sites.models.Site.settings.RelatedObjectDoesNotExist: Site has no settings. Can you help direct me here or even just spotlight on anything that I might be missing? What I have already tried - Flushing the database - Dropping the database, creating database again, making and running migrations again. -
Django: Parameters in URLs .... which start with a slash
I use a regex for URL dispatching like described in the Django docs. r'^remote/(?P<slug>[^/]+)/call_rfc/(?P<rfc_name>.+)$' Unfortunately rfc_name can start with a slash! Example: https://example.com/remote/my_slug/call_rfc//MLK/FOO The rfc_name is /MLK/FOO. But this fails. Somewhere (I don't know yet if it is in the browser or in Django) the duplicate slash gets removed. What is the best practice to handle URL parameters which can start with a slash? -
Is is bad to implement NodeJS on the backend and use Node Child Process to run python? project: Algorithmic trader. Should I use just Django?
I am highly experienced with NodeJS, but not Python or Django. I want to manipulate API's in JS, but do all computational tasks in Python. Is this a good way to go about it, or should I take the time to learn django, and utilize that as my full-stack framework. -
Column is not being added to table Mysql using Django
The following diagram is from my database Database schema I have the following model that represents that schema: class Finalproduct (models.Model): idfinalproduct = models.AutoField(primary_key=True) idproduct = models.ForeignKey('Product',on_delete=models.CASCADE) idtaste= models.ForeignKey('Taste', on_delete=models.CASCADE) idpresentation = models.ForeignKey('Presentation', on_delete=models.CASCADE) idcategory = models.ForeignKey('Category', on_delete=models.CASCADE) cantidad = models.IntegerField(), class Meta: unique_together = (("idproduct","idtaste","idpresentation","idcategory"),) The cantidad field is not being added in my database table finalproduct. The following is the result of the migration in MySql: Mysql, table generated with model shown above I have tried deleting my database, migrations, and the problem is never solved. -
Django: send email via Office365
What I have: A domain purchased in webs.com (I'll call it contoso.com); An Office 365 account connected to that domain (my email address is something like john@contoso.com); A Django application hosted in Azure; What I want: I would like to configure Django in order to send emails using my john@contoso.com address. What I'v done: I tried this Django configuration: EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.office365.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'john@contoso.com' EMAIL_HOST_PASSWORD = 'xxxxxx' but it didn't work. So, just for a test, I tried the free Google SMTP server: EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'john@gmail.com' EMAIL_HOST_PASSWORD = 'yyyyyy' This time it works but, obviously, the email is sent from john@gmail.com and not from john@contoso.com. What's wrong in the previous configuration? Or maybe I need to make some changes in my Office 365 account?