Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: unable to create Generic Foreign key object
I'm using Django 2.x I have two models class DynamicUrlObject(models.Model): content_type = models.ForeignKey(ContentType, null=True, on_delete=models.SET_NULL) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') domain = models.CharField(max_length=255) and class MyModel(models.Model): name = models.Char(max_length=50) my_obj = fields.GenericRelation(DynamicUrlObject, related_query_name='my_obj') I have an object of MyModel and want to create a record for DynamicUrlObject and link same to the MyModel model. I'm doing it something like dy_obj = DynamicUrlObject.objects.get_or_create( content_object=my_existing_obj, domain='http://example.com' ) my_existing_obj.my_obj = dy_obj my_existing_obj.save() But this is not creating a record for DynamicUrlObject and gives an error as django.core.exceptions.FieldError: Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. -
In my django admin change_list, there are names with diacritics. How to order them properly?
I'm using it with Python 3.6.5. In my Django 2.1 app, I have a model object like this: class Person(models.Model): name = models.CharField(max_length=64) with some names presenting diacritics. In my admin.py, I have: from django.contrib import admin from .models import Person class PersonAdmin(admin.ModelAdmin): ordering = ['name'] admin.site.register(Person, PersonAdmin) So, this is the default order I got when accessing my change_list admin view: Joseph Josué José Éderson but I need them to show up in this order: Éderson Joseph José Josué Also, I have a sort key to do this trick when I have a list: import locale def sort_key_BR(): locale.setlocale(locale.LC_ALL, "pt_BR.UTF-8") return locale.strxfrm names = ['Joseph', 'Josué', 'José', 'Éderson'] names.sort(key=sort_key_BR()) for n in names: print(n) # Éderson Joseph José Josué Worth to mention, in my project's settings.py, I already have: LANGUAGE_CODE = 'pt-BR' What is the proper way to inform a sort key rather than the default to ordering in Django models? Rather what is a proper way of doing this? -
Simple way to make a file available to user for download
I have a template xls file in the media folder. I want that the user can easily download this file from the page. What is a simple way of doing this? I could not find any simple reliable way of doing this. Sorry, I'm new to Django. My urls.py: urlpatterns = [ ... ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) template: ... <a href="#">Download Template</a> -
PostGIS OSM import: the number of features is -1
Disclaimer: it's too specific: anybody can reproduce this with a blank Django project which used gdal, and a download of a file here. I'm using Gdal for Django to check what's inside an OSM file. I've tried to download a dozens files from Geofabrik here. From all those files (osm and pbf) I'm using this small script to get some informations: from django.contrib.gis.gdal import DataSource ds = DataSource(r'C:\blabla\data\mayotte-latest.osm.pbf') for l in ds: print('name: "%s", geom_type.name: %s ' % (l.name, l.geom_type.name)) print(" fields: %s, field_widths: %s" % (l.fields, l.field_widths)) print(" l.num_feat: %s, l.extent: %s" % (l.num_feat, l.extent)) print(" l.field_widths: %s, l.field_precision: %s" % (l.field_widths, l.field_precisions)) print(" l.field_types: %s" % (l.field_types, )) for feat in l: print(feat.get('NAME'), feat.geom.num_points) else: print(" ... no points") And with all files (no exception), I get something very close to: name: "points", geom_type.name: Point fields: ['osm_id', 'name', 'barrier', 'highway', 'ref', 'address', 'is_in', 'place', 'man_made', 'other_tags'], field_widths: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] l.num_feat: -1, l.extent: (44.85604, -13.1491, 45.45754, -12.46832) l.field_widths: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], l.field_precision: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] l.field_types: [<class 'django.contrib.gis.gdal.field.OFTString'>, <class 'django.contrib.gis.gdal.field.OFTString'>, <class 'django.contrib.gis.gdal.field.OFTString'>, <class 'django.contrib.gis.gdal.field.OFTString'>, <class 'django.contrib.gis.gdal.field.OFTString'>, <class … -
How to get user in Django signals
How can you get the user who is saving record in django signals? I am using signals to fill in data when a user marks completed = True via a form. I was hoping something like instance.User or instance.CustomUser.username would work, but it just throws errors that these don't exist in Maintenance model. models.py from django.db import models from accounts.models import CustomUser from django.contrib.auth import get_user_model from django.urls import reverse from django.conf import settings from django.db.models.signals import post_save from django.utils.timezone import utc import datetime from django.utils import timezone class Maintenance(models.Model): device = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,) customerTag = models.CharField(max_length=50,) maintenanceItem = models.CharField(max_length=35,blank=True,) maintenanceDescrip = models.TextField(max_length=300,blank=True,) maintenanceNotes = models.TextField(max_length=300,blank=True,) dateCreated = models.DateTimeField(auto_now_add=True,) dateDue = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True, editable=True) dateCompleted = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True, editable=True) completed = models.BooleanField(default = False) createdBy = models.CharField(max_length=35,blank=True,) completedBy = models.CharField(max_length=35,blank=True,) def __str__(self): return str(self.maintenanceItem) def get_absolute_url(self): return reverse('equipmentdashboard',) def check_complete(sender, instance,**kwargs): hasCompleteDate = instance.dateCompleted if not (hasCompleteDate is None): return else: isComplete = instance.completed if isComplete == True: completed_By = ? Maintenance.objects.filter(id = instance.id).update(completed = True, dateCompleted = timezone.now(), completedBy = completed_By,) post_save.connect(check_complete, sender = Maintenance) -
Celery Redis instance filling up despite queue looking empty
We have a Django app that needs to fetch lots of data using Celery. There are 20 or so celery workers running every few minutes. We're running on Google Kubernetes Engine with a Redis queue using Cloud memorystore. The Redis instance we're using for celery is filling up, even when the queue is empty according to Flower. This results in the Redis DB eventually being full and Celery throwing errors. In Flower I see tasks coming in and out, and I have increased workers to the point where the queue is always empty now. If I run redis-cli --bigkeys I see: # Scanning the entire keyspace to find biggest keys as well as # average sizes per key type. You can use -i 0.1 to sleep 0.1 sec # per 100 SCAN commands (not usually needed). [00.00%] Biggest set found so far '_kombu.binding.my-queue-name-queue' with 1 members [00.00%] Biggest list found so far 'default' with 611 items [00.00%] Biggest list found so far 'my-other-queue-name-queue' with 44705 items [00.00%] Biggest set found so far '_kombu.binding.celery.pidbox' with 19 members [00.00%] Biggest list found so far 'my-queue-name-queue' with 727179 items [00.00%] Biggest set found so far '_kombu.binding.celeryev' with 22 members -------- summary ------- Sampled … -
Django-ORM - selecting the last record by date for each attribute
I have constructed the following query "chain": survey_results = OrganisationSurveyResult.objects.filter(user=user) survey_results = survey_results.filter( created_date__in=survey_results.values( 'user', 'organisation_survey' ).annotate( latest_created_date=Max('created_date') ).values( 'latest_created_date' ) ).annotate( module=F('organisation_survey__survey__module'), score=F('survey_result__normalized_score'), rank=F('survey_result__rank_class'), ).values( 'module', 'score', 'rank', 'created_date' ) Which returns the following entries when iterated: {'created_date': datetime.datetime(2019, 8, 14, 15, 10, 54, 214754, tzinfo=<UTC>), 'module': UUID('151cb049-65c5-4278-8133-610859be6f34'), 'score': 95, 'rank': 'Low'} {'created_date': datetime.datetime(2019, 8, 14, 15, 10, 54, 220694, tzinfo=<UTC>), 'module': UUID('7c5848eb-3090-4819-8eac-166367ab0e65'), 'score': 91, 'rank': 'Low'} {'created_date': datetime.datetime(2019, 8, 14, 15, 10, 54, 226334, tzinfo=<UTC>), 'module': UUID('b894c988-af3d-4ecb-a2a1-c42225b64b71'), 'score': 100, 'rank': 'Low'} {'created_date': datetime.datetime(2019, 8, 14, 15, 10, 54, 232898, tzinfo=<UTC>), 'module': UUID('22edce11-f78e-4b2e-a1de-1ecc7f0518c9'), 'score': 59, 'rank': 'Medium'} The request-response cycle for this API endpoint is 51-89ms. The DB query time is 24-38ms. It was originally 1280ms as I was using a prefetch_related method and looping. It's also passed all tests. It has four record entries for a single user (there are only four modules). Each date in the list of entries is also the last SurveyResult for that module and user. Happy so far. However, my next step is for each of the above entries in the list, I need to obtain the following: for survey_result in survey_results.iterator(): resource = Resource.objects.filter(module=survey_result['module'], rank_class=survey_result['rank']) So, I am adding an extra 4 … -
How to save model with foreign key
I am making Django scraping application where I want to keep scraped properties and rooms from bookingdotcom. Whilst scraping I need that the flat would be linked for a property which already exists in the DB. The thing is that I am novice with django and I am not sure how to save flat record which links to the property. def process_item(self, item, spider): if not item: spider.crawler.stats.inc_value('empty_item_parsed') raise DropItem("Dropping empty item") bdc_room = BDCRoom() #How to save it so it links to property, which already exists in the database. bdc_room.bdc_property = BDCProperty().pk bdc_room.name = item["flat_name"] bdc_room.created_datetime = item["date_time"] bdc_room.save() try: bdc_property = BDCProperty.objects.get(name=item["listing_name"]) print("Listing already exist") return item except BDCProperty.DoesNotExist: pass bdc_property = BDCProperty() bdc_property.name = item["listing_name"] bdc_property.created_datetime = item["date_time"] bdc_property.address = item["address"] bdc_property.rating = item["rating"] bdc_property.review_count = item["review_count"] bdc_property.available_rooms_count = item["availability_count"] bdc_property.save() return item -
How to remove SMTPAAuthenticationError caused by changing of EMAIL_HOST_USER?
How to show the logged in user email address whenever I send email to bilalkhangood6@gmail.com? Although every time it shows me another email address(bilalkhangood4@gmail.com) who is not logged in. I used user.request.email to send email from those user who is logged in. After changing EMAIL_HOST_USER, it gives me SMTPAuthenticationError at /ViewSendEmail/ (535, b'5.7.8 Username and Password not accepted settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_HOST_USER = 'bilalkhangood4@gmail.com' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 587 ACCOUNT_EMAIL_VERIFICATION = 'none' EMAIL_USE_SSL = False views.py from django.contrib.auth.models import User def ViewSendEmail(request): send_mail('Hello from Bilal Khan', 'Hello there, This is an automated message.', request.user.email, #FROM ['bilalkhangood6@gmail.com'], #TO fail_silently=False) return render(request, 'nextone/email_send.html') -
Nested Serializer not showing up
I am trying to update my serializers in my drf project to be shown in a nested way. The two models in question are Image and Gallery, images are related to Galleries. I tried following https://www.django-rest-framework.org/api-guide/relations/#nested-relationships, but i am not entirely sure why it is not working. Below is models.py class Gallery(models.Model): title = models.CharField(max_length=30) author = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True, blank=True) modified_on = models.DateTimeField(auto_now=True, blank=True) def __str__(self): return self.title class Image(models.Model): gallery_id = models.ForeignKey(Gallery, on_delete=models.CASCADE) img = models.ImageField(upload_to='images/') created_on = models.DateTimeField(auto_now_add=True, blank=True) serializers.py class ImageSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Image fields = ["gallery_id", "img", "created_on", "id"] class GallerySerializer(serializers.HyperlinkedModelSerializer): image = ImageSerializer(many=True, read_only=True) def validate(self, data): # Check if user id is equal object id before creation or if SuperUser request = self.context.get("request") if request.user.id != data["author"].id and request.user.is_superuser is not True: raise ValidationError("Unauthorized User Post") return data class Meta: model = Gallery fields = ["title", "author", "created_on", "modified_on", "image", "id"] Expecting outcome would be [ { "title": "test_1", "author": "http://127.0.0.1:8000/api/users/2/", "created_on": "2019-08-19T09:13:45.107658Z", "modified_on": "2019-08-19T09:13:45.107731Z", "image": [ { "gallery_id": "http://127.0.0.1:8000/api/galleries/24/", "img": "http://127.0.0.1:8000/media/images/angga-tantama-background-art-minimalism.jpg", "created_on": "2019-08-20T09:17:31.790901Z", "id": 6 }, { "gallery_id": "http://127.0.0.1:8000/api/galleries/24/", "img": "http://127.0.0.1:8000/media/images/art-vector-background-illustration-minimalism-angga-tantam-2.jpg", "created_on": "2019-08-20T09:31:40.505035Z", "id": 7 } ] "id": 24 }, { "title": "test_2", "author": "http://127.0.0.1:8000/api/users/2/", "created_on": "2019-08-20T09:42:09.448974Z", "modified_on": … -
Inserting a record into a table's ManyToMany field while using multiple databases
My project uses Django's builtin multi-database support and I am trying to synchronize data in 2 different databases by taking a record from one database and inserting it into another one. I have tried to do this in the usual way using the add method of the RelatedManager, but it did not work and did not insert the record in the intermediary table in the second db, but rather did that in the default db. Here is how I did that: I have a Person model which has a ManyToMany field to Dbs model: ... class Person(models.Model): ... tenant_dbs = models.ManyToManyField(to=Dbs, blank=True) and Dbs model which contains a single column with the names of the databases a person can have access to: ... class Dbs(models.Model): person_id = models.CharField(primary_key=True, max_length=20 ) So I want to get some Person, Dbs and intermediary records from the default database and copy them all to another database (let's assume its name is 'secondary'). So I do the following: from core.models import Person from .models import Dbs # here I take the objects from default db as I did not mention any other # db manually and save them in the 'secondary' db. This works fine … -
Django, long filter query
I cant understand why it works like this, for example: Query1 Q( Q(groups__name=CONST_DEALER) & Q(additional_info__address__district=address.district) ) lead time: 2sec Query2 Q(Q(Q(groups__name=CONST_SELLER) | Q(groups__name=CONST_GROWER)) & Q(minor_user__major__additional_info__address__district=address.district) ) lead time: 2sec but when I unites them(i need to unites them) Q( Q( Q(groups__name=CONST_DEALER) & Q(additional_info__address__district=address.district) ) | Q( Q(Q(groups__name=CONST_SELLER) | Q(groups__name=CONST_GROWER)) & Q(minor_user__major__additional_info__address__district=address.district) ) ) lead time: 80sec!!!!!! tell me how to make a quick request -
Slugify not saving title as slug Django 2: NoReverseMatch error
Can't seem to get the slug field to save because I am getting the error NoReverseMatch. Reverse for 'blog_detail' with arguments '(5, '')' not found. 1 pattern(s) tried: ['blogpost/(?P<pk>[0-9]+)/(?P<slug>[^/]+)$'] Could someone look over my code please as I am having trouble finding the problem? urls.py path('blogpost/<int:pk>/<str:slug>', news_views.BlogPostDetailView.as_view(), name='blog_detail'), models.py class BlogPost(models.Model): title = models.CharField(max_length=190, null=True) slug = models.SlugField(max_length=190, editable=False, unique=True, blank=True, default='') def save(self, *args, **kwargs): self.slug = slugify(self.title, allow_unicode=True) super().save(*args, **kwargs) def get_absolute_url(self): kwargs = { 'pk': self.pk, 'slug': self.slug, } return reverse('blog_detail', kwargs=kwargs) views.py class BlogPostDetailView(DetailView): context = { 'blog': BlogPost.objects.all(), } model = BlogPost template_name = 'blog/blog_detail.html' slug_field = 'slug' slug_url_kwarg = 'slug' homepage.html <a href="{% url 'blog_detail' blog.pk blog.slug %}">{{ blog.title }}</a> -
How to filter against URL with foreign key field in Django REST, overwriting get_queryset method correctly
I am trying to filter my queryset against an url with django REST but can't really get it to work. I want to pass a string in the URL (a project name). According to this string, which is a foreign key, I want to filter my queryset (BuildingGroup). I don't want to use query params but a url filter. I followed the docs but there is not so much on it on the site. This is what I am trying: class ListBuildingGroupProject(ListAPIView): serializer_class = BuildingGroupSerializer filter_fields = 'project' def get_queryset(self): project = self.kwargs['project'] building_groups = BuildingGroup.objects.filter(project=project) result = building_groups.order_by('-creation_date') return result The line building_groups = BuildingGroup.objects.filter(project=project) throws me a KeyError for project. Here are my models. Note that BuildingGroup has one Project. A project can belong to many BuildingGroups. class BuildingGroup(models.Model): description = models.CharField(max_length=500, null=True, blank=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) creation_date = models.DateTimeField(auto_now=False) class Project(models.Model): project_name = models.CharField(max_length=120, primary_key=True, unique=True) start_date = models.DateTimeField(auto_now=False, null=True, blank=True) end_date = models.DateTimeField(auto_now=False, null=True, blank=True) and here my URL: path('project/<str:project_name>', ListBuildingGroupProject.as_view(), name='building-group-project'), Help is so much appreciated! Thanks in advance! -
Is there a way to override the content of notification email from a test case update in Kiwi TCMS?
Im trying to change the content of the notification email sent after a test case has been updated to better clarify what has been changed. As it is, the content is hard to read. Went through the link below to configure the other notification content: http://kiwitcms.org/blog/atodorov/2018/08/06/how-to-override-templates-for-kiwi-tcms/ The content of the notification email: Updated on Tue Aug 20 15:47:18 2019 Updated by Admin --- notes +++ notes @@ -1 +1 @@ -TestTest +TestTest123123 --- text +++ text @@ -10,7 +10,7 @@ 3. item *Expected results*: - +Test 1. item 2. item 3. item I managed to replicate the example (from the link) for post_case_delete, post_run_save, and user_registered but the dir(tcms/templates/email/) lacks one for test case updates. Is there a way to amend how the content is shown in the notification email? -
Dojo: all xhr / ajax calls seem to be synchronous and block other calls
I am working on a CRM we inherited. Long story short - there is a button that calls a php script which should run in background and we don't need to wait for response. request(idata+'transferInTimeExec.php',{ sync: false, preventCache:true, method:'GET' }); Now, the transferInTimeExec.php takes an hour to run, it's a very complex script that deals with weekly timesheets for a recruitment company, processes them, does a lot of DB operations etc. Using Chrome. Every time I press the button to run it, it blocks all the xhr calls until it finishes. CRM is "ajax heavy" and while the script is running, the user can't do anything, not even navigate away from that page. Even when I open a new browser tab and try to do something, it won't do it. If I open the CRM in another browser (Firefox) while the script is running, I can use the CRM. In Network tab - the first one is pending, and as you can see all the subsequential calls to a different Ajax call wait (all have sync:false) I even replaced the whole logic with PHP function sleep(30) to make it just do nothing for 30 seconds before returning anything - same … -
In django, how can I ensure that a specific user is accessing a view?
I would like to be able to check if the user accessing a page is a specific user. For instance, when a user accesses the "Edit Post" page on my blog app, I want to ensure that the user is the author of the post. Currently, I check that the user accessing '/Blog/Edit//' has the blog.change_post permission. However, if a second user (who also has that permission) were to enter the URL to change someone else's post, they would pass that permission check and be able to edit someone else's post. What I want is a @user_passes_test function that check's the user object accessing the view against the author attribute of the post. #/Blog/urls.py urlpatterns = [ ... path('Edit/<int:pk>', views.BlogEdit, name='BlogEdit'), ... ] #/Blog/views.py @permission_required('blog.change_post', login_url='/Portal/login') def BlogEdit(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('/Blog', pk=post.pk) else: form = PostForm(instance=post) return render(request, 'Blog/Edit.html', {'form': form}) -
MultipleObjectsReturned- get() returned more than one UserDetails -- it returned 10
For my project i am doing a resume parser. When i upload one resume, it was able to extract those data. When i upload more resume i get this error, i understand it does matter with get() or filter(). I have tried changed my user details user_detail = UserDetails.objects.get(user=user) from get() to filter(), although it resolve the multiple object error, but it having another issue is my result extract nothing, no result show at all. It means it doesn't extract any data from my resume although upload successful def homepage(request): if request.method == 'POST': user = User.objects.get(id=1) UserDetails.objects.filter(user=user).delete() Competencies.objects.filter(user=user).delete() MeasurableResults.objects.filter(user=user).delete() Resume.objects.filter(user=user).delete() ResumeDetails.objects.filter(resume__user=user).delete() file_form = UploadResumeModelForm(request.POST, request.FILES) files = request.FILES.getlist('resume') if file_form.is_valid(): for file in files: try: user = User.objects.get(id=1) # saving the file resume = Resume(user=user, resume=file) resume.save() # extracting resume entities parser = resume_parser.ResumeParser(os.path.join(settings.MEDIA_ROOT, resume.resume.name)) data = parser.get_extracted_data() # User Details # resume.name = data.get('name') # resume.email = data.get('email') # resume.education = get_education(data.get('education')) user_details = UserDetails() user_details.user = user user_details.name = data.get('name') user_details.email = data.get('email') user_details.mobile_number = data.get('mobile_number') user_details.skills = ', '.join(data.get('skills')) user_details.years_of_exp = data.get('total_experience') user_details.save() for comp in data.get('competencies'): competencies = Competencies() competencies.user = user competencies.competency = comp competencies.save() for mr in data.get('measurable_results'): measurable_results = MeasurableResults() measurable_results.user = … -
Understanding Django CSRF_COOKIE_SAMESITE and CSRF_TRUSTED_ORIGINS
Obviously I have a problem to understand the impact of Django (2.2.4) settings regarding CSRF parameters in a cross-domain environment. As I have already noticed I have to set SESSION_COOKIE_SAMESITE = None if I want to place my Django application into an iframe of a website with another domain (e.g. Django app on foo.com and iframe on bar.com) in order to send forms on my Django application. However what's about the CSRF parameters? After some trials I noticed that I can only send the Django form in the iframe if I also set CSRF_COOKIE_SAMESITE = Nonein the Django settings. But what is the CSRF_TRUSTED_ORIGINS for? If I set the iframe domain (e.g. bar.com) into the list ['bar.com'] instead of CSRF_COOKIE_SAMESITE = None I can not send the form on my Django app in the iframe. Could anybody explain in what case CSRF_TRUSTED_ORIGINS has any effect? Is it just usable in an environment with one domain and serveral subdomains? Thanks for any hint! -
Sort the elements of list contains salutation in it?
I have a list contains salutation in it. How can I sort the list on the basis of names in pythonic way? I have tried to split the elements of list on the basis of '.' character and sorted the names but could not get salutation with names. names = ["Mr.usman", Mrs.obama, "Mr.Albert"] sorted_list = sorted([i.split('.')[1] for i in names]) For e.g ["Mr.usman", Mrs.obama, "Mr.Albert"] should be like ["Mr.Albert", Mrs.obama, "Mr.usman"] -
Unable to import TokenObtainPairView,TokenRefreshView from JWT
I want to use Json Web token authentication. but when I import, it gives me error of no reference of TokenObtainPairView, TokenRefreshView, found, however I installed jwt. urls.py: from django.contrib import admin from django.urls import path from rest_framework_jwt.views import ( TokenObtainPairView, TokenRefreshView, ) from django.conf.urls import url,include urlpatterns = [ path('admin/', admin.site.urls), path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), url(r'^auth/', include('authsystem.urls')) Settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', ), } when I do pip freeze I have the packages: Django==2.2.4 django-cors-headers==3.1.0 djangorestframework==3.10.2 djangorestframework-jwt==1.11.0 djangorestframework-simplejwt==4.3.0 Pillow==6.1.0 PyJWT==1.7.1 pytz==2019.2 sqlparse==0.3.0 I have tried to import from different way but still it giving me cannot find reference. -
bin/python3: cannot execute binary file: Exec format error
I just made a new django project, pushed it to git and now I am trying to go deploy it using Digital ocean. I installed all the needful things like pip, python etc. but I am not able to make the python manage.py runserver work. ((g-v) is my virtualenv so that is not the problem.) It is throwing this error: (g-v) root@ubuntu-s-4vcpu-8gb-blr1-01:/home/g-v/src# python manage.py runserver File "manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax I read a few posts that recommended trying out python3 manage.py runserver but when I try that, I get this error: (g-v) root@ubuntu-s-4vcpu-8gb-blr1-01:/home/g-v/src# python3 manage.py runserver -bash: /home/g-v/bin/python3: cannot execute binary file: Exec format error My pip list command outputs: (g-v) root@ubuntu-s-4vcpu-8gb-blr1-01:/home/g-v/src# pip list DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Package Version ----------------------------- ---------- astroid 1.6.6 autopep8 1.4.4 backports.functools-lru-cache 1.5 certifi 2019.6.16 configparser 3.7.4 Django 1.11.23 enum34 1.1.6 futures 3.2.0 isort 4.3.21 lazy-object-proxy 1.4.1 mccabe 0.6.1 pip 19.2.2 pipenv … -
Object of type "" is not JSON serializable
I am trying to create an API and pass the context data in Response but I am getting the error: Object of type TakenQuiz is not JSON serializable Below is the code: taken_quizzes = quiz.taken_quizzes.select_related('supplier__user').order_by('-date') total_taken_quizzes = taken_quizzes.count() quiz_score = quiz.taken_quizzes.aggregate(average_score=Avg('score')) least_bid = quiz.taken_quizzes.aggregate(least_bid=Min('least_bid')) extra_context = {'taken_quizzes': taken_quizzes, 'total_taken_quizzes': total_taken_quizzes, 'quiz_score': quiz_score, 'least_bid': least_bid, 'matching_bids': matching_bids, 'driver_num': driver_num, 'lat_lon_orig': lat_lon_orig, 'lat_lon_dest': lat_lon_dest, 'user_pass': user_pass, 'username': username, 'password': password, } print("extra content is ", extra_context) return Response(extra_context) Here is the context data: extra content is {'taken_quizzes': <QuerySet [<TakenQuiz: TakenQuiz object (1)>]>, 'total_taken_quizzes': 1, 'quiz_score': {'average_score': 0.0}, 'least_bid': {'least_bid': 899}, 'matching_bids': [], 'driver_ num': 0, 'lat_lon_orig': '36.1629343, -95.9913076', 'lat_lon_dest': '36.1629343, -95.9913076', 'user_pass': ('jkcekc', 'efce'), 'username': 'efw', 'password': 'sdf'} The error I believe is because of the queryset in the extra_context, How do I resolve this ? I tried json.dumps but it still doesn't work -
How to show the email address of sender correctly in django?
How to show the logged in user email address whenever I send email to bilalkhangood6@gmail.com? Although every time it shows me another email address(bilalkhangood4@gmail.com) who is not logged in. I used user.request.email to send email from those user who is logged in. settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_HOST_USER = 'bilalkhangood4@gmail.com' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 587 ACCOUNT_EMAIL_VERIFICATION = 'none' EMAIL_USE_SSL = False views.py from django.contrib.auth.models import User def ViewSendEmail(request): send_mail('Hello from Bilal Khan', 'Hello there, This is an automated message.', user.request.email, #FROM ['bilalkhangood6@gmail.com'], #TO fail_silently=False) return render(request, 'nextone/email_send.html') -
how to customize django password forms, do not use default password form
I am customize reset password form for my django project, however, it always direct to the default password form?? I can customize the login and signup form no problem, but comes to password reset it just direct to the default password form. I do not know what happen? I use django 2.2 project/urls.py from django.contrib import admin from django.urls import path, include from django.views.generic.base import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls')), path('users/', include('django.contrib.auth.urls')), ] project/users/urls.py from django.urls import path from .views import SignUpView urlpatterns = [ path('signup/', SignUpView.as_view(), name='signup'), ] project/users/views.py f rom django.urls import reverse_lazy from django.views.generic import CreateView from .forms import CustomUserCreationForm class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') password_reset_url = reverse_lazy('password_reset') template_name = 'signup.html' project/users/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('username', 'email', 'age',) class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('username', 'email', 'age',) my directory