Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Queryset getting a sequence of objects instead of result of a Sum
I'm trying to perform a Sum of different rows of the Model according to specific column values, in this case I want to Sum according to a week and an specific car, so for example: Car Week Payment 1 2020-W06 $500 1 2020-W06 $300 2 2020-W06 $200 1 2020-W05 $500 So I pass to the query the car & the week and it should get the sum of the payments according to those values I pass Car = 1 and Week = 2020-W06 and Payment Sum = $800 this is my queryset: payed = Pagos.objects.filter(carro_id=1, semana=semana).annotate(total=Sum('pago')) and thi is the result I'm getting: <Pagos: Pagos object (6)>, <Pagos: Pagos object (12)>] I don't understand why I don´t get the Sum models.py class Pagos(models.Model): carro = models.ForeignKey( Carros, on_delete=models.CASCADE, blank=False, null=False) pago = models.DecimalField(max_digits=6, decimal_places=2) fecha = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) semana = models.CharField(max_length=20) startweek = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) endweek = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) renta = models.ForeignKey( Renta, on_delete=models.PROTECT, blank=False, null=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Pagos" def get_absolute_url(self): return reverse('pagos') class Carros(models.Model): nombre = models.CharField(max_length=20, blank=True, null=True) marca = models.CharField(max_length=25) modelo = models.CharField(max_length=25) year = models.IntegerField() placa = models.CharField(max_length=10, unique=True) … -
TypeError: useroptions() missing 1 required positional argument: 'self'
I have following model - class Userdetails(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, blank=True, null=True) userno = models.CharField(max_length=200, blank=True, null=True) and following view.py - @api_view(['GET', 'POST']) def useroptions(request): if request.method == 'POST': count = Userdetails.objects.count() serializer = userdetailsSerializer(data=request.data) names = Userdetails.objects.values("name") if serializer.is_valid(): if count < 5: serializer.save() Userdetails.objects.filter(name = serializer.data["name"]).update(userno = userno) new_nam = request.data["name"] self.new_count = new_count self.new_nam = new_nam # using raw query over this with connection.cursor() as cursor: cursor.execute("UPDATE dynapp_userdetails SET id = %d WHERE name = %s", [self.new_count, self.new_nam]) row = cursor.fetchone() print("row raw query") print(row) This gives me the following error - TypeError: useroptions() missing 1 required positional argument: 'self' Here I want to use RAW QUERY to update the data from table. Since I am using UPDATE for PK value thus I have to use RAW QUERY. Simple UPDATE function to update PRIMARY KEY gives error of - Internal Server Error: /view/pardel/2/multiuser django.db.utils.IntegrityError: (1062, "Duplicate entry '4' for key 'PRIMARY'") Thus after many search I got above syntax for RAW QUERY to UPDATE Primary Key. Please give me solution to UPDATE Primary Key except this use in the above code. Also please resolve the query. -
React Django CORS not working : has been blocked by CORS policy
I've tried all the possible combinations of CORS between react and django api. it is still not working. im getting this error has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'todos' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = False view.py class StuffViewSet(APIView): def post(self, request): serializer = StuffSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(data = "data saved", status=status.HTTP_201_CREATED) return Response(data = "data not saved", status=status.HTTP_400_BAD_REQUEST) def get(self, request): snippets = Stuff.objects.all() serializer = StuffSerializer(snippets, many=True) return Response(data = json.dumps(serializer.data)) I am calling the api from react like this getAPI(e) { const headers = { 'Content-Type': 'application/json', "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET,OPTIONS,POST,PUT" } axios.get('http://localhost:8000/api', { headers: headers }).then(function(response) { console.log("/api") console.log(response.data) }); } what did I do wrong here ? -
Django error_messages always displayed in form after overriding
I've overridden Django's built-in password_mismatch error for password reset confirmation. In my template, the error is always shown as soon as it is loaded. The password reset procedure works smoothly, but I can't get rid of the error being shown before I've even entered anything. How can I do this? My code is shown below. forms.py class PasswordResetConfirmationForm(SetPasswordForm): new_password1 = CharField(max_length=35, required=True, widget=PasswordInput, error_messages={'required': 'Please do not leave blank.'}) new_password2 = CharField(max_length=35, required=True, widget=PasswordInput, error_messages={'required': 'Please do not leave blank.'}) error_messages = { 'password_mismatch': 'The two passwords should never match.', } views.py class PasswordResetConfirmationView(PasswordResetConfirmView): form_class = PasswordResetConfirmationForm def password_reset_confirm(self): return render(self.request, 'accounts/registration/password_reset_confirm.html') form in password_reset_confirm.html <form method="post" novalidate="novalidate" class="popup-form empty-form"> {% csrf_token %} <label for="{{ form.new_password1.id_for_label }}">Password</label> {{ form.new_password1.errors }} {% render_field form.new_password1 placeholder="New password" %} <label for="{{ form.new_password2.id_for_label }}">Re-enter password</label> <p>{{ form.error_messages.password_mismatch }}</p> {% render_field form.new_password2 placeholder="New password again" %} <input type="submit" value="Change password"> </form> -
"This field cannot be blank" even if the field is not empty?
models.py: class Test(PolymorphicModel): title = models.CharField(max_length=300) forms.py: class RestaurantForm(forms.ModelForm): class Meta: model = Test fields = [ 'title', ] def clean_title(self, *args, **kwargs): title = self.cleaned_data.get("title") if len(title) < 3: raise forms.ValidationError("Please, enter at least 3 symbols!") Okay, when try to submit the form with text, like "aa" it shows error "Please, enter at least 3 symbols!" it works fine, but when add more than 3 symbols it returns me This field cannot be blank which comes from Model, because there is no blank=True, but field is not empty, I'm confused. -
DRF - JWT How to fix Token still active after expired?
I'm using Djangorestframework with djangorestframework-simplejwt library, the token system is working except that after an access and refresh token are both expired ( I can confirm with postman ) the frontent app (Vue & axios) is able to still GET the updated data, how is this possible? When i check the axios request the token is the same as the one I use in postman, in Postman it gives me "Token Invalid or expired" but in axios it receives all the data and 200 OK. These are the configs: settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60), 'REFRESH_TOKEN_LIFETIME': timedelta(hours=24), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'AUTH_HEADER_TYPES': ('JWT',), 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', } urls.py from rest_framework_simplejwt.views import TokenRefreshView from dgmon.views import MyTokenObtainPairView app_name = 'dgmon' admin.site.site_header = settings.ADMIN_SITE_HEADER admin.site.site_title = settings.ADMIN_SITE_TITLE urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^', include('dgmon.urls')), path('api/token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] views.py from rest_framework_simplejwt.views import TokenObtainPairView from dgmon.serializers import MyTokenObtainPairSerializer class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer serializers.py from rest_framework_simplejwt.serializers import TokenObtainPairSerializer class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) refresh = self.get_token(self.user) data['refresh'] = str(refresh) data['access'] = str(refresh.access_token) data['user'] = self.user.username data['groups'] = self.user.groups.values_list('name', flat=True) return data -
Best approach for Django+Heroku+Scrapyd(or Scrapy + Celery)
I have django project and I need to add scraping to it. It will be a spider which will be available for each user from interface - one spider but different inputs. The app is on Heroku. I've tried to use Scrapyd and it works fine. But the problem is that it's not possible to deploy the app and the scrapyd server on the same host. As I understand it's needed to create separate host, deploy scrapyd there and run spider on that host. As I understand, there is another option. To write custom spider scheduler with Scrapy and Celery. So, the questions is: what's the best approach for that situation? Is it ok to use Scrapyd on a separate host or I have to write my own scheduler? -
A new user can login after registering until i manually change the password in admin console
I do not know what's happening with the user login, when a user registers, everything is saved in the database when I check the admin console, but when the user wants to log in it doesn't authenticate the password. But if I go to the admin console and manually change the user password even to the same password that the user registered with then, then the user login will in successfully. I tried this like 10 times, it won't authenticate the user until I manually change the password. I hope to get a response soon because I have gone over my codes severally. `Below is my views.py. Thank you. from django.contrib.auth.models import User from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from newapp import forms from django.contrib.auth import authenticate, login, logout from django.urls import reverse from django.contrib.auth.decorators import login_required def userreg(request): form = forms.UserInfoForm() otherform = forms.UserProfileInfoForm() registered = False newname = False if request.method == "POST": form = forms.UserInfoForm(data=request.POST) otherform = forms.UserProfileInfoForm(data=request.POST) if form.is_valid() and otherform.is_valid(): newname = form.cleaned_data.get('first_name') user = form.save() user.set_password(user.password) user.save() profile_form = otherform.save(commit=False) profile_form.user = user if 'profile_pic' in request.FILES: profile_form.profile_pic = request.FILES['profile_pic'] profile_form.save() registered = True return render(request, 'newapp/register.html', context={'form': form, 'otherform':otherform, 'newname':newname, … -
How to modify a models who's already migrated in Database?
I am new to django, I want to modify my models (Which is already in my sqlite3 database) without bugging my entire project. Last time I modified my models it took me hours to fix it cause I bugged the whole project. So I dont want to make the same error, could you guys help me witht the commands please? Thanks for helping models.py (at the moment) from django.db import models THE_GENDER = [ ("Monsieur", "Monsieur"), ("Madame", "Madame") ] class Post(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=100) gender = models.CharField(max_length=8, choices=THE_GENDER) number = models.CharField(max_length=100) def __str__(self): return self.name The edit that I want to make to the models (I want to add an author user into the models. So i know whos making the form.) from django.db import models from django.contrib.auth.models import User THE_GENDER = [ ("Monsieur", "Monsieur"), ("Madame", "Madame") ] class Post(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=100) gender = models.CharField(max_length=8, choices=THE_GENDER) number = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name my admin.py files (not sure If ill need to leave it the same or modify it) from django.contrib import admin from .models import Post admin.site.register(Post) my forms.py files from django import forms from .models import Post … -
Django include template, overwrite 'self' variable?
I've been tasked to fix a template structure in a Django app. I am not very familiar with Django as I deal mostly with front end projects built in React. The Django app is using Wagtail as a backend CMS. I am looping through it's pages, and including a template block and trying to pass variables with the with statement on the include. I can successfully pass variables to the template block, but I need to overwrite the 'self' variable as the template block is looking for self.something. Here is what my template looks like. {% load static wagtailimages_tags wagtailcore_tags %} <div class="c-card {% if self.variant %}c-card--{{ self.variant }}{% endif %}"> {% if self.image %} {% image self.image original class="c-card__image" loading="lazy" %} {% endif %} {% if self.title %} <h3 class="c-card__title">{{ self.title }}</h3> {% endif %} {% if self.text %} <p class="c-card__content">{{ self.text }}</p> {% endif %} {% if self.button.title and self.button.url %} {% include './button_block.html' with button=self.button %} {% endif %} </div> and then there is the loop and include snippet... {% for chapter_menu in page.chapters %} <div class="medium-6 large-4 columns"> {{ chapter_menu.value.title }} {% include './blocks/card_block.html' with self=chapter_menu.value %} </div> {% endfor %} Doing this self=chapter_menu.value results in … -
How to log in on API-level with django-hosts subdomain and DRF
I'm using django-rest-framework (DRF) to have a browsable API which shall be available under the api subdomain e.g. api.localhost:8000. To serve subdomains, I'm using django-hosts. I'm having trouble to achieve login and logout functionality on API level (i.e. under the api subdomain). The subdomains work but I can't get the DRF autentication mechanism to work anymore. Problem Visiting api.localhost:8000/ shows the browsable api page which is fine. The DRF Log in button is also available. Using this button shows the log-in form, but when submitting the form, I'm redirected to http://login/ which of course can't be resolved and thus the login fails. The same applies to the logout functionality, which leads to http://logout/ and also fails. Below are screenshots for these steps. Django Settings ROOT_URLCONF = "server.urls" ROOT_HOSTCONF = "server.hosts" DEFAULT_HOST = "api" django-hosts configuration # server/hosts.py from django_hosts import patterns, host from django.conf import settings host_patterns = patterns( '', host(r"api", "server.api_urls", name="api"), host(r"admin", "server.admin_urls", name="admin"), host("", settings.ROOT_URLCONF), # resolves to server/urls.py ) URLS configuration # server/urls.py from django.urls import include, path # this is my root url conf urlpatterns = [ path("", include("server.api_urls")), path("", include("rest_framework.urls", namespace='rest_framework')), path("", admin.site.urls), ] I'm not happy with this, but even though I serve … -
Django: Find all one_to_one relations from queryset
I have a queryset of users, which are instances of the model User. A second model called Patient has a OneToOneField named user: user = OneToOneField('users.User', on_delete=CASCADE, related_name="patient", blank=True, null=True) The goal is to get a queryset of all patients from the queryset of users. I thought that by using the related_name would be enough, meaning: queryset_of_users=users queryset_of_patients=users.patient but it seems this is not it since I get the following error: AttributeError: 'QuerySet' object has no attribute 'patient' Any ideas? -
Django project beginner
Currently I am learning django. I want to open some github basic projects on django. But I am not able to open it on my ide. Can anyone help with a proper step by step guide? My ide is pycharm professional -
Django deleting not working, 'Notification' object has no attribute '__unicode__' [duplicate]
I have a project that was working on django 1.8 and python 2.7, once migrating to django 2.2 and python 3.6 iam facing some errors. SO unicode is not working, if I try to type self.str() instead of unicode thing, it is crashing with recursion. def __str__(self): # Adds support for Python 3 return self.__unicode__() line 606, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 223, in inner return view(request, *args, **kwargs) File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/django/utils/decorators.py", line 45, in _wrapper return bound_method(*args, **kwargs) File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1698, in changelist_view response = self.response_action(request, queryset=cl.get_queryset(request)) File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1397, in response_action response = func(self, request, queryset) File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/django/contrib/admin/actions.py", line 28, in delete_selected deletable_objects, model_count, perms_needed, protected = modeladmin.get_deleted_objects(queryset, request) File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1820, in get_deleted_objects return get_deleted_objects(objs, request, self.admin_site) File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/django/contrib/admin/utils.py", line 151, in get_deleted_objects to_delete = collector.nested(format_callback) File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/django/contrib/admin/utils.py", line 211, in nested roots.extend(self._nested(root, seen, format_callback)) File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/django/contrib/admin/utils.py", line 195, in _nested children.extend(self._nested(child, seen, format_callback)) File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/django/contrib/admin/utils.py", line 197, in _nested ret = [format_callback(obj)] File "/home/bsd/.virtualenvs/bsd/lib/python3.6/site-packages/django/contrib/admin/utils.py", line 126, in format_callback … -
How to access image from Django form before saving using CreateView
I want to access image from form upload in order to manipulate it in class based view, but I keep getting MultiValueDictKeyError Here is my code: class CreateAuction(LoginRequiredMixin, CreateView): model = Auction fields = ['title', 'category', 'description', 'starting_price', 'duration', 'hp_express', 'tisak_paketi', 'dpd', 'gls', 'osobno_preuzimanje', 'shipping_pays', 'image_1', 'image_2', 'image_3', 'image_4', 'image_5', 'image_6',] def form_valid(self, form): image = self.request.FILES['image_1'] I also tried to access it like this: image = form.cleaned_data['image_1'] which results in AttributeError at /nova-aukcija/ 'NoneType' object has no attribute 'read' How can I access image in order to manipulate it with Pillow? -
i am trying to read files in zip folder using python in django app and there is error Permission denied appears when i run the app
i'm trying to read dicom files in aip folder but when i run this code it gives me this error [Errno 13] Permission denied: 'PATIENT_DICOM/' file = patient.PATIENT_DICOM with zipfile.ZipFile(file,'r') as zip: ls= zip.infolist() slices = [pydicom.read_file(s.filename) for s in ls] -
How do i limit the numbers if comment to be displayed
I have multiple comments on my homepage, how do i limit the comment to be displayed on a post. Like, i have 10 comments and i want to display only 2 comments. class Image(models.Model): imageuploader_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True) first_upload_image = models.FileField(upload_to ='picmate',null=True, blank=True) second_upload_image = models.FileField(upload_to ='picmate',null=True, blank=True) image_caption = models.CharField(max_length=700) date = models.DateTimeField(auto_now_add=True, null= True) class Meta: verbose_name = 'Image' verbose_name_plural = 'Images' ordering = ['-date'] def __str__(self): return self.image_caption class Comments (models.Model): comment_post = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True) commented_image = models.ForeignKey('Image', on_delete=models.CASCADE, related_name='comments') date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Comment' verbose_name_plural = 'Comments' ordering = ['-date'] def __str__(self): return self.author.__str__() def home(request): all_images = Image.objects.filter(imageuploader_profile=request.user.id) users = User.objects.all() next = request.GET.get('next') if next: return redirect(next) context = { 'all_images': all_images, 'users': users, } return render(request,'home.html', context,) @login_required def comments(request, id): post = get_object_or_404(Image,id=id) # current_user = request.user print(post) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.commented_image = post comment.save() return redirect('/') else: form = CommentForm() all_comments = Comments.objects.filter( author=request.user.id, commented_image=post, ) {% for comment in post.comments.all %} <div class="mb-1" style="padding-bottom:-10px;position:relative;top:-10px"> <div class="truncate card-meta dark-grey-text" style=""> <a href="#" class="username dark-grey-text text-lowercase"> {{ comment.author }}</a>&nbsp;&nbsp;{{ comment.comment_post }} </div> … -
How to override app_settings while testing
Okay now, I have settings.py SETTING1='value' SETTING2='value' After that we realized that these settings SETTING1 and SETTING2 are more specified to app1 So we've added them apps.py from django.apps import AppConfig class EXAPPConfig(AppConfig): name = 'EXAPPConfig' verbose_name = "EXAPPConfig" SETTING1 = 'value' def ready(self): pass and call them withviews.py app_settings = apps.get_app_config('ex_app') app_settings.SETTING1 according to Django documentation So how can I override them with override_settings at tests @override_settings I tried @patch to patch the config app but failed -
question php to python simple loop increasing [django]
I have to convert some php code to python django, in django i noticed that it's difficult to make things like php does: my question is, i have to increase a simple loop by n ( step) * iteration, php code: <?php $step = 3; for($i=0; $i < count($items); $i += $step){ /* */} in django template: i tried for loop of a dictionary, data['posts'] = { "comments": [ {"id": "1", "title": "hey buddy"}, {"id": "2", "title": "hey buddy"}, {"id": "4", "title": "hey buddy"}, {"id": "5", "title": "hey buddy"}, {"id": "6", "title": "hey buddy"}, {"id": "7", "title": "hey buddy"}, ] } and in template: for elem in posts.items: {{ forloop.counter0|add:"3" }} this works, but it's only display, not set the loop counter to each iteration to 3, i want that each iteration, the loop will increase by a specified number. thanks -
Django - how to decrease DB queries when iterating
I have a model ProductFilter in the project. An object of this model is a set of lookups defining a queryset. It's like a group of products - but just as a filter, not connected with a ForeignKey (ManyToManyField). The product can be filtered in multiple ProductFilters and the first is taken to account. It works like this: User define their filters. Then assign to each filter some pricing (and other) rules. For example filter with the name "Products under 10 USD" - rule - increase the price by 10%. The problem is that when I render products or export them. I have to check for every product if they belong to any filter which means a lot of DB queries. There can be 100k products. Do you have any ideas how to make it faster? class Product(...): ... @property def price(self): for filter in self.user.filters(): if filter.get_queryset().filter(pk=self.pk).exists(): return filter.rule.apply_rule(self.price) class ProductFilter(BaseTimeStampedModel): project = models.ForeignKey('projects.UserEshop', related_name='product_filters', on_delete=models.CASCADE) order = models.IntegerField(default=0) name = models.CharField(max_length=64) categories = models.ManyToManyField('FeedCategory', blank=True) brands = models.ManyToManyField('Brand', blank=True) manufacturers = models.ManyToManyField('Manufacturer', blank=True) import_price_no_vat_max = models.DecimalField(decimal_places=2, max_digits=64, null=True, blank=True) import_price_no_vat_min = models.DecimalField(decimal_places=2, max_digits=64, null=True, blank=True) name_icontains = models.CharField(max_length=128, null=True, blank=True) def get_queryset(self): # products for this project qs … -
Ajax request has to change GET insted of POST when using django i18n pattern
Requset has been change POST to GET enter image description here Ajax function enter image description here Django urlpatterns enter image description here -
How can I wrap lines in textarea - django
I have been struggling with this problem about 3 months. I tried every single suggestion but none of them worked. I am sick of explain myself. forms.py class blablablaForm(forms.Form): blablabla= forms.CharField(label='Blabla', max_length=100)) ... ... ... html <table class="table" style="border-style: solid; "> <form method="POST" > {% csrf_token %} {{ form.as_table}} <th colspan="2"><input style="" type = 'submit' value='Bla' /></th> </form> </table> and here is my output. When I start to write something in the "textarea", text goes and goes and goes. I want that the text areas able to responsive so i can read what i wrote. -
Django - ApiDetailView
I am following this solution on how to get specific fields from a django model: Select specific fields in Django get_object_or_404 from django.core import serializers as djangoserializer # module 'rest_framework.serializers' has no attribute 'serialize' class ProjectDetailApiView(APIView): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get(self, request, slug=None, format=None): project_instance = get_object_or_404(Project.objects.only('project_title', 'project_post'), slug=slug) data = djangoserializer.serialize('json', [ project_instance, ], fields=('project_title','project_post')) user = self.request.user updated = False viewed = False if not user in project_instance.project_views.all(): viewed = True project_instance.project_views.add(user) updated = True data = { "project": data, "updated":updated, "viewed":viewed } return Response(data) Output: { "project": "[{\"model\": \"webdata.project\", \"pk\": 4, \"fields\": {\"project_title\": \"Project 4\", \"project_post\": \"Blabla\"}}]", "updated": true, "viewed": false } Desired Output: { "project_title": "Project 4", "project_post": "Blabla", "updated": true, "viewed": false } Thank you -
Using Celery in a single-app Django project
I've structured my Django project according to the Single-App Django Project Anatomy pattern for simplicity. This gives me a project structure as follows: myproject ├── manage.py ├── settings.py ├── celery.py ├── myapp │ ├── models.py │ ├── tasks.py │ ├── ... │ └── views.py ├── urls.py └── wsgi.py Further, I've created a celery.py containing initializing the app instance: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') app = Celery('myproject') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() I do realise that Celery probably expects a "traditional" project structure for it's integration. What would be a correct celery.py setup in this case, and how should the worker be run? -
Can anyone explain the incompatible change about "model.save()" in Django 3.0
From the office release note, it says Model.save() no longer attempts to find a row when saving a new Model instance and a default value for the primary key is provided, and always performs a single INSERT query. .... In order to update an existing model for a specific primary key value, use the update_or_create() method or QuerySet.filter(pk=…).update(…) instead. But when I trired this: Class Order(models.Model): status = models.PositiveSmallIntegerField(default=1) order = Order.objects.filter(id=1).first() order.status = 2 order.save() or order = Order() order.id =1 order.status=2 order.save() where id=1 has existed in db. But it still works well. Why?