Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - querying only subclass instances
I have the following model inheritance structure: class ModelA(models.Model): # some fields class Type(models.Model): # fields common to all subtypes # ... # and a ForeignKey relationship modelA = models.ForeignKey(ModelA) class Subtype1(Type): # fields specific for this type class Subtype2(Type): # fields specific for this type So, as you can see. I have this inheritance structure. So far, I can list all Type instances (regardless of their subtypes) at once via the following class-based view in views.py: class TypeList(generics.ListAPIView): serializer_class = TypeSerializer def get_queryset(self): pk = self.kwargs['pk'] modelA = ModelA.objects.get(id=pk) return modelA.type_set.all() So, what I does is: The view gets the id (packed within the URL) of the ModelA instance so that it can get the right ModelA instance from the database. Later on, we return all Type instances of ModelA (because through the foreignkey relationship it can access its set of Type objects). It works very well. But I also want to query the subclass types. How I can do that ? When I replace the return statement from previous code with return modelA.subtype1_set.all(), then I get the following error: AttributeError at /modelAs/1/ 'ModelA' object has no attribute 'subtype1_set' That's clear for me because there is no relationship between … -
Django REST Framework: How to create/handle auth_token for existing and new users?
Currently working on a web-app that I'm implementing an API for. This API will be consumed by an iOS application. Django REST Framekwork provides a convenince view to create tokens for users, providing the username+password are included in the headers: from rest_framework.authtoken import views urlpatterns += [ url(r'^api-token-auth/', views.obtain_auth_token) ] Assumption is users will be registering and logging in from both web and app. What's the best way to handle this? My biggest quibble is with existing users that will be logging in from the iOS app (they already have an account, but don't have an auth token). My current plan is this: Create auth tokens for ALL existing users. Integrate token creation upon registration. This way I can cover all cases. But is there a better approach? -
foreign key assignment for child object
I have a very simple question which I am not able to get my head around. I have following models class Parent(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=64) class Child(models.Model): boardid = models.ForeignKey(Parent,on_delete=models.CASCADE,related_name="child") id = models.AutoField(primary_key=True) title = models.CharField(max_length=128) Serializers class ParentSerializer (serializers.ModelSerializer): class Meta: model = Parent fields = ('__all__') class ChildSerializer (serializers.ModelSerializer): class Meta: model = Child fields = ('id','title') and simple createAPIview for the children class ChildCreateView(CreateAPIView): queryset= Child.objects.all() serializer_class = ChildSerializer When I call this url /api/parent/1/child/create I want to pre populate the foreign key board id with the id 1 and create child object with rest of the information which I will be providing in the body . How is this possible to achieve -
Password Confirmation error not displayed in django forms
I tried to compare password and confirmpassword .if i enter different password it wil not raise error. it will redirected to loginpage. i am using pycharm software and django framework with sqlite3 database. '''models.py class reg1(models.Model): name=models.CharField(max_length=100) city=models.CharField(max_length=100) email=models.CharField(max_length=100) username=models.CharField(max_length=100) password=models.CharField(max_length=100) cpassword=models.CharField(max_length=100) class Meta: db_table='reg1' forms.py class regform(forms.Form): name = forms.CharField(max_length=100) city = forms.CharField(max_length=100) email = forms.CharField(max_length=100) username = forms.CharField(max_length=100) password = forms.CharField(max_length=100) cpassword=forms.CharField(max_length=100) def clean_password(self): if self.data['password'] != self.data['cpassword']: raise forms.Error('Passwords are not the same') return self.data['password'] views.py if myregform.is_valid(): name1 = myregform.cleaned_data['name'] city1 = myregform.cleaned_data['city'] email = myregform.cleaned_data['email'] username1 = myregform.cleaned_data['username'] password1 = myregform.cleaned_data['password'] password2=myregform.cleaned_data['cpassword'] a=reg1(name=name1,city=city1,email=email,username=username1,password=password1,cpassword=password2) a.save() ''' I expect the output as i enter a different password it will show password not matching error -
How to return int from select option value in plain html in django
I have a plain html form which contains a select option, the select option value should return an int to be stored in the database. I have tried converting the value to int in the view but it still doesnt work. This is the model from which I am populating the select options. class GoalStatus(models.Model): target = models.CharField(max_length=100, choices=target, default="Week") def __str__(self): return self.target This is the html form <form action="" method="post"> {% csrf_token %} <div class="form-group"> <label for="task">Task</label> <input type="text" class="form-control" id="task" name="task"> </div> <div class="form-group"> <label for="task">Goal</label> <select name="goal" class="form-control"> {% for goal in user %} <option value='{{goal.id | to_int }}'>{{goal.target}}</option> {% endfor %} </select> </div> <button type="submit" class="btn btn-primary">Create task</button> </form> This is the view which I am getting the post request and saving to the database. def user_add_task(request): user = GoalStatus.objects.all() if request.method == 'POST': if request.POST.get('task') and request.POST.get('goal'): task = ScrummyGoals() task.target_name = int(request.POST.get('goal')) task.user_name = request.user.scrummyuser.id task.task = request.POST.get('task') task.save() return redirect('myapp:home') return render(request, 'myapp/user_add_task.html', {'user':user}) I expect the value of the select option to be an int e.g 1 not a string e.g "1". So I get this error: Exception Type: ValueError Exception Value: Cannot assign "1": "ScrummyGoals.target_name" must be a "GoalStatus" instance. -
How to fix "ImportError: cannot import name 'safe_join' from 'storages.utils' " error while deploying web application on heroku?
I am deploying Django web application which is working on local server but after deployment to heroku it gives error. I have attached last few logs I get by running heroku logs --tail. Error Logs in Heroku 2019-06-15T10:04:39.772193+00:00 app[web.1]: from storages.utils import safe_join, setting 2019-06-15T10:04:39.772196+00:00 app[web.1]: ImportError: cannot import name 'safe_join' from 'storages.utils' (/app/.heroku/python/lib/python3.7/site-packages/storages/utils.py) 2019-06-15T10:04:39.772260+00:00 app[web.1]: [2019-06-15 10:04:39 +0000] [11] [INFO] Worker exiting (pid: 11) 2019-06-15T10:04:39.881913+00:00 app[web.1]: [2019-06-15 10:04:39 +0000] [4] [INFO] Shutting down: Master 2019-06-15T10:04:39.881994+00:00 app[web.1]: [2019-06-15 10:04:39 +0000] [4] [INFO] Reason: Worker failed to boot. 2019-06-15T10:04:39.963380+00:00 heroku[web.1]: Process exited with status 3 2019-06-15T10:05:54.887448+00:00 heroku[web.1]: State changed from crashed to starting 2019-06-15T10:15:34.031356+00:00 heroku[run.4032]: State changed from up to complete 2019-06-15T10:15:34.014580+00:00 heroku[run.4032]: Process exited with status 127 ImportError: cannot import name 'safe_join' from 'storages.utils' (/app/.heroku/python/lib/python3.7/site-packages/storages/utils.py) -
why login form and signup form doesn't show errors?
I have a simple login form and signup form which upon wrong validation it doesn't throw any error, these are respective codes: def signup_view(request): if request.method == 'POST': signup_form = UserRegistrationForm(request.POST) if signup_form.is_valid(): signup_form.save() username = signup_form.cleaned_data.get('username') messages.success(request, f'Thank you for using our website.') return redirect('user:login') signup_form = UserRegistrationForm() context = { 'form':signup_form } return render(request, 'users/signup.html', context) def login_view(request): if request.method == 'POST': login_form = AuthenticationForm(request, request.POST) if login_form.is_valid(): username = login_form.cleaned_data.get('username') user = authenticate(username=username, password=login_form.cleaned_data.get('password')) if user is not None: login(request, user) messages.success(request, f'Successfully logged in as <strong> {username} </strong> ') return redirect('blog:blogs') login_form = AuthenticationForm() context = { 'form': login_form } return render(request, 'users/login.html', context) this is login form and it looks same as signup form: <form action="." method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <input type="submit" value="Login" class="btn btn-warning btn-block"> <hr> <small class='text-secondary'>Don't have an account? <a href="{% url 'user:signup' %}">Sign up</a> </small> <br> <small class='text-secondary'>Forgot password? <a href="{% url 'password_reset' %}">Reset</a></small> </form> These two forms work properly, it can create a new user and it log in that user, but if I make any error it doesn't throw or show that error, why? Thank you in advance -
Setting model field default to shortuuid.uuid() does not generate unique values
I have a CustomUser model that I want to generate a unique shortuuid each insert. Not sure if I'm doing this the right way because I'm running into non-unique uuids with consecutive inserts. Or am I supposed to override the create method and generate the shortuuid from there? from django_extensions.db.fields import ShortUUIDField import shortuuid class CustomUser(AbstractUser): uuid = ShortUUIDField(unique=True, blank=False, editable=False, default=shortuuid.uuid()) -
Django Rest Framework: DRYer pagination for custom actions
Suppose I need to set up several GET endpoints that look like this objects/past, objects/future. Example: @action(detail=False, methods=["GET"], name="Past Objects") def past(self, request, *args, **kwargs): startdate = datetime.datetime.now() some_user = UserProfile.objects.get(user__username="someuser") queryset = self.queryset.filter( other__attribute__profile=some_user, creation_date__lte=startdate ).order_by("-creation_date") page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) Is there anyway to avoid the page = ... -> serializer part? I have specified this in my ModelViewSet: pagination_class = CustomObjectPagination But it seems this is only auto-applied to methods like get_queryset and not custom actions. Do I have to write this boilerplate every time I specify a custom action like past? page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) -
How to get "price_retail" field value in tempate?
I am trying access price_retail field in product detail page using template tag purchase_info_for_product. but am not getting the value of price_retail. {% purchase_info_for_product request product as session %} {{ session.price.price_retail|currency:session.price.currency }} but i am able to access fields like incl_tax, excl_tax -
How to solve a "Direct assignment to the forward side of a many-to-many set is prohibited. Use users_ifollow.set() instead." error?
I am trying to make a follower system using django and am getting the above mentioned error code models.py class Following(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) users_ifollow=models.ManyToManyField(User, related_name='followed_by') def __str__(self): return f'{self.user.username} following' views.py class UserFollowView(View): def get(self, request, username, *args, **kwargs): toggle_user=get_object_or_404(User,username__iexact=username) if request.user.is_authenticated: user_profile, created=Following.objects.get_or_create(user=request.user) if toggle_user in Following.objects.filter(user=request.user, users_ifollow=toggle_user): Following.objects.remove(user=request.user, users_ifollow=toggle_user) else: Following.objects.create(user=request.user, users_ifollow=toggle_user) return render(request, 'users/not_creator.html') urls.py path('user/<str:username>/follow', UserFollowView.as_view(),name='follow_user'), traceback Traceback: File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/views/generic/base.py" in dispatch 97. return handler(request, *args, **kwargs) File "/home/Grayocean/grayocean.co/blog/views.py" in get 74. Following.objects.create(user=request.user, users_ifollow=toggle_user) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/db/models/query.py" in create 420. obj = self.model(**kwargs) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/db/models/base.py" in init 496. _setattr(self, prop, kwargs[prop]) File "/home/Grayocean/.virtualenvs/myenv/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py" in set 538. % self._get_set_deprecation_msg_params(), Exception Type: TypeError at /user/rheazes/follow Exception Value: Direct assignment to the forward side of a many-to-many set is prohibited. Use users_ifollow.set() instead. -
How to download from another server using Django?
I am using Django, and I have set up a form where a user is able to set a url from a sister website(another server) and download this resource into the django server. Upon completion of the download to the django server to show a download link to the user. Initially I made a python attempt using requests and it works correctly. Now I tried to embed that in django but it is failing. Can i use requests in Django? Is there a better/preferable way this is being done? This is the code I have used class DownloadFile: def __init__(self, user, password, location): self.location = location self.user = user self.password = password def startDownload(self, urllist): cleanList = self.cleanUrlList(urllist) filenames = [] for x in cleanList: filenames.append(self.getFilename(x)) payload = {'op': 'login', 'redirect': 'http://www.sisSite.com', 'rand': 'nqkprxqrwa', 'login': self.user, 'password': self.password} s = requests.Session() r = s.post('http://www.sisSite.com/login', data=payload) for pos in range(len(cleanList)): with open(self.location + filenames[pos], "wb") as f: response = s.get(cleanList[pos], stream=True) total_length = response.headers.get('content-length') print('\nDownloading -> ' + filenames[pos] + 'from URL >>' + cleanList[ pos] + '<< -- total length =' + total_length) if total_length is None: f.write(response.content) else: dl = 0 total_length = int(total_length) for data in response.iter_content(chunk_size=4096): dl … -
how to display the uploaded image using Django and AJAX
i am creating a form that allow user user to select image and uploaded using django and ajax. this process work fine but the problem is that the uploaded image doesn't being displayed on the screen however i did specified a for it. steps that i followed: Create a model that handle the uploaded image. Create a path for the function. Create the function that upload the selected image Create the template and ajax function models.py class photo(models.Model): title = models.CharField(max_length=100) img = models.ImageField(upload_to = 'img/') home.html <form method="POST" id="ajax" enctype="multipart/form-data"> {% csrf_token %} Img: <br /> <input type="file" name="img"> <br /> <br /> <button id="submit" type="submit">Add</button> </form> $('#ajax').submit(function(e) { e.preventDefault(); var data = new FormData($('#ajax').get(0)); console.log(data) $.ajax({ url: '/upload/', type: 'POST', data: data, contentType: 'multipart/form-data', processData: false, contentType: false, success: function(data) { // alert('gd job'); $("#photo").html('<h2> {{'+data.title+'}}</h2> <img src="{{'+data.img.url+ '}}" alt="{{ photo.title }}">') } }); return false; }); views.py def upload(request): if request.method == 'POST': if request.is_ajax(): image = request.FILES.get('img') uploaded_image = photo(img = image) uploaded_image.save() photo=photo.objects.first() # return render(request, 'home2.html') return HttpResponse(photo) i expect that after the user upload the image and the image i stored in the database, the image must be displayed on the screen. -
Django: Setting "on_delete=DO_NOTHING" on a ManyToManyField
Django's although useful ManyToManyField is highwired to kill all involved subjects when deleted... with it's internal ForeignKey on_delete=CASCADE. Why is that hard coded?! and what is the simple way to override this behavior? After considering a number of solutions, seems the most clean one is to externally handle delete signal call and set nulls on the values... Is there a cleaner/simpler way? And shouldn't it be a red flag on ManyToManyField? -
What are the most useful python libraries for creating an IPTV Panel?
I want to create an IPTV Panel like Xtream codes but in python using django and I want to know if there are any useful python libraries that may help me in this project (creating VOD, use channel links and generate m3u files from it...) -
How to call a REST API service through Vue JS
I am creating a blog website using Vue JS and Django Rest Framework. I have a submit Button in Vue JS which should pass text input to Django, How can I do that ? The POST API link is in localhost:8000/api/post -
import views.py from another section in the main section's urls.py
i can't extend blog/template/base.html in users app i use this code: {% extend "blog/base.html" %} here is my project image: Error: TemplateDoesNotExist at /register/ blog/base.html Request Method: GET Request URL: http://localhost:8000/register/ Django Version: 2.2 Exception Type: TemplateDoesNotExist Exception Value: blog/base.html -
In Django, How to display an index file not customized for django with relative links to it's own source files
Give a link on a page to an index file that works as a standalone offline app without changing the internal links and structures. I have hundreds of these. -
Integrating Django Rest Framework and Scrapy
Both Scrapy and Django Frameworks are standalone best framework of Python to build crawler and web applications with less code, Though still whenever You want to create a spider you always have to generate new code file and have to write same piece of code(though with some variation.) I was trying to integrate both. But stuck at a place where i need to send the status 200_OK that spider run successfully, and at the same time spider keep running and when it finish off it save data to database. Though i know the API are already available with scrapyd. But i Wanted to make it more versatile. That lets you create crawler without writing multiple file. I thought The Crawlrunner https://docs.scrapy.org/en/latest/topics/practices.html would help in this,therefor try this thing also t Easiest way to run scrapy crawler so it doesn't block the script but it give me error that the builtins.ValueError: signal only works in main thread Even though I get the response back from the Rest Framework. But Crawler failed to run due to this error does that mean i need to switch to main thread? I am doing this with a simple piece of code spider = GeneralSpider(pk) runner … -
Writing Django TestCase for Rest API
I am new in django and please don't feel boring with armature question. I tried to find some tutorial to write TestCase for django rest api but i couldnt find any tutorial for Api testcase but i found huge tutorial for django testcase Can anyone suggest me any tutorial how to write TestCase for Django Rest API? Thanks in Advance -
How to use math operations in django
I want to use arithmetic operations in django. {% if skipped.i-{{ pending | length }}.resource_id.resource_type == 'videos' %} i want to do i-{{pending | length }} -
How to create Django custom validation, so that custom validations depends on another field
I'm trying to make a custom validator. I have there three input-fields in 'model', first for 'content_type', Second for 'content_text' and another for 'content_file'. 'content_type' is one of these values: 'text' or 'file'. Please show me how to fix the problem using the form class in 'form.py' How do I create custom form fields validation, so that if 'content_type==text' ('text' selected by user) then 'content_text' required? and if 'content_type==file' then 'content_file' required? My models: class ContentType(models.Model): title = models.CharField(unique=True, max_length=100) class Suggest(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING) content_text = models.TextField(blank=True) content_file = models.FileField(upload_to='media/upload/suggest_files', null=True) -
Unable to login with provided credentials
I am trying to automatically login the user when user signs up instead of redirecting to login page and then only login. However, I get an error "errors": [ "email", "Unable to login with provided credentials." ], Here is how i have done def get_token(**user): data = {} if user.get('email') and user.get('password'): serializer = JSONWebTokenSerializer(data=user) if serializer.is_valid(): token = serializer.object['token'] user = serializer.object['user'] data = { 'user': user, 'token': token } return data else: data = { 'errors': serializer.errors } return data data = { 'errors': 'Email or Password not provided' } return data # creates the user but could not login class Register(graphene.Mutation): ''' Mutation to register a user ''' class Arguments: email = graphene.String(required=True) password = graphene.String(required=True) password_repeat = graphene.String(required=True) success = graphene.Boolean() token = graphene.String() user = graphene.Field(UserQuery) errors = graphene.List(graphene.String) def mutate(self, info, email, password, password_repeat): if password == password_repeat: try: serializer = RegistrationSerializer(data={ 'email': email, 'password': password, 'is_active': False }) if serializer.is_valid(): user = serializer.save() user_identity = get_token(email=user.email, password=user.password) if not user_identity.get('errors'): return Register(success=True, user=user_identity.get('user'), token=user_identity.get('token')) else: return Register(success=False, token=None, errors=['email', 'Unable to login with provided credentials.']) except Exception as e: errors = [e] return Register(success=False, errors=errors) errors = ["password", "Passwords don't match."] return Register(success=False, … -
Page Not found : Writing your first Django app, part 1
I'm following the Writing your first Django app, part 1, I'm getting the Page not found error , whats the wrong with my code??enter image description here enter image description here enter image description here enter image description here -
how to configure oracle database in ATOM for the django development?
Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, testapp Running migrations: Traceback (most recent call last): File "C:\Users\sandeepreddy\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 83, in _execute return self.cursor.execute(sql) File "C:\Users\sandeepreddy\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\oracle\base.py", line 506, in execute return self.cursor.execute(query, self._param_generator(params)) cx_Oracle.DatabaseError: ORA-02000: missing ALWAYS keyword