Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-rest-auth logout endpoint does not work
I got my logout functionality working by using django-rest-auth, but the django-rest-auth logout endpoint doesn't seem to work. It says that I am logged out succesfully upon making a post request with the authorized token in the payload. But when I login again I get the same token as I got earlier. So apparently the backend doesn't actually delete the last token and just gives the old one, making the logout endpoint really useless. Does anyone have a solution for this? -
How do i log-in with a POST request in a Django view?
On a certain page of my Django project, i'm trying to add a feature where, when a page is loaded, a request is sent to an external Python script, this Python script will retrieve some data and send it as a response to the Django view, which should show it on the HTML using Jquery. To send the requests, i'm using the Request module. I'm having some problems sending the response with the Json data to the Django view, here is what i tried: Here is how the request is sent: import requests req = requests.post('http://127.0.0.1:8000/myview', json={"test": "testjson"}) print('SENT') What i tried in the view: def myTestView(request): if request.method == 'POST': received_json_data=json.loads(request.body) print(received_json_data) print('Received request') I'm trying to print the response in my console just for debugging purposes. The problem is that i don't see the request being printed in the console. Instead, i only see this: [24/Dec/2019 12:00:40] "POST /tv/ HTTP/1.1" 302 0 [24/Dec/2019 12:00:40] "GET /account/login/?next=/tv/ HTTP/1.1" 200 23357 Which means that i have to add my credentials, since the view is @login_required. The problem is that this request is fired when the user loads the page or performs a certain operation, and the request will hold sensitive … -
Filter Django Generic Foreign Key by related model attribute
I have a model: from django.db import models from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType class TaggedItem(models.Model): tag = models.SlugField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') def __str__(self): return self.tag How to filter a queryset by related object attribute? Not all of related objects have attribute 'name' TaggedItem.objects.filter(content_object__name='guido') -
how to run django server on background at startup?
I wanna Django runserver on the background when I start my laptop I'm using ubuntu. I tried using "screen" but this is not what am looking for. -
Retrieve details from multiple tables using django query
I need to write a single django query such that I'm able to display the "status, date, time, job_name, sol_name and dept_name" so that a rest api is created. Model classes class Job_Report(models.Model): id:models.BigAutoField(primary_key=True) job_id: models.ForeignKey(Job, models.DO_NOTHING) status:models.CharField(max_length=7) date: models.DateField() time: models.TimeField() duration = models.BigIntegerField(blank=True, null=True) class Job(models.Model): id:models.BigAutoField(primary_key=True) name:models.CharField(max_length=500) folder_id:models.ForeignKey(Job_folder, models.DO_NOTHING) class Job_folder(models.Model): id:models.BigAutoField(primary_key=True) repo_id:models.ForeignKey(Sol_folder, models.DO_NOTHING) class Sol_folder(models.Model): id:models.BigAutoField(primary_key=True) sol_id:models.ForeignKey(Solution, models.DO_NOTHING) class Solution(models.Model): id:models.BigAutoField(primary_key=True) name:models.CharField(max_length=500) dep_id:models.ForeignKey(Department, models.DO_NOTHING) class Department(models.Model): id:models.BigAutoField(primary_key=True) dept_name:models.CharField(max_length=500) I tried using "query_set=Job_Folder.objects.raw('select Job_Folder.status,Job_Folder.date,Job_Folder.time,Job.name,Department.name,Solution.name from Job_Folder,Job,Solution') but resulted in error. Any help would be appreciated. -
Permission for logged in user steps
I am creating an app with recipes. Now i want to make that a logged in user can add recipes by himself. I know that i have to create some permission for this user, but i do not know how. I do not need any code i am just wondering if you can give me some direction what must be done. Do i have to add some user to my model and create permission.py? My model: from django.db import models class Ingredient(models.Model): ingredient_name = models.CharField(max_length=250) def __str__(self): return self.ingredient_name class Recipe(models.Model): recipe_name = models.CharField(max_length=250) preparation = models.CharField(max_length=1000) ingredients = models.ManyToManyField(Ingredient) def __str__(self): return self.recipe_name admin: from django.contrib import admin from .models import Recipe from .models import Ingredient admin.site.register(Recipe) admin.site.register(Ingredient) -
How to merge functionalities in Django Admin Mixins?
I am using two Django plugins, django-import-export and django-safedelete. Both have provided features in Django Admin dropdown. Like: django-import-export django-safedelete Is there a simple method to combine features from these two plugin, with minimal code changes? -
Django - Create Images related on Article's HTML
I have an Article model with html as the text and I have an Image model with a field article = ForeignKey(Article). If there are images added to html of Article, they should be extracted and added as objects to the Image model. I have written my function create_images_from_tags to search for img tags using Beautifulsoup and save them. Unfortunately, this doesn't work and I get this error: ValueError: save() prohibited to prevent data loss due to unsaved related object 'Article'. Here's my save function of my Article model: def save(self, *args, **kwargs): self.html = self.create_images_from_tags(self.html) return super().save(*args, **kwargs) Placing the function after super.save() will end up in an endless loop, because I'd have to save the model after it again. -
Django FilePathField
field_name = models.FilePathField(path=None, match=None, recursive=False, max_length=100, **options) Hi guys, has anyone used the FilePathField? What filesystem is it referring to, the client filesystem or the server filesystem that is stores a Char path to? -
Failure in multiple times Parameters Passing in Django (Python)
I am new to django. My current plan is displaying user name on different html pages, once user have successfully logged in. At the moment, the page after login page can successfully display the user name with the django tag in html which is {{ username }}. But once it has successfully passed to my second page, my second page CAN NOT pass it to my third page. The attached images are my html codes for second.html and third.html. Thanks for your help. ''' Python codes in view.py def ActionGet(request): if request.method == "POST": if 'login' in request.POST: usrname = request.POST.get("usrnm", None) passwrd = request.POST.get("pwd", None) dic={} dic['username']=usrname dic['password']=passwrd return render(request, "Second.html",dic) if 'SecondPageSub' in request.POST: usrname = request.POST.get("usrnm", None) dic={} dic['username']=usrname return render(request, "Third.html",dic) if 'ThirdPageSub' in request.POST: usrname = request.POST.get("usrnm", None) dic={} dic['username']=usrname return render(request, "Forth.html",dic) Second Html code Third Html code -
Why is an integer dictionary key retrieved as string from session?
In the code below, why is the 1 key of people dictionary retrieved as string in session_retrieve view? How can I keep the original (integer) type? Also, why does the same not happen for the 45 value? def session_add(request): people = { 1: { 'name': 'Tom', 'age': 45, } } request.session['people'] = people print(request.session['people']) # prints {1: {'name': 'Tom', 'age': 45}} return HttpResponse('added') def session_retrieve(request): print(request.session['people']) # prints {'1': {'name': 'Tom', 'age': 45}} return HttpResponse('retrieved') -
Django throwing an error when I try to send a mail
i try to send mail through django from django.shortcuts import render from django.http import HttpResponse from django.core.mail import send_mail def function(request): send_mail('cheking', 'cheking django is sending mail or not', 'nithinjith40@gmail.com', ['ravisarath64@gmasil.com'], fail_silently=False) return render(request,'message.html') then show this error Internal Server Error: / Traceback (most recent call last): File "/home/expert/project _jango/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/expert/project _jango/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/expert/project _jango/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/expert/project _jango/myproject/webapp/views.py", line 11, in function fail_silently=False) File "/home/expert/project _jango/venv/lib/python3.5/site-packages/django/core/mail/__init__.py", line 60, in send_mail return mail.send() File "/home/expert/project _jango/venv/lib/python3.5/site-packages/django/core/mail/message.py", line 291, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/expert/project _jango/venv/lib/python3.5/site-packages/django/core/mail/backends/smtp.py", line 103, in send_messages new_conn_created = self.open() File "/home/expert/project _jango/venv/lib/python3.5/site-packages/django/core/mail/backends/smtp.py", line 70, in open self.connection.login(self.username, self.password) File "/usr/lib/python3.5/smtplib.py", line 729, in login raise last_exceptio smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials d65sm27731624pfa.159 - gsmtp') How i can solve this error? 'i enable Less secure app access' then showing the same error -
ImportError: No module named django.core even I getting when I am importing django in python console
I had recently updated my django version from 1.11 to 3.0. when I want to create a project using python-admin startproject mysite I am getting error as ImportError: No module named django.core I tried importing the django in python3 console it is working. -
How to Validate DJango Rest Framework API request?
I want to validate my API with the requested data to access and API. Suppose I want to create and register API in Django rest framework using a serializer and my requirement is to customize validation with all keys and send proper validation error messages, like Required field validations, Age Restrictions validations, Proper Email fields validation, Captcha code validation, Password Length and alphabetic validation, Mobile Validation With OTP verifications -
how to slice email to make username in django rest framework?
I have created slicing in views but how to do that using rest framework in django. username = email username = username.split("@") real_username = username[0] I have done this in views -
Django Admin weird behavior with save_model()
I currently having a custom User model which some of the fields are supposed to be encrypted (data side) but on Django Admin they need to be decrypted to show the actual data so i have encrypt_string() and decrypt_string() function to handle it. My user model: class User(AbstractUser): uid = models.CharField( "uid", max_length=255, null=True, blank=True) nickname = models.CharField( "Nickname", max_length=255, null=True, blank=True) eth_address = models.CharField( "Eth address", max_length=255, null=True, blank=True) eth_private_key = models.CharField( "Eth private key", max_length=255, null=True, blank=True) evt_address = models.CharField( "Evt address", max_length=255, null=True, blank=True) evt_private_key = models.CharField( "Evt private key", max_length=255, null=True, blank=True) eth_address, eth_private_key, evt_address and evt_private_key need to be encrypted when doing any kind of saving or edit Currently when my server request from an api it will create a default user(handle on custom authentication_class of django-rest-framework): existed_user_check = User.objects.filter(uid=uid).exists() if not existed_user_check: random_password = ''.join(["{}".format(randint(0, 9)) for num in range(0, 6)]) eth_address, eth_private_key = generate_eth() evt_address, evt_private_key = generate_evt() new_user = User( username=uid, uid=uid, eth_address=encrypt_string(eth_address), eth_private_key=encrypt_string(eth_private_key), evt_address=encrypt_string(evt_address), evt_private_key=encrypt_string(evt_private_key) ) new_user.set_password(random_password) new_user.save() And on my Django Admin i wrote the following in the admin.py to handle decrypt(when showing the data on change view) and encrypt(when doing any saving or edit of those 4 fields): user_profile_encrypt_fields … -
Django ORM query for this purpose
I'm displaying rows of my Influencer objects in some view. Any of those influencers can be in a InfluencerList object (related by many-to-many). I have added an "Add to List" button to each row so user can add influencers to his own lists (user and influencer list are related by many-to-one). When user clicks the button a popup window opens and it displays users all list names and each lists influencer count next to it. Here is what i got so far: https://pasteboard.co/IMHHSa6.png What i want to do is make some of those checkboxes checked by default if any of those lists contains the related influencer. Here is my current code: models.py: class Influencer(models.Model): # fields are not included for clarity pass class InfluencerList(models.Model): name = models.CharField('Name:', max_length=20, blank=False) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='lists') influencers = models.ManyToManyField('Influencer', related_name='lists') views.py: class InfluencerListView(LoginRequiredMixin, ListView): model = Influencer # template_name = "app1/influencer_list.html" context_object_name = 'influencers' # not necessary, default is object_list #queryset = Influencer.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) logged_in_user = self.request.user context['myLists'] = logged_in_user.lists.values('name').annotate( influencers_count=Count('influencers')) # returns a list of dicts return context views.py {% for myList in myLists %} <label class="list_existing_item"> <input class="checkbox-input" id="myCheckbox" type="checkbox" data-inf_id="{{influencer.id}}" data-list_id="{{myList.id}}" onclick="myFunc(this)"> {{myList.name}} <span … -
django.urls.exceptions.NoReverseMatch: Reverse for 'displayTagInfo' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<tagname>[^/]+)$']
url.py urlpatterns = [ .... path("<str:tagname>", views.displayTagInformation, name='displayTagInfo'), # path('displayTagInformation',views.displayTagInformation) ] In this urls tagname is string which I got from list data. home.html <form action="dispalyTagName" method="POST"> {% csrf_token %} <h3 align="center">Tags</h3> <h6>{{ userName }} <form action="" method="POST"> {% csrf_token %} {% for tagname in tagNameList %} <a href="{{tagname}}" title="Created by: {{ userName }}">{{ tagname }} ,</a> {% endfor %} </form> </form> Here I am trying to fetch all list in for loop as link because I want to pass that link again to py file. views.py def displayTagInformation(request, tagname): print("selected tag name : ", tagname) databaseTags = TagsInformation.objects.filter(tagName = tagname).values() global tagDesc addedTagdata= list(databaseTags) print(addedTagdata) print(type(addedTagdata)) for tagDescription in addedTagdata: tagDesc=tagDescription.get("tagDescription") return render(request, "questionnaireApp/TagTable.html", {'addedTagdata': addedTagdata, 'selectedTagName':tagname,'tagDesc':tagDesc}) In view function I fetched data from sqlite database and I got list addedTagdata. I fetched some data with the help of this list. I got above exception. -
Some chat suggestions
Hey I am trying to build a chat application like you have on social media sites with django on backend.On the frontend I know vannila JavaScript and jquery for Ajax. What are some of the best made solutions to this problem or should I made it from scratch or should I use django channels for this and learn a frontend framework like react before starting out to build it? I need a detailed explanation on what's the fastest roadmap of achieving the solution? -
How to add to cart drf
I have already asked this question but i got no response can you please elaborate how should i proceed. I am trying to create the order but i stuck at logic. models.py: class OrderItem(models.Model): image_number = models.CharField(max_length=20) title = models.CharField(max_length=20) image_size = models.CharField(max_length=50) file_type = models.CharField(max_length=20) price = models.CharField(max_length=50) #item = models.ForeignKey(Image, on_delete=models.CASCADE) #image_number = models.CharField() #quantity = models.IntegerField(default=1) def __str__(self): return self.title class Order(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return str(self.user) serializers.py: class AddtocartSerializers(serializers.ModelSerializer): class Meta: model = OrderItem fields = ['image_number','title','image_size','file_type','price'] class CartSerializers(serializers.ModelSerializer): class Meta: model = Order fields = ['item', 'start_date', 'ordered_date' ] views.py: class AddtocartView(viewsets.ModelViewSet): authentication_classes = [] permission_classes = [] pagination_class = None queryset=OrderItem serializer_class = AddtocartSerializers class CartView(APIView): authentication_classes = [] permission_classes = [] pagination_class = None queryset=Order.objects.all() serializer_class = CartSerializers urls.py: path('addtocart/',views.AddtocartView.as_view({'get':'list'}),name='addtocart'), path('cart/',views.CartView.as_view({'get':'list'}),name='cart'), i think when i make a post request with addtocart api its should add to order or nasted with cart api. i'm not sure? -
How to select random data excluding specific entry from database in python
In Python-Django I have table mangoes. It has mango_id, mango_details, mango_type and mango_del. mango_del used for if the entry exists or deleted. 1 for delete and 0 for exist. Now I want to fetch random mangoes from database but this should not include those whose mango_del is 1. suggest me to solve this problem in two ways. 1) what if my database is small say 1000-10,000 entry. 2) what if my database is huge say hundred thousand or more entry. -
Error running python runserver --nothreading -noreload
/home/saumen/.local/lib/python2.7/site-packages/django/core/management/__init__.py:316: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal if subcommand == 'runserver' and '--noreload' not in self.argv: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/saumen/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/saumen/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/saumen/.local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/saumen/.local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 61, in execute super(Command, self).execute(*args, **options) File "/home/saumen/.local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/saumen/.local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 86, in handle 'or address:port pair.' % options['addrport']) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128) I am getting the error when I run python runserver --nothreading -noreload.what Can I do? I have installed mysqlclient and necessary python libraries. -
Python: Add minutes or seconds to a time only object
I need to add a given number of minutes or seconds to a Time object that comes without the date portion. For Ex: Time: 13:00:00 + 10 minutes (Should return 13:10:00) Time: 21:50:00 + 1800 seconds (Should return 22:20:00) How can I do this in Python 3? -
CSV to Database in Django
I'm receiving data from upload form on my site, and I would like to insert the data to a Database. In views.py I'm using this code def upload(request): data = {} if "GET" == request.method: return render(request, "main/upload.html", data) # if not GET, then proceed csv_file = request.FILES["csv_file"] if not csv_file.name.endswith('.csv'): messages.error(request,'File is not CSV type') return HttpResponseRedirect(reverse("main:upload")) #if file is too large, return if csv_file.multiple_chunks(): messages.error(request,"Uploaded file is too big (%.2f MB)." % (csv_file.size/(1000*1000),)) return HttpResponseRedirect(reverse("main:upload")) file_data = csv_file.read().decode("utf-8") lines = file_data.split("\n") #io_string = io.StringIO(data_set) #print(io_string.getvalue()) #next(io_string) for line in lines: column = line.split(",") data_dict = {} data_dict["顧客CD"]=column[0], data_dict["顧客補助CD"]=column[1], data_dict["顧客名称1"]=column[2], data_dict["顧客名称"]=column[3], data_dict["顧客名称カナ"]=column[4], data_dict["法人名称"]=column[5], data_dict["代表者名称"]=column[6], data_dict["住所"]=column[7], data_dict["電話番号"]=column[8], data_dict["地区名称"]=column[9], data_dict["データマッチ用電話番号"]=column[10], data_dict["契約状態"]=column[11] form = kokyaku(data_dict) form.save() return HttpResponseRedirect(reverse("main:upload")) And in models.py this from djongo import models from django.utils import timezone from django.contrib.auth.models import User class kokyaku(models.Model): 顧客CD = models.IntegerField(blank=True) 顧客補助CD = models.IntegerField(blank=True) 顧客名称1 = models.TextField(blank=True) 顧客名称 = models.TextField(blank=True) 顧客名称カナ = models.TextField(blank=True) 法人名称 = models.CharField(max_length=15, blank=True) 代表者名称 = models.CharField(max_length=15, blank=True) 住所 = models.TextField(blank=True) 電話番号 = models.IntegerField(blank=True) 地区名称 = models.TextField(blank=True) データマッチ用電話番号 = models.IntegerField(blank=True) 契約状態 = models.CharField(max_length=2, blank=True) def __str__(self): return self.顧客名称 As you can see, I'm trying to "match" the columns from views to models with python's dict, but in models I'm trying to … -
String to Integer in Django Template
I have rendering one string in django template but in django template, I want to convert it into integer. I have tried many thing like |add:to_int but it doesn't work.