Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF doesn't update instead create new instance in modelserializer
Searched throughout SO to find the matching questions doesn't answer mine as there are only few explanations. So hoping to get an answer here. I have a model named "testcase" with pk set as "testcase_name". On update operation in the serializer, instead of updating a new instance is created everytime. I suspect it is because of the pk. serializer.py class TestcaseSerializer(serializers.ModelSerializer): class Meta: model = testcase lookup_field = 'testcase_name' fields = ("testcase_name", 'description') def update(self, instance, validated_data): print(instance) # returns test1 as it is ithe current pk # ret = super(TestcaseSerializer, self).update(instance, validated_data) [setattr(instance, key, value) for key, value in validated_data.items()] instance.save() print(instance)# returns test2 as the testcase_name is changed to test2 #instead it is a new instance rather than the old instance getting updated return instance models.py class testcase(models.Model): testcase_name = models.CharField( max_length=20, primary_key=True) description = models.CharField(max_length=100, blank=True) def __str__(self): return self.testcase_name views.py class Testcaseviewset(viewsets.ModelViewSet): queryset = testcase.objects.all() serializer_class = TestcaseSerializer lookup_field = 'testcase_name' Is there any way to solve this in the serializer itself not from the views. -
Chmod fails when using fuse mount as media directory
I'm trying to use a remote FTP as a Django media source in docker. I have mounted a directory: /mnt/ftp_media with curlftpfs: curlftpfs -o allow_other user:pass@host /mnt/ftp_media I've noticed that when trying to upload a file, it actually does get created on the remote, but django fails on chmod with: Operation not permitted I've tried to directly execute chmod inside the mount: cd /mnt/ftp_mount chmod 666 some_file.txt But then I also get an error: chmod: changing permissions of 'some_file.txt': Operation not permitted Even as a root user. I've tried to remount with different users, but it always yields the same results. Is it just that you should not use chmod in fuse mounts? -
django: href doesn't redirect to the right page
This is my first django project, I'm not sure why the href = "{{ itema.get_absolute_url }}" doesn't work. Any help is appreciated, I'm not sure what I'm doing wrong here. html> <div id='Art' class='research'> {% if info %} {% for itema in research %} <a class = 'linka' href = "{{ itema.get_absolute_url }}"> <div class="research-box"> <img class='research-img' src='{{ itema.image.url }}'> <h3>{{itema.title}}</h3> </div></a> {% endfor %} {% else %} <div> <p>No data available</p> </div> {% endif %} </div> urls> # pages/urls.py from django.urls import path from .views import LinksContentDetailView urlpatterns = [ path('<int:pk>', LinksContentDetailView.as_view(), name='links_detail'), ] root>urls.py> path('', include('pages.urls')), models.py> class LinksContent(models.Model): author = models.ForeignKey(Author, on_delete=models.DO_NOTHING, default= True) title = models.CharField(max_length=100) content = HTMLField() image = models.ImageField(upload_to = 'images/%Y/%m/%d/') image2 = models.ImageField(upload_to = 'images/%Y/%m/%d/', blank = True) is_published = models.BooleanField(default = True) publish_date = models.DateTimeField(default = datetime.now, blank = True) def get_absolute_url(self): return reverse('links_detail', args=[str(self.id)]) views.py> # links research laboratory separate view class LinksContentDetailView(DetailView): model = LinksContent template_name = 'links_detail.html' -
Django - deployment on Heroku returns different HTML than local host
I have a Django app that works great on localhost. When deployed the Heroku, for some reason the app returns different HTMLs. A few examples: I have a form with button type submit. This is the template <button type="button" page="{{request.resolver_match.view_name}}" type="submit" id="bullets_submit" class="btn btn-primary px-5 py-2"> Next Step </button> In localhost everything works well but on Heroku the HTML I receives is without the type="submit". Same button just without this attribute. I have a for loop that iterates on a model and create a li <div class="h5 mx-4 px-3 bg-white" style="position: absolute; top: -20px;"> About the role <a href="{% url 'app:responsibilities' description.pk %}" type="button" class="btn btn-outline-light px-2 text-muted border border-0"><i class="far fa-edit"></a></button> </div> <div class="border border-primary rounded shadow p-2 pt-3 m-2"> <ul> {% for responsibility in description_responsibilities%} <li>{{responsibility}}</li> {% endfor %} </ul> </div> On Heroku, even though the <i class="far fa-edit"> is clearly outside of the for loop, it still get generated several times in the HTML I receive from the server, as if it was inside the for loop. Any idea what might cause this weird behavior? Or how I can debug it? -
Can't get Django REST to save POST object request in model
Trying to allow users to create an object and save it in my model. My front-end POST requests are getting a 201 confirmation response, so no traceback error from the backend. The data seems to be getting serialized but not saved in my model. Here is my code... model.py: class Bucket(models.Model): category_options = ( ('personal', 'Personal'), ('social', 'Social'), ) class BucketObjects(models.Manager): def get_queryset(self): return super().get_queryset() owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='buckets') admin_user = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='admin_user') guest_user = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='guest_user', blank=True) category = models.CharField(max_length=30, choices=category_options) name = models.CharField(max_length=35) created = models.DateTimeField(default=timezone.now, blank=True) slug = AutoSlugField(populate_from = "random_string", blank=True) stock_count = models.IntegerField(blank=True, null=True) stock_list = ArrayField(models.CharField(max_length=6,null=True),size=30,null=True, blank=True) about = models.CharField(max_length=200) objects = models.Manager() bucketobjects = BucketObjects() class Meta: ordering = ('-created',) def save(self, *args, **kwargs): if self.stock_list: self.stock_count = len(self.stock_list) super().save(*args, **kwargs) serializer.py: class BucketCreateSerializer(serializers.ModelSerializer): class Meta: model = Bucket fields = ('owner','category','name','about') read_only_fields = ['owner'] def create(self, validated_data): user = self.context['request'].user bucket = Bucket.objects.create( owner=user, **validated_data ) bucket.save() return bucket view.py: class CreateBucket(generics.CreateAPIView): permission_classes = [IsAuthenticated] serializer_class = BucketCreateSerializer queryset = Bucket.objects.all() How can I go about solving this? -
Django Email Not Working on Production Server
I have recently deployed a site that I developed in Django onto a production server running Ubuntu and Apache. The site functioning in every respect with the exception of sending emails wherever I configure an email to be sent, the page keeps loading and nothing happens although in the back end whatever information was made is saved like the contact us. On the local host emails are working perfectly fine and on the deployed site it is just not sending and the page keeps loading endlessly. Here is an example of the contact us config views.py def contact_us(request): if request.method == 'POST': # check post form = ContactForm(request.POST) if form.is_valid(): data = ContactMessage() # create relation with model data.name = form.cleaned_data['name'] # get form input data data.email = form.cleaned_data['email'] data.subject = form.cleaned_data['subject'] data.message = form.cleaned_data['message'] data.save() # save data to table messages.success(request, "Your message has ben sent. Thank you for your message.") template = render_to_string("marketing/contact_us_email.html", {'first_name': request.user.first_name, 'last_name': request.user.last_name, 'form': form}) msg = EmailMessage('Contact Us Message', template, settings.EMAIL_HOST_USER, ['email@email.com']) msg.content_subtype = "html" # Main content is now text/html msg.fail_silently = False msg.send() return HttpResponseRedirect('/') form = ContactForm context = {'form': form} template = 'marketing/contact_us.html' return render(request, template, context) Here is … -
CSS onclick animation
I have the following messages block at my Django application, see below. Its working beatifully if a new messages appear but what I dont understand is how can I also play a "fadeOut" animation as soon as the onclick function gets hit. {% if messages %} <div class="animated slideInRight messages glas-messages"> <span class="closebtn dot" onclick="this.parentElement.style.display='none';"><span class="cross">×</span></span> {% for message in messages %} <span><li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li></span> {% endfor %} </div> {% endif %} It would be awesome if I could also exec a animation if I click on the cross, can smb help? kind regards -
Writing a cleaner function in python, a parameter to be either a set or a value
I have a struggling with a way of writing this function much cleaner and to make this function for the parameter objs to can be either a QuerySet or an single object, in case when the objs parameter is an set of objects I want to go with the for loop but in the case when is a single object I want to create the date parameter without looping, and also I am not sure if the try block is the good way for checking if the object with these information is already in db or not and if it's not I want to create it with these dates. Any help would be appreciated, thanx! the function: def check_recurrent_or_new(user, objs, obj): for item in objs: if item.created_date.month == 12: date = datetime( item.created_date.year + 1, 1, item.created_date.day, item.created_date.hour, item.created_date.minute, item.created_date.second, item.created_date.microsecond ) else: date = datetime( item.created_date.year, item.created_date.month + 1, item.created_date.day, item.created_date.hour, item.created_date.minute, item.created_date.second, item.created_date.microsecond ) try: obj.objects.get( user=user, name=item.name, amount=item.amount, created_date=date, category=item.category, recurrent=True ) except: obj.objects.create( user=user, name=item.name, amount=item.amount, created_date=date, category=item.category, recurrent=True -
In Django admin, how can I filter a MultipleChoiceField depending on a previous MultipleChoiceField?
In my django website, I have 3 classes: Thing, Category and SubCategory. Thing has 2 ForeignKeys: "Category" and "SubCategory" (such as Car and Ferrari). SubCategory has 1 ForeighKey: "Category" (Ferrari is in the category Car) When I create an instance of Thing in the Admin part and when I choose a Category, I would like that the "SubCategory" field only shows the SubCategories linked to the Category I chose. Is that possible? I saw the possibility to change the AdminForm like: class ThingFormAdmin(forms.ModelForm): def __init__(self,Category,*args,**kwargs): super (ThingFormAdmin,self ).__init__(*args,**kwargs) # populates the post self.fields['sub_category'].queryset = SubCategory.objects.filter(category= ... ) But I don't know what to write on the ... Thanks for the help! -
Docker Plesk Django React PostGre
I have a working Django React Postgres Nginx Project on local Docker and i need to upload it on a plesk server. I hade downloaded the plesk docker application, have downloaded the needed images, uploaded the files, but i cannot seem to make it work. I need help! Thanks. -
Django Rest Framework - Expected a time, but got a datetime on serializer.data
at the moment I have a project, where I need to edit the db through a backend. My problem is that I cant call "serializer.data", but everything else. I did this way of editing date time fields a few times and it always worked but not here. My Model: class Trackedtime(models.Model): personid = models.CharField(db_column='personId', max_length=255, blank=True, null=True) date = models.DateTimeField(db_column='date', blank=True, null=True) latstart = models.FloatField(db_column='latStart', blank=True, null=True) longstart = models.FloatField(db_column='longStart', blank=True, null=True) logout = models.DateTimeField(db_column='logout',blank=True, null=True) latstop = models.FloatField(db_column='latStop', blank=True, null=True) longstop = models.FloatField(db_column='longStop', blank=True, null=True) worktime = models.IntegerField(db_column='workTime', blank=True, null=True) class Meta: managed = False db_table = 'trackedtime' My Serializer: class TrackedTimeSerializer(serializers.ModelSerializer): class Meta: model = Trackedtime fields = ('personid', 'date', 'latstart', 'longstart', 'logout', 'latstop', 'longstop', 'worktime') My View with the error line: class TrackedTimeUpdateDateView(generics.UpdateAPIView): queryset = Trackedtime.objects.all() serializer_class = TrackedTimeSerializer def update(self, request, pk): instance = get_object_or_404(Trackedtime, pk=pk) data = {"date": request.data.get("date")} serializer = ZeiterfassungSerializer(instance, data=data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The error message is Expected a time, but got a datetime. and I know its the serializer.data, because I also tried printing it out. I hope you can help me. Thank you! -
Django(not rest-framework) don`t remember the sessions if a make multiple request from react app
I trying to make request from react-app(http://localhost:8082/) to django-app(not rest-framework) and after each request , request.session.items() is empty. This is happend only when i make requests from browsers , if makes all this steps from postman the sessions middleware works good. I think the problem is from Headers , but i don`t find it React requests : var qs = require('qs'); const headers = { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'withCredentials':false, 'X-CSRF-TOKEN':'cwE9Ddste5nblT6ADjyi1AVhyyh4bQVirjr7CKiC3e5Fazw0YpwLmAQLFuu1X315' } axios.get('http://127.0.0.1:8000/users/setSession',headers) .then(res => { console.log(res.data); },(error) => { }); axios.get('http://127.0.0.1:8000/users/getSession',headers) .then(res => { console.log(res.data); },(error) => { }); Python views.py methods : #@csrf_exempt def setSession(request): request.session['id'] = 12312312 request.session['token'] = 'test' return JsonResponse({'status':200},safe=False,status=202) #@is_auth #@csrf_exempt def getSession(request): print(request.session.items()); return JsonResponse({'status':200},safe=False) enter image description here -
Using different color than bootstrap default color scheme - Django Python
Pretty new to Django, Recently, while building a website using Django, I created the navbar and used bootstrap. Just to make it look better. However, it seems that I'm forced to use bootstrap default color scheme. I want to change the navigation bar background color to a color tag, inside the base.html file. Google left me empty-handed. With many advices on overwriting and adding your custom.css (which a lot of people aware you of doing so as it is not recommended). I tried adding custom script into the html file, failed. <script> .navbar-custom { background-color: #9f6967; } </script> I would appreciate help on (maybe) creating a custom.css file. So far the nav-bar is the default bootstrap navigation bar script from their website. <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> Other than dark/light/other colors from the scheme, there isn't any way to add a color tag. (specific : #9f6967) -
How to upload an image in django using S3Boto3Storage where the path is set dynamically from the view in django
I'm wanting to save images to an S3 bucket using the session_key as the directory inside the bucket, in django. I have created a test page that uploads an image to a set location in the bucket but don't know how to use the session_key to set the upload location dynamically. I've looked at the docs for django-storages and I can see a way to do this if it wasn't for the fact that I am using a ModelForm. Here is the code I have (I have omitted my settings.py with the bucket name and credentials): storage_backends.py from storages.backends.s3boto3 import S3Boto3Storage class TestS3MediaStorage(S3Boto3Storage): location = 'dev/' default_acl = 'public-read' file_overwrite = False models.py from .storage_backends import TestS3MediaStorage class TestS3Upload(models.Model): uploaded_at = models.DateTimeField(auto_now_add=True) file = models.FileField(storage=TestS3MediaStorage()) forms.py from .models import TestS3Upload class TestS3UploadForm(forms.ModelForm): class Meta: model = TestS3Upload fields = ['file'] views.py from django.shortcuts import render from django.http import HttpResponse from .forms import TestS3UploadForm def test_s3_upload(request): # create session if it doesn't already exist if not request.session.session_key: request.session.create() # not quite sure how to use this to set upload destination session_key = request.session.session_key if request.method == 'POST': form = TestS3UploadForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponse("upload successful!") else: form = TestS3UploadForm() … -
Field Error When Using choices in a Django Model field
After adding one of the model fields to select an option from a list, I get a field error. What could possibly be the cause and the solution to this ERROR: File "/home/chrisdev/code/work/cw-full/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1481, in names_to_path raise FieldError("Cannot resolve keyword '%s' into field. " django.core.exceptions.FieldError: Cannot resolve keyword 'status' into field. Choices are: description, id, image, name, slug MODEL: from django.db import models from django.contrib.auth.models import User # News Model class News(models.Model): DRAFT = 'DRT' PUBLISHED = 'PUB' article_publication_choices = [ (DRAFT, 'Draft'), (PUBLISHED, 'Published'), ] title = models.CharField('News Title', max_length=200, unique=True, help_text='News Heading') slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.SET_NULL, related_name='news', null=True) updated_on = models.DateTimeField(auto_now= True) news_summary = models.CharField('News Summary', max_length=200) content = models.TextField('News Content') created_on = models.DateTimeField(auto_now_add=True) article_publication = models.CharField(max_length=2, choices=article_publication_choices, default=PUBLISHED, ) class Meta: verbose_name = 'News Updates' verbose_name_plural = verbose_name ordering = ['-created_on'] def __str__(self): return self.title -
Performance issue in downloading Static files and assets in django
I have published an app based on Django & react and I'm serving static files from the same server whitenoise take care of that's in my localhost 127.0.0.1:8000 everything work as expected nothing to improve In a production server, I have a lot of loading for images and other static files. I have a mistake or something I missing to implement it? or I need to move all static files to another web server like amazon? I do not know if this question is based on opinions or not, but I really do confusing -
Systemd service file for running django app using docker
I have a Django application running using the docker containers on my local system. I want to start the application on system reboot. So, I decided to write a systemd service file. [Unit] Description=docker_container service [Service] WorkingDirectory=/home/sree/Documents/code/solutions_new/solutions/ ExecStart=/usr/bin/docker /usr/bin/docker-compose -f docker-compose_dev.yml up Restart=always RestartSec=60 [Install] WantedBy=multi.user.target On my system, I usually run the Django app in a virtual environment.Am getting the below error when trying to start the service file docker_container.service - docker_container service Loaded: loaded (/etc/systemd/system/docker_container.service; enabled; vendor preset: enabled) Active: activating (auto-restart) (Result: exit-code) since Sun 2021- 01-24 09:33:49 PST; 9s ago Process: 21241 ExecStart=/usr/bin/docker /usr/bin/docker-compose -f docker-compose_dev.yml up (code=exited, status=125) Main PID: 21241 (code=exited, status=125) -
Trying to make an availability table with multiple inputs in a column
I want to create a table where users register their available hours, but when I click on two or more boxes in the same column the data is overwritten by the latest time. I want to store the values in the database as a list of strings. Is my approach totally wrong? because I believe this is the best and easiest way to do what I want to do. views.py def availability(request): start = datetime(year=1, month=1, day=1, hour=8, minute=00, second=00) time_slots = [] for x in range (0, 29): time_slots.append(str(start.strftime('%-I:%M %p'))) start += timedelta(minutes = 30) x += 1 if request.method == 'POST': sunday = request.POST['sunday'+str(x)] monday = request.POST['monday'] tuesday = request.POST['tuesday'] wednesday = request.POST['wednesday'] thursday = request.POST['thursday'] friday = request.POST['friday'] saturday = request.POST['saturday'] context = { 'if_tutor': UsersUpdated.objects.get(user_id=request.user.pk), 'time_slots': time_slots, } return render(request, 'user/tutor_availability.html', context) HTML {% extends "user/base.html" %} {% csrf_token %} {% block title %}Dashboard{% endblock %} {% block content %} <div class="content"> <div class="inner_content"> <h2 class="title">Availability</h2> <div class="top_line"></div> <form method="POST"> {% csrf_token %} <table> <tr> <th></th> <th>Sunday</th> <th>Monday</th> <th>Tuesday</th> <th>Wednesday</th> <th>Thursday</th> <th>Friday</th> <th>Saturday</th> </tr> {% for time_slot in time_slots %} <tr> <td>{{ time_slot }}</td> <td><input type="checkbox" value="{{ time_slot }}" name="sunday"></td> <td><input type="checkbox" value="{{ time_slot }}" name="monday"></td> … -
Django and React authentications system
I am intermediate Django web developer. I am trying my hands on working with both Django and react at the same time. It's all good if you are using the rest framework, but I am stuck with the authentication system. I love Django built-in UserCreationForm but the solutions(JWT) I find don't seem to utilize Django forms. I tried Django Djoser and Knox; my problem Djoser throw parse error when the password is complex, i.e. include symbols, and both don't utilize Django forms. Note: It's okay if your solution does utilize Django forms, but it's better if it does. I should be able to login to Django admin panel too. I should be able to upload images(profile pic) while registering user. And that's it any help is really appreciated and also English is not my first language, so forgive me if I made any mistake. Thanks -
How to properly do monkey Patching on Django 3.1
i'm currently coding a web application with django 3.0 and trying to override some functions of an installed django apps (Python social auth module). I want to do it because i want to change the default behavior. I have found some method to perform overriding of a module (monkey patching) and try to implement it but i the following errors when i try to implement it : File "/Users/***********/code/recrutlocataire/recrutlocataire/core/__init__.py", line 1, in <module> import core.monkey File "/Users/***********/code/recrutlocataire/recrutlocataire/core/monkey.py", line 6, in <module> from django.contrib.sessions.models import Session File "/usr/local/lib/python3.8/site-packages/django/contrib/sessions/models.py", line 1, in <module> from django.contrib.sessions.base_session import ( File "/usr/local/lib/python3.8/site-packages/django/contrib/sessions/base_session.py", line 26, in <module> class AbstractBaseSession(models.Model): File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 107, in __new__ app_config = apps.get_containing_app_config(module) File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Create my patch in the monkey.py file in my application directory: core/monkey.py from social_core import utils from social_core.exceptions import InvalidEmail from django.core import signing from django.core.signing import BadSignature from django.contrib.sessions.models import Session from django.conf import settings def partial_pipeline_data(backend, user=None, *args, **kwargs): pass Import the monkey file in the init file located in my application directory : core/init.py import core.monkey It seems that I have this … -
HTML video Tag range not working propery in Django
Am creating a small website, where Django returns a movie and the video Tags handles and play the movie. The video Tag plays the movie but the video tag range or slider doesn't work. When i try to move it, it immediately goes back to 0 and the movie restarts. I don't want that, all i want is to move the range and the movie skips according to the range or slider values. I tried this before in Flask it worked fine, but with Django it isn't. Here is are my models class Movies(models.Model): genre = models.ForeignKey(Genres, on_delete=models.CASCADE, null=True, related_name="movie_genre") name = models.CharField(max_length=200) movie_image = models.ImageField(upload_to="movie_images", blank=True) movie_path = models.FileField(upload_to="movie_path", blank=True) description = models.TextField(null=True) author = models.CharField(max_length=200) date_released = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(User, related_name="movie_like", blank=True) favorites = models.ManyToManyField(User, related_name="movie_favorites", blank=True) def __str__(self): return f"Movies('{self.genre.name}, {self.name}','{self.author}', '{self.date_released}')" def total_likes(self): return self.likes.count() def total_favorites(self): return self.favorites.count() def get_absolute_url(self): return reverse('home') Here are my views @login_required def show_movie_data(request, id): movie = get_object_or_404(Movies, id=id) if movie: stuff = get_object_or_404(Movies, id=id) total_likes = stuff.total_likes() liked = False is_favorite = False if stuff.favorites.filter(id=request.user.id).exists(): is_favorite = True if stuff.likes.filter(id=request.user.id).exists(): liked = True context = { 'movie':movie, 'total_likes':total_likes, 'liked': liked, 'is_favorite': is_favorite, } return render(request, 'main/show_movie_data.html', context) else: … -
Django client get: TypeError: __init__() takes 1 positional argument but 2 were given
I have following easy test: class DeviceListTests(APITestCase): def test_devices_list(self): self.user = UserFactory() self.device = DeviceFactory(name="SoundTalks_device") self.client.force_login(self.user) response = self.client.get( reverse("device-list") ) Python/Django is returning an error on: response = self.client.get( reverse("device-list") ) However this is an easy request, I get following error: Traceback (most recent call last): File "/opt/project/integrator_api/devices/tests/test_get_devices.py", line 15, in test_devices_list reverse("device-list") File "/usr/local/lib/python3.6/site-packages/rest_framework/test.py", line 286, in get response = super().get(path, data=data, **extra) File "/usr/local/lib/python3.6/site-packages/rest_framework/test.py", line 203, in get return self.generic('GET', path, **r) File "/usr/local/lib/python3.6/site-packages/rest_framework/test.py", line 232, in generic method, path, data, content_type, secure, **extra) File "/usr/local/lib/python3.6/site-packages/django/test/client.py", line 422, in generic return self.request(**r) File "/usr/local/lib/python3.6/site-packages/rest_framework/test.py", line 283, in request return super().request(**kwargs) File "/usr/local/lib/python3.6/site-packages/rest_framework/test.py", line 235, in request request = super().request(**kwargs) File "/usr/local/lib/python3.6/site-packages/django/test/client.py", line 503, in request raise exc_value File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: __init__() takes 1 positional argument but 2 were given app_1 | app_1 | Aborting on container exit... Stopping integrator-api_app_1 ... Stopping integrator-api_app_1 ... done Process finished with exit code 1 devices/urls.py from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from integrator_api.devices.views.device_list_view import DeviceListView urlpatterns = format_suffix_patterns( [ url(r"^$", DeviceListView, … -
'QuerySet' object has no attribute 'view_count'
Meanwhile using "view count" in my ecommerce project showing this error ('QuerySet' object has no attribute 'view_count') views.py class ProductDetailView(TemplateView): template_name = 'product-detail-view.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) slug_url = self.kwargs['slug'] product = Product.objects.filter(slug=slug_url) product.view_count += 1 product.save() context["products"] = product return context models.py class Product(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) image = models.ImageField(upload_to='products_img') wholesale_rate = models.PositiveIntegerField() amazon_rate = models.PositiveIntegerField() description = models.TextField() warranty = models.CharField(max_length=200, null=True, blank=True) return_policy = models.CharField(max_length=200, null=True, blank=True) view_count = models.PositiveIntegerField(default=0) -
Django ModelAdmin get_form 'NoneType' object is not callable
I am trying to add a new field to ModelAdmin, but get an error: @admin.register(FilmWork) class FilmworkAdmin(admin.ModelAdmin): fields = ('title', 'plot', 'ratings', 'film_creation_date', 'age_limit', 'link') def get_form(self, request, obj=None, **kwargs): form_factory = super(FilmworkAdmin, self).get_form(request, obj, **kwargs) form_factory.base_fields['Actors'] = forms.CharField(widget=forms.Textarea(), required=False) The error says: form = ModelForm(initial=initial) TypeError: 'NoneType' object is not callable I do not initialise any modelform anywhere. What am I doing wrong? -
django drf testing social oauth2 with google
I'm trying to test drf-social-oauth2's integration with Google via python manage.py test with the following test class: class DRFSocialOAuthIntegrationTest(TestCase): def setUp(self): self.test_user = UserModel.objects.create_user("test_user", "test@user.com", TEST_USER_PASSWORD) self.application = Application( name="Test Application", redirect_uris="", user=self.test_user, client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_PASSWORD, # https://github.com/jazzband/django-oauth-toolkit/blob/master/oauth2_provider/models.py ) self.application.save() # Every test needs a client. self.client = Client() def tearDown(self): self.application.delete() self.test_user.delete() def test_drf_social_oauth2_integration(self): '''Following testing steps found at curl -X POST -d "grant_type=convert_token&client_id=<django-oauth-generated-client_id>&client_secret=<django-oauth-generated-client_secret>&backend=google-oauth2&token=<google_token>" http://localhost:8000/auth/convert-token''' def convert_google_token(self): ''' Convert Google token to our access token curl -X POST -d "grant_type=convert_token&client_id=<client_id>&client_secret=<client_secret>&backend=google-oauth2&token=<google_token>" http://localhost:8000/auth/convert-token ''' return self.client.post( '/auth/convert-token', { 'grant_type': 'convert_token', 'client_id': self.application.client_id, 'client_secret': self.application.client_secret, 'backend': 'google-oauth2', 'token': <google_token> } ) That seems to work fine, but I have to keep feeding it the google_token by manually navigating to https://developers.google.com/oauthplayground/?code=<my_code>&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+openid&authuser=0&prompt=consent#: Once there, I click on the 'Exchange authorization code for tokens' button, get the access token, and paste that access token into the tokenparameter of the request inside convert_google_token(). This doesn't feel very automated. I'm not sure if I should just click the checkbox so that the access token is refreshed automatically and therefore never have to edit it in convert_google_token(). Or maybe I'm supposed to get that access token programmatically. But I believe that would entail getting the authorization code first, which …