Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Ajax form submission get 500 Internal Server Error: TypeError at /articles/test_1 get() got an unexpected keyword argument 'id'
Currently I'm trying to realize "Add comments" funtion for my website through ajax submission. But I always get 500 Internal Server Error when I submit comments. I checked Chrome console and found it says "TypeError at /articles/test_1 get() got an unexpected keyword argument 'id'" (here test_1 is the slug of the article). I'm confused about this error. Could anyone please help me about this? My models.py: class Article_comments(models.Model): post = models.ForeignKey(Article, on_delete=models.CASCADE) nicknames = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='UserProfile_nickname') comment = models.TextField(max_length=3000) timestamp = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Article comments' verbose_name_plural = verbose_name ordering = ['-timestamp'] def __str__(self): return '{}-{}'.format(self.post.article_ti, str(self.nicknames.nickname), self.nicknames.avatar, self.nicknames.qq, self.nicknames.motto, self.nicknames.create_time, self.nicknames.user_url) My views.py def article_details(request, slug): article_detail = get_object_or_404(Article, slug=slug) comments = Article_comments.objects.filter(post=article_detail).order_by('-timestamp') paginator_comment = Paginator(comments, per_page=5) page_var = 'page' page = request.GET.get(page_var, 1) try: sets = paginator_comment.page(page) except PageNotAnInteger: sets = paginator_comment.page(1) except EmptyPage: sets = paginator_comment.page(paginator_comment.num_pages) # Here is the ajax code: if request.method == 'POST': if request.is_ajax(): user = request.user usr_nc = UserProfile.objects.filter(usr=user) cmt_user = usr_nc cmt_art_id = request.POST.get('article_id') cmt_body = request.POST.get('body') article = request.POST.get(id=cmt_art_id) slug = slug comments = Article_comments.objects.create(nicknames=cmt_user, comment=cmt_body, post=article) comments.save() return JsonResponse({'msg': 'Comments successfully submitted!'}) article_detail.view_sum() return render(request, 'article_detail.html', {'article_detail':article_detail, 'comments':comments, 'sets':sets, 'page_var':page_var}) My app/urls.py: path('articles/<str:slug>', article_details, name='article_url') My … -
Are there disadvantages of using __slots__?
I'm using Python 3.7 and Django. I was reading about "_slots__" -- http://book.pythontips.com/en/latest/slots__magic.html . Evidently, _slots can be used to optimize memory allocation for a large number of those objects by doing this ... class MyClass(object): __slots__ = ['name', 'identifier'] def __init__(self, name, identifier): self.name = name self.identifier = identifier self.set_up() My perhaps obvious question is why wouldn't we want to do this for all objects? Are there disadvantages for using _slots__? -
How to initiate User in SetPasswordForm via Django FormView CBV?
I have the following view which utilizes the built-in SetPasswordForm from Django. The form itself requires you to initialize it with a User (settings.AUTH_USER_MODEL) when creating it. The view validates uid/token get parameters (or allows authenticated users) and then presents the user with a form. I have the GET request creating the form correctly, but is there a better way? What would be the best way to set what is currently self.init_user in the POST request: add user.pk as a hidden field to the SetPasswordForm or set a sessions object? from django.views.generic.edit import FormView from django.contrib.auth.forms import SetPasswordForm class PasswordResetView(FormView): """ Reset user password. Either with provided uid/token get parameters or if the user is logged in. """ template_name = 'users/password_reset.html' form_class = SetPasswordForm success_url = 'home' init_user = None def corrupt_link_redirect(self, request): messages.error( self.request, user_strings.PASSWORD_RESET_INVALID_LINK ) return redirect('forgot_password') def get_form(self): form_class = self.get_form_class() if not self.init_user: return Http404() ## Refine this return form_class(self.init_user, **self.get_form_kwargs()) def post(self, request, *args, **kwargs): ## ***************************** ## EITHER NEED TO INCLUDE THE USER.PK IN THE SetPasswordForm OR ## PUT IT IN A SESSION SO WE CAN SET self.init_user TO PREVENT ## THE get_form() METHOD FROM 404'ING ## ***************************** return super(PasswordResetView, self).post(request, *args, **kwargs) def … -
Unauthorized on only part of a Viewset
I have been pulling my hair out at this one. I am trying to leverage my Django Rest API in a React Native Project. For some reason, when I try get a detail view from the following viewset it returns a 401 Unauthorized error: class TestViewset(viewsets.ModelViewSet): depth = 2 serializer_class = TestSerializer def get_serializer_class(self): if self.action == 'create': return UserTestSerializer if self.action == 'list': return TestListSerializer return TestSerializer def get_queryset(self): return Test.objects.filter(owner=self.request.user) def perform_create(self, serializer): serializer.save(owner=self.request.user) populate_test(serializer.instance) filterset_fields = ('complete',) However, when I look at the detail view via a web browser with the built in explorer this works fine. Further, and most importantly, I am able to perform a get against the list view but not the detail. Such that, api/v1/tests/ works api/v1/tests/ca696375-eb59-4754-9070-72cdb124eeb8/ 401 error Any ideas? -
How do I combine my react server with django server using server sided rendering?
When I deploy my django project with python manage.py runserver, and my react app with npm start, I don't know which one is my "real project". I think the question boils down to client sided rendering vs server side rendering, and for now I want to go with server side rendering as I am more familiar with django than I am with react. That would mean I would have to set up urls and views with django/drf correct? If so, my questions are as follows... How do I "invoke" react whenever I go to a url (for example, website.com/items). I want to return a list of all my items in a nicely formatted html file. I suspect this has to do with a template parameter in the path() function. How do I prevent users from accessing api views (website.com/api/items), which is the url I use to handle api calls with django-rest-framework, but I don't want people to see this but also want react to "see" this. Because I am doing server side rendering, is there any there anything else my react app needs to do other than do the correct http calls to my api urls and making my html … -
How to install sql functions in startup of django app
I have an app that uses sql functions for some of its queries. For now, I've written an installation function that installs the sql functions through a cursor: def install_all(): install(FUNC1) install(FUNC2) install(FUNC3) def install(script): with connection.cursor() as cursor: cursor.execute(script) I've added a call to install_all() inside one of the project's __init__.py so that every time the project is run, it reinstalls the functions (in case they've changed.) I really do not want to do this with manual migrations. The problem I had recently is that this creates an open connection to the db and prevents things like manage reset_db from working because of an open connection. Even manage dbshell opens up with an existing connection to the db from the cursor. Presumably the cursor executes, the socket isn't closed, and the exec'ed psql inherits the still open socket. For now I've changed it to: from django.db import connection def install_all(): install(FUNC1) install(FUNC2) install(FUNC3) connection.close() ...and this works but seems heavy handed. Is there an explicitly supported way this startup code can be incorporated into a Django App? version: Django 1.11 -
How to combine/mix object level and user level permissions in DRF?
I am currently working on a DRF project where Admin users, Teacher users and Owner users should be able to have access to an objects detail-view. Basically all user types except those who are not the owner of the object or a teacher or an admin user. I am able to implement the separate permissions for each, but when I need to combine these permissions on a view I hit a roadblock because the user level perms are checked before object level perms. Thus I cannot use boolean operands to combine them and I have to write these ugly permission classes for my views. My question is: How can I implement these permissions on my detail-view in a cleaner way or, alternatively, is there a cleaner way to obtain my result? As you will see, I violate DRY because I have an IsAdminOrOwner and IsAdminOrTeacherOrOwner perm. You will also note in my view that I overwrite get_permissions() to have appropriate permission classes for the respective request methods. Any comments on this and other implementations are welcome, I want critique so that I can improve upon it. Here follows permissions.py: from rest_framework import permissions from rest_framework.permissions import IsAdminUser class IsOwner(permissions.BasePermission): def … -
how to receive username with token by django rest authetication?
I am using django Django=2.1.7 and rest framework djangorestframework=3.9.2 This is my url for login path('rest-auth/login', include('rest_auth.urls')), When I enter username and password I got the token from rest API. But I want my user detail like name, id etc to show in my react components. Please help me how to figure achieve. I have seen many answers on StackOverflow even the official documentation is not descriptive https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication -
F expression not working to update my model in database
I have a django model which has a field counter. Every time I am calling the List view, I's like to update this field, incrementing it by one. I am trying to do this with an F expression. According to other questions here and to the django docs, something like this should do the trick: my model: class Job(models.Model): skills = models.TextField(blank=False, default="Skills") counter = models.IntegerField(default=0) my view: class ListJobView(ListView): model = Job context_object_name = 'jobs' template_name = 'list_jobs.html' ordering = '-pub_date' # paginate_by = 1 def increment_counter(self): count = Job.objects.get_or_create(id=66) count.counter = F('counter') + 1 count.save(update_fields=["counter"]) Unfortunately, this is not working. Is there something obvious that I am doing wrong? Also, I would like to update all of the counters for every job. But count = Job.objects.all() also does not work. Any suggestions or hints? That would be great, thanks in advance! -
Retrieve property from array property into pymongo object
How to retrieve contactos.0.direcciones.0.id property with pymongo y django Framework? { "_id" : ObjectId("5cb8c6827033b71491a296e3"), "id" : NumberInt(89), "contactos" : [ { "id" : NumberInt(1), "nombre" : "", "direcciones" : [ { "id" : NumberInt(1), "calle":"Street 1" } } ] } this code run for contactos.id and retrieve the max id value for contactos use esco_mongo; db.getCollection("clientes").aggregate( [ { "$match" : { "id" : NumberInt(89) } }, { "$project" : { "_id" : 1.0, "contactos.id" : 1.0 } }, { "$unwind" : { "path" : "$contactos" } }, { "$sort" : { "contactos.id" : -1.0 } }, { "$limit" : 1.0 } ], { "allowDiskUse" : false } ); but if i change to contactos.direcciones.id dont retrieve results : use esco_mongo; db.getCollection("clientes").aggregate( [ { "$match" : { "id" : NumberInt(89) } }, { "$project" : { "_id" : 1.0, "contactos.direcciones.id" : 1.0 } }, { "$unwind" : { "path" : "$contactos.direcciones" } }, { "$sort" : { "contactos.direcciones.id" : -1.0 } }, { "$limit" : 1.0 } ], { "allowDiskUse" : false } ); Its possible retrive the values form the direcciones array in one query to mongodb database? Thanks in advance -
User Registration and Login in 1 view
I am trying to create a page where login and registration are in the same template in django, the login form is working correctly but the registration form is not submitting the registration form is not validated in the views i have tried using django's in build UsercreationForm but that doesn't work either views.py def login_register(request): if request.method == "POST": form_log = UserLoginForm(data=request.POST or None) form_reg = UserRegistrationForm(data=request.POST or None) if 'sign_up' in request.POST: if form_reg.is_valid(): user = form_reg.save(commit=False) password = form_reg.cleaned_data.get('password1') user.set_password(password) user.save() login(request, user) return redirect('network:homepage') elif 'sign_in' in request.POST: if form_log.is_valid(): username = form_log.cleaned_data.get('username') password = form_log.cleaned_data.get('password') user = authenticate(request, username=username, password=password) login(request, user) if user is not None: login(request, user) return HttpResponseRedirect(reverse('network:homepage')) else: form_reg = UserRegistrationForm() form_log = UserLoginForm() return render(request,"network/bothpage.html", {'form_reg': form_reg, 'form_log': form_log}) forms.py lass UserLoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Username'}), label='Username') password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'}), label="Password") class Meta: model = User fields = ['username', 'password'] def clean(self, *args, **kwargs): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError('This user does not exist') if not user.check_password(password): raise forms.ValidationError('Incorrect Password') if not user.is_active: raise forms.ValidationError('User is Not active') return super(UserLoginForm, self).clean(*args, **kwargs) class UserRegistrationForm(forms.ModelForm): username = … -
Django - Can a crispy form be split into 2 columns?
I'm trying to split a crispy layout form into 2 columns to try and eradicate the need to scroll, I've tried to use formhelper in forms.py to put 2 questions in a DIV but that doesn't change anything. Does anyone have any ideas? Forms.py class ProfileUpdateForm(forms.ModelForm): address = forms.CharField() dob = forms.DateField( widget=forms.TextInput( attrs={'type': 'date'} ), label='Date of Birth' ) helper = FormHelper() helper.layout = Layout( Div( Div('fullname', css_class='col-md-6',), Div('dob', css_class='col-md-6',), css_class='row', ), Div( Div('address', css_class='col-md-6',), Div('city', css_class='col-md-6',), css_class='row', ), Div( Div('country', css_class='col-md-6',), Div('profilephoto', css_class='col-md-6',), css_class='row', ), ) class Meta: model = Profile fields = ['fullname', 'dob', 'address', 'city', 'country', 'profilephoto'] labels = { 'fullname': 'Full Name', 'address': 'Address', 'city': 'City', 'country': 'Country', 'profilephoto': 'Profile Photo', } Current State -
How do I use data stored in database model in a calculation and then store the result of a calculation in a django model field?
I'm working on my first Django app, and I need to take the data inputted by a user in my models fields, insert it into a function that makes a calculation using that data, and then returns the value of that calculation to my model where it is then stored. It is not essential that the result be stored in my database, however I will need to use the resulting figure later on to allow the app to determine which data to present to the user. I have my model class in models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) age = models.IntegerField(default=18) gender = models.CharField(max_length=6, choices=gend, default='') weight = models.IntegerField(default=0) height = models.IntegerField(default=0) and my function in a services.py file: def caloriefunction(): weight = Profile.weight height = Profile.height age = Profile.age isMale = Profile.gender if isMale == "Male": isMale = True elif isMale == "Female": isMale = False else: print("Error") quit() if isMale: bmr = 66.5 + (13.75 * weight) + (5 * height) - (6.755 * age) else: bmr = 655.1 + (9.6 * weight) + (1.8 * height) - (4.7 * age) bmr = round(bmr) return bmr How would I get the resulting value and then store it … -
The current path, didn't match any of these - Django
the page http://127.0.0.1:8000/category.html/ throws a 404, saying Using the URLconf defined in ddblog2.urls, Django tried these URL patterns, in this order: admin/ ^ [name='index'] ^ category [name='category'] The current path, category.html/, didn't match any of these. ddblog2/ddblog2/urls.py is as follows: from django.conf.urls import url, include from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), url(r'^', include('blog.urls')), ] ddblog2/blog/urls.py is as follows: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('category/', views.category, name = 'category') ] ddblog2/blog/views.py: from django.shortcuts import render def index(request): return render(request, 'index.html', {}) def category(request): return render(request, 'category.html', {}) 'blog' has been added to the INSTALLED_APPS how do I correct this error? -
Unable to Mock REST API function with Python Mock in Django
I have an API which use ElasticSearch to get data. I have to write test cases for this. These tests will be run using Circle CI. When we run test cases on test cases on Circle CI, test failed as ElasticSearch is not installed on Circle CI. Now we want to Mock ElasticSearch in order to successfully executing tests. The problem is that we have to write test cases for APIs and in our tests, we are calling API using unit test requests. But we want to mock ElasticSearch which being accessed in our API. We tried to run our test cases by directly calling our view but it does not work. Below is our code. class Test_api(TestCase): @mock.patch("src.chart.views.MyView.my_function_to_mock", MagicMock(return_value='return value')) def setUp(self): self.user = User.objects.create_user('foo', 'foo@bar.de', 'bar') self.request = APIRequestFactory() def test_my_api(self): view = MyView.as_view() request = self.request.get('/api/abc/') force_authenticate(request, user=self.user) response = view(request) self.assertEqual(response.status_code, 200) self.assertEqual(response.data, 'return value') When we run this test case, our required function is not get mocked. Can any one guide us how we can Mock our function in our Rest API? -
Unable to get user id with token by django rest framework?
I am using django Django=2.1.7 and rest framework djangorestframework=3.9.2 This is my url for login path('rest-auth/', include('rest_auth.urls')), After authentication I got token but I need user id too. I tried to override the post method of rest_framework.authtoken.views.py file with the following code def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) context = { 'token': token.key, 'user': user.id } return Response({'context': context}) Please help me figure out how to get user id with the token. This is my college project. Note: I find many answers on stack overflow but none is helpful. -
Problem with customising upload path for ImageField and FileField in Django 2.2
I created a function outside the model to be used as a utility function that would work with any method by just passing a path string to it and it would return the file path plus a renamed filename. The function(instance, filename) that changes the filename is wrapped inside a wrapper function that would accept the path string. Here is the function (stored in helpers.py in another app): def path_and_rename(path): """ Returns wrapper func :param path: path string with slash at the end :return: func """ def wrapper(instance, filename): """ Returns a filename string, both and filename, with filename as an md5 string :param instance: model instance with the file_field or image_field :param filename: filename as uploaded (as received from the model) :return: str """ ext = filename.split('.')[-1] # Preserve image file extension md5_file_name = f"{hashlib.md5(str(filename).encode('utf-8')).hexdigest()}.{ext}" # md5 from filename return f"{path}{md5_file_name}" return wrapper And in my models i've done the following: image = ImageField(verbose_name=_("Product image"), upload_to=path_and_rename("products/images/")) But this is producing an error upon makemigrations: 'Could not find function %s in %s.\n' % (self.value.__name__, module_name) ValueError: Could not find function wrapper in my_app_root.core.helpers. -
Is there a way to allow users to change their Active Directory password with Django
I'm setting up a simple django webpage that helps users to update/change their Active directory password We get a-lot of requests from users to reset their domain passwords(Active directory), in which we as the Administrators log in to the AD tool and reset their passwords, sharing with them over the call or email, I wanted to create a simple Django website the links to the AD in which the user resets their password by themselves -
Passing user-entered data to Queryset.filter() - is it safe?
I have a page which takes GET parameters from its url, and passes these directly to a REST API. So the page URL looks like: foo.com/pizzas/?toppings=mushrooms&toppings=sausage As the page loads, it will take the GET params and pass them to a REST API like: foo.com/totally/unrelated/url/?toppings=mushrooms&toppings=sausage On the backend, I want to extract these out and filter based on them. This is basically what I have right now: # inside a django rest framework ModelViewSet # it's not really relevant other than that self.request exists def get_queryset(self): queryset = self.model.objects.all() for param in self.request.query_params: # param = "toppings" if not self.is_real_model_field(param): # assume this works continue param_value_list = self.request.query_params.getlist(param) # param_value_list = ['mushrooms', 'sausage'] queryset = queryset.filter( f"{param}__in": param_value_list ) return queryset So, is this safe to do in Django? A malicious actor could directly manipulate the URL. I assume that django's QuerySet.filter(field__in: values) will automatically do some cleaning for you, and/or the limited character set of a URL will help stop anything nasty from coming through, but I haven't been able to find any resources discussing the issue. -
Django ORM add variable instead .filter directive
In my project i have a function with django ORM query inside. I would to pass into the .filter parth a list o values passed to the function: def testFilter(filterlist): #for example filterlist could be: thread='DEAD',id=11,t_type='SA' myquery = t_threads.objects.filter(filterlist).select_related().order_by(lorder)[x:y] but if i , for example run my function: testFilter("id=1,thread='LIVE'") i got an error: ValueError: too many values to unpack (expected 2) How i can run my ORM query passing the filter directive every time i run the function? So many thanks in advance -
field must be unique on OneToOne field in Django DRF
I'm using Django 2.x and DRF. I have a model to save rating for each entity class UserRideRating(models.Model): user_ride = models.OneToOneField(UserRide, on_delete=models.CASCADE, related_name='user_ride_rating') rating = models.PositiveIntegerField( validators=[validate_rating_range] ) and serializers.py class UserRideRatingSerializer(serializers.ModelSerializer): class Meta: model = UserRideRating fields = ('id', 'user_ride', 'rating') I have a view to create rating object if not already exists or update the rating if already exists. Also, I want to check validation using default Serializer validation and thus my view is like @api_view(['POST']) def rate(request): serializer = UserRideRatingSerializer(data=request.data) if serializer.is_valid(raise_exception=True): # create or update data return Response(serializer.data) When on passing data from the postman, it gives an error as { "user_ride": [ "This field must be unique." ] } How can I enable check for only valid data and not the uniqueness of the field? Although user_ride should be unique, it can pass in the request data. -
Compile SASS/SCSS files on Heroku in Django app
I am getting an error when DEBUG is set to False or unset in Heroku, in Django app, when I activate logs. ValueError: Missing staticfiles manifest entry for 'css/sass/home.css' Seems that my SCSS files are not compiled when I deploy on Heroku, while it compiles automatically locally with django-sass-processor -
Best way to implement users who can edit model in Django
In Django, I have a model Artists, and a custom User model with a UserManager class: class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Creates and saves a new user""" if not email: raise ValueError("Users must have an email address") user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) # required for supporting multiple databases return user def create_superuser(self, email, password): """Creates and saves a new superuser""" user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): """Custom user model that supports using email instead of username""" email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "email" @property def full_name(self): return f'{self.first_name} {self.last_name}' I want superusers, staff users, and the artist themselves to be able to edit the artist model. What is the best way to do this? I'm thinking of adding a field to my artist model like so: users_who_can_edit = models.ManyToManyField(user=get_user_model()) but I'm guessing I implement a filter in the view? -
AttributeError: 'NoneType' object has no attribute 'get' even though I have an instance of the class I'm using
When I run my test, which is the following: def test_match_data_while_updating(self): match_updated_data = { 'id': 1, 'status': 'not_started', } match = Match.objects.first() # TST N.1 : status not_started # ------- match.status = 'not_started' request = self.__class__.factory.put('', match_updated_data, format='json') add_authentication_to_request(request, is_staff=True) response = update_match_video(request) self.assertEqual(Match.objects.first().status,'live') I get the Error that says: print('request data get match: ',request.data.get('match').get('id')) AttributeError: 'NoneType' object has no attribute 'get' Here is the function I'm testing: def update_match_video(request): print('request data get match: ',request.data.get('match').get('id')) if not request.data.get('match').get('id'): return JsonResponse({}, status=status.HTTP_400_BAD_REQUEST) try: match_id = valid_data_or_error(request.data, method='PUT')['match_data']['id'] match = Match.objects.get(id = match_id) db_match_status = match.status if db_match_status == 'live': valid_data_or_error(request.data, method='PUT')['match_data']['status'] = 'live' else: if db_match_status == 'closed': valid_data_or_error(request.data, method='PUT')['match_data']['status'] = 'closed' except Match.DoesNotExist: print('Match does not exist') I will appreciate some help please! -
Draw 2D in HTML or Python
I need to draw multiple rows of boxes programmatically with text content using HTML5, CSS, JS or Python. What can you recommend as best and most flexible solution to generate such images: Are there any libraries you can recommend to build my software?