Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django test fails with 'django.db.utils.ProgrammingError: relation "django_content_type" does not exist'
I'm trying to write and run tests for a Django project, but running $ python manage.py test apps/actions/tests gives the following error: django.db.utils.ProgrammingError: relation "django_content_type" does not exist This only happens when I try to run the tests. Running python manage.py runserver gives me no error whatsoever and everything works fine. Here's the full traceback: Traceback (most recent call last): File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "django_content_type" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Kamil\Projekty\fast-intercept\manage.py", line 22, in <module> main() File "C:\Users\Kamil\Projekty\fast-intercept\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\core\management\commands\test.py", line 23, in run_from_argv super().run_from_argv(argv) File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\core\management\commands\test.py", line 53, in handle failures = test_runner.run_tests(test_labels) File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\test\runner.py", line 695, in run_tests old_config = self.setup_databases(aliases=databases) File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\test\runner.py", line 614, in setup_databases return _setup_databases( File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\test\utils.py", line 170, in setup_databases connection.creation.create_test_db( File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\db\backends\base\creation.py", line 72, in create_test_db call_command( File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\core\management\__init__.py", line 168, in call_command return command.execute(*args, **defaults) File "C:\Users\Kamil\Projekty\fast-intercept\venv\lib\site-packages\django\core\management\base.py", line 371, in execute output … -
Update the 'CHOICE' in the post method
I have a Model with Choices applied to one of the attributes: class Booking(models.Model): BOOKING_STATUS_CHOICES = [ ('RESERVED', 'Reserved'), ('COMPLETE', 'Complete'), ] status = models.CharField( max_length=10, null=False, blank=False, choices=BOOKING_STATUS_CHOICES, default='RESERVED' ) other_attributes = models.OtherFields() etc My ModelForm does not include this attribute as a form field. Instead, I want to update the value in the post method of the form. I am loosely following a walkthrough project where the form is saved but not committed, and then any other values that werent part of the form are added to the form instance before committing the save. What I have is below: def post(self, request): form = self.form_class(request.POST) if form.is_valid(): booking = form.save(commit=False) booking.status = "COMPLETE" booking.save() However checking the admin panel afterwards shows this value has not been applied. I am sure this is really simple to do but I can't find how to do it. Any help would be appreciated -
fatal: Out of memory, malloc failed (tried to allocate 524288000 bytes)
I am working with django. I have first tracked the staticfiles folder which is generated when we run python manage.py collectstatic {'its a copy of original static files actually"}. I don't want to track it because its increasing size of project while deploying and push in git. so i just added it in gitignore and removed from index using 'git rm -r --cached foldername'. After it when i try to push changes its giving error. Previously i have modified my config files to push larger files. Error: fatal: Out of memory, malloc failed (tried to allocate 524288000 bytes) I thing My config file: [core] repositoryformatversion = 0 filemode = false bare = false logallrefupdates = true symlinks = false ignorecase = true packedGitLimit = 128m packedGitWindowSize = 128m [remote "origin"] url = 'removed for privacy ' fetch = +refs/heads/*:refs/remotes/origin/* [branch "master"] remote = origin merge = refs/heads/master [branch "developer"] remote = origin merge = refs/heads/developer [remote "heroku"] url = 'removed for privacy ' fetch = +refs/heads/*:refs/remotes/heroku/* [pack] deltaCacheSize = 128m packSizeLimit = 128m windowMemory = 128m -
Seperation of dialogues based on specific users in Django
I am trying to implement direct messaging into my blog app using Django. Pretty much like Instagram direct but without using anything fancy like socket programming and Django channels. In other words, I don’t want online and instant chatting. I have made a simple Message in my message app in my project. It works properly and users can send messages to each other. The problem is that when I want to bundle each dialogue (two specific user) I cannot do it. I mean, I get all messages pretty fine but I cannot find any way to separate messages between different users. I want user to be able to click on the person that he or she wants and after that in a separate url his or her messages will be shown. I know that I have not included any code and my problem is so abstract. But to be honest my problem is the methodology of implementing this not the Django code itself. -
make a write_only field conditionally required in django rest framework
I have a field in my serializer which is required conditional on value of another field. say password is required only if registerField is email. I have this serializer class UserSerializer(ModelSerializer): ... password = CharField(write_only=True, required=False) def validate(self, data): if 'email' in data.keys() and 'password' not in data.keys(): raise ValidationError({'password', 'this field is required'}) return data this method works, but the response is: { "non_field_errors": [ "{'this filed is required', 'password'}" ] } but I want it to be like { "password":"this filed is required" } -
post() got an unexpected keyword argument 'id'
Hello i am trying to create quantity plus button where I can add 1 quantity per click but whenever I click the plus button i got this error.i don't know why I am getting this kind of error.Please also explain why I am getting this error and also please give me solution : post() got an unexpected keyword argument 'id' Here is my cart.py: @register.filter(name='in_cart') def in_cart(product, cart): keys = cart.keys() for id in keys: if int(id) == product.id: return True return False @register.filter(name='cart_quantity') def cart_quantity(product, cart): keys = cart.keys() quantity = 0 for i in keys: if int(i) == product.id: quantity = cart.get(i) else: continue return quantity Here is my Views.py: def post(self, request): product = request.POST.get('product') cart = request.session.get('cart') remove = request.POST.get('remove') if cart: quantity = cart.get(product) if quantity: if remove: cart[product] = quantity - 1 else: cart[product] = quantity + 1 else: cart[product] = 1 if cart[product] < 1: cart.pop(product) else: cart = {} cart[product] = 1 request.session['cart'] = cart return redirect('product_details') Here is my index.html: where I want to apply this functionality: <div>{{products|cart_quantity:request.session.cart}} in cart</div> <form acrtion="/" method="POST"> {% csrf_token %} <input type="text" name="product" value="{{products.id}}" /> <input type="submit" value="+" /> </form> -
This site can't be reached, docker-compose up does not show any error
this is the following up question from my last question to learn and deploy React and Django with Nginx and Docker while following Piotr's answer (link). I'm at the stage of deploying the development docker-compose without any SSL certificate. I have changed the code from Piotr's answer (link included above) to fit with my project name and directory, but after running ``docker-compose -f ... up` without any error, the site is showing This site can’t be reached. I'm still new to docker and Nginx and would really appreciate any guidance or troubleshooting tips on this issue. I have attached here: docker-compose-dev.yml, Dockerfile for Nginx and backend; my project directory tree; docker log; Nginx default.conf; wsgi-entrypoint.sh. Thank you!!! project directories: . ├── docker │ ├── backend │ │ ├── Dockerfile │ │ └── wsgi-entrypoint.sh │ └── nginx │ ├── Dockerfile │ └── development │ └── default.conf ├── docker-compose-dev.yml ├── front-end │ ├── README.md │ ├── debug.log │ ├── package-lock.json │ ├── package.json │ ├── public │ ├── src │ └── yarn.lock ├── housing_dashboard_project │ └── housing_dashboard │ ├── dashboard_app │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ ├── models.py │ │ ├── serializers.py │ │ … -
Error when using Angular to upload image to Django REST API
I created a Django REST framework API to upload data and images. When I using the REST API website, I can upload images properly. However, when I try to use Angular to create a frontend to upload images, it raise an error in console. The full error page is shown as below Here is my codes in Angular: .ts: public registrationForm: FormGroup; ngOnInit() { this.apiService.getLearnid(this.id).subscribe( (data) => this.learn = data, (error) => this.errorMsg = error, () => console.log('the sequence completed!') ); this.registrationForm = this.fb.group({ name: ['',], learn_type: ['',], createtime: ['',], status : ['',], problems: ['',], image: ['',], }); } fileChange(event) { let fileList: FileList = event.target.files; let file: File = fileList[0]; this.registrationForm.value.image = file } onSubmit() { console.log(this.registrationForm); console.log(this.registrationForm.value); //console.log(this.registrationForm.value.userName); //console.log(this.registrationForm.value.password); //--test //--endtest this.id = parseInt(this.route.snapshot.paramMap.get('id'));; this.apiService.editLearn(this.id,this.registrationForm.value) .subscribe( response => console.log('Success!', response), error => console.error('Error!', error) ); //window.location.reload() } .html: <form [formGroup]="registrationForm" (ngSubmit)="onSubmit()" enctype='multipart/form-data'> <div class="form-group"> <label>Name</label> <input type="text" formControlName="name" class="form-control" [(ngModel)]="learn.name"><br> <label>Learning Type</label> <select formControlName="learn_type" [(ngModel)]="learn.learn_type"> <option value="study material"> study material </option> <option value="test problems"> test problems </option> <option value="exam"> exam </option> </select> <label>Create Time</label> <input type="datetime" formControlName="createtime" [(ngModel)]="learn.createtime" class="form-control"><br> <label>Image</label> <input type="file" formControlName="image" (change)="fileChange($event)" class="form-control" ><br> <label>status</label> <input type="json" formControlName="status" [(ngModel)]="learn.status" class="form-control"><br> <label>problems</label> <input type="json" formControlName="problems" [(ngModel)]="learn.problems" class="form-control"><br></div> … -
When I include GroupedForeignKey, ChainedForeignKey to my project the web servers(Apache, and IIS) give errors(500 - Internal server error.)
I used Django-smart-select to my project, before including the smart-select to model.py everything work properly but when I import GroupedForeignKey, ChainedForeignKey from Django-smart-select (from smart_selects.db_fields import GroupedForeignKey, ChainedForeignKey) the web servers(IIS, Apache) give errors. Apache errors (500 internal server error) IIS errors (Traceback (most recent call last): File "c:\python37\lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "c:\python37\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "c:\python37\lib\site-packages\wfastcgi.py", line 600, in get_wsgi_handler handler = import(module_name, fromlist=[name_list[0][0]]) File "C:\inetpub\wwwroot\webproject\webproject\wsgi.py", line 16, in application = get_wsgi_application() File "c:\python37\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "c:\python37\lib\site-packages\django_init_.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "c:\python37\lib\site-packages\django\apps\registry.py", line 83, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant StdOut: StdErr: ) would you please help me thank you. -
AttributeError at /checkout/ 'QuerySet' object has no attribute 'id'. can't access to my automactically created 'id model
I'm a beginner at django. It's my first time to post there. That's why feel free to point if I have done something wrong. I'm doing 'e-commerce page' project. I'm using django 3.1.3. I can't get access to my 'id' model in my Order model: from django.db import models from django.contrib.auth import get_user_model # Create your models here. from products.models import Product User = get_user_model() ORDER_STATUS_CHOICES = ( ('created', 'Created'), ('stale', 'Stale'), ('paid', 'Paid'), ('shipped', 'Shipped'), ('refunded', 'Refunded'), ) class Order(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) status = models.CharField(max_length=20, choices=ORDER_STATUS_CHOICES, default='created') sub_total = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) tax = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) total = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) paid = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) shipping_address = models.TextField(blank=True, null=True) billing_adress = models.TextField(blank=True, null=True) timestamp = models.DateField(auto_now=True) This is my view: from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required # Create your views here. from .models import Order from products.models import Product @login_required def checkout_order(request): qs = Product.objects.filter(featured=True) if not qs.exists(): return redirect('/') product = qs.first() user = request.user # without login_required there will be AnonUsers so we don't want it order_id = request.session.get('order_id') order_obj = None try: order_obj = Order.objects.filter(id=order_id) except: order_id = … -
get chained queryset ajax django
I want to get a queryset through ajax request and use it as I can do with django queryset in template. I have the following codes: # view.py def ajax_get_allocates_by_date(request): """ ajax 요청 함수 """ today = timezone.localdate() date = request.GET.get('kw', today.strftime('%Y-%m-%d')) date=parse_date(date) d=Date.objects.get(date=date) allocate_list = Allocate.objects.filter(date=d) data = { 'date': serializers.serialize( 'json', [d] ), 'allocate_list': serializers.serialize( 'json', allocate_list ) } return JsonResponse(data) template <form method="get"> ... <input type="text" id="refer-date" name="refer-date" class="frm_input2 frm_date"> ... </form> ... <script> $('#refer-date').datepicker({ onSelect: function(dateText, inst) { let date = $(this).val() console.log(date) $.ajax({ url: "{% url 'allocate:get-allocates-by-date' %}", data: { 'kw': date }, success: function(data) { let date = JSON.parse(data.date) let queryset = JSON.parse(data.allocate_list) console.log(date) console.log(queryset) } }) } }) </script> If the value of #refer-date is changed, I get ajax response and it is logged in console. However, my Allocate model has some other ForeignKey relationship, which I also want to display in the template. For now it seems I can only render some id if the field is ForeignKey. The best would be use django for loop as ajax response, but I'm not sure how I can achieve that. Any suggestion would be highly appreciated. Thank you. -
Comment is not adding after click on add button
Comment is not adding after clicking it on Add comment, views.py @login_required def detail_view(request,id): data = Post.objects.get(id=id) comments = data.comments.filter(active=True) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = data new_comment.save() else: comment_form = CommentForm() context = {'data':data,'comments':comments,'new_comment':new_comment,'comment_form':comment_form} return render(request, 'mains/show_more.html', context ) models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE,related_name='comments') body = models.TextField() active = models.BooleanField(default=False) class Meta: ordering = ['created_at'] def __str__(self): return self.body forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) Please help me in this. I will really appreciate your Help. -
Django ValueError: Field 'id' expected a number but got 'myuser'
I need to use my usernames to panel/profile/<username> address. So what I did in models is: class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) def __str__(self): return str(self.user) And in urls.py I have these paths: urlpatterns = [ path('panel', views.home, name='panel'), path('panel/register', views.registerPage, name='register'), path('panel/login', views.loginPage, name='login'), path('panel/logout', views.logoutPage, name='logout'), path('dashboard', views.userProfile, name='dashboard'), path('dashboard/settings/edit-profile', views.userSettings, name='settings'), path('panel/profile/<str:username>', views.profile, name='profile'), ] and in this way there is no problem: >>> customer=Customer.objects.get(user_id=118) >>> customer.user.username 'myuser' But in views.py I need to grab username as a part of URL like that: @login_required(login_url='login') @allowed_users(allowed_roles=['admins']) def profile(request, username): customer = Customer.objects.get(user=username) print(type(customer), customer) But I have this error: ValueError at /panel/profile/myuser Field 'id' expected a number but got 'myuser'. -
Callback Endpoints in Django
I have a scenario were a view function sends a post request to an external webserver which sends the callback response to a endpoint in my application. My question is how do I identify the session flow, that is how do I know that the callback response on the endpoint is for the user who triggered the view function initially. -
Django view not executing
I'm implementing an excel export function in one of my django apps, but when I click the link that is supposed to execute the view, nothing happens, and the server is not running the view at all. This is the button that is supposed to run that view: <li class="nav-item mt-sm-2 mt-lg-0"> <a href="{% url 'catalog:export_all_csv' %}" class="btn btn-success btn-sm" download="OrdenesProximas" tabindex="0" data-toggle="popover" data-trigger="focus" title="¡Archivo descargado!" data-content="El archivo ha sido descargado exitosamente."> <i class="uil-file"></i> Exportar catálogo a Excel </a> </li> My urls.py for the app: from django.urls import path from . import views app_name = 'catalog' urlpatterns = [ path('catalog/list/', views.ProductList.as_view(), name='product_list_table'), path('catalog/add/', views.create_product, name='add_product'), path('catalog/category/add/', views.CategoryCreate.as_view(), name='add_category'), path('catalog/<slug:category_slug>/', views.product_list, name='product_list_by_category'), path('catalog/<slug>/list/', views.CategoryProductList.as_view(), name='category_product_list_table'), path('catalog/', views.product_list, name='product_list'), path('catalog/<int:id>/<slug:slug>/', views.product_detail, name='product_detail'), path('catalog/<int:id>/<slug:slug>/edit/', views.edit, name='product_edit'), path('catalog/export_csv/', views.export_csv, name='export_all_csv'), ] The view: @login_required def export_csv(request): import pdb; pdb.set_trace() categories = Category.objects.filter(company=request.user.profile.company) queryset = Product.objects.filter(category__in=categories) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = f'filename=productos.csv' writer = csv.writer(response) writer.writerow(['Id de Producto', 'Categoría', 'Nombre del producto', 'SKU', 'Código de barras', 'Marca', 'Proveedor', 'Color', 'Medidas', 'Descripción', 'Observaciones', 'Precio 1', 'Precio 2', 'Precio 3', 'Impuesto (%)', 'Costo de fabricación']) for item in queryset: writer.writerow([item.id, item.category.name, item.name, item.sku, item.barcode, item.brand, item.provider, item.color, item.measures, item.description, item.observations, item.price_1, item.price_2, item.price_3, item.tax, item.fabrication_cost]) return response … -
django related field filter with range
I tried to filter the range of keyword_id in the book table. However, the following error continues to occur. How can I filter the range of keyword_id? here is my code UserBook.objects.prefetch_related('book').filter(book__keyword_id__range(2,7)).values( 'book_id').annotate(count=Count('book_id')).order_by('-count') it is error raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: range -
Only superuser to make new accounts using Django allauth
I am making a subscription based site using Django allauth. I want it so that only the super user can use the sign up page to register clients, so they then have access to the whole site. I thought I had it by using if statements on the base.HTML page it then when I go to make a new user when still logged in as the super user it does not work! Any suggestions?! Thanks 😃 -
ckeditor-form is not properly shown in server; Django
I have a form that is displayed ok, localy: <form id="form_image" method="POST" enctype="multipart/form-data"> <div class="col"> {% csrf_token %} {{ form.media }} {{ form.as_p }} <input id="bb0" type="submit" class="btn btn-primary" value="Submit"> </div> </form> but on server, it cannot find the recourses: it gives the 404 error that the following is not found: https//mysite.com/static/ckeditor/ckeditor/ckeditor.js where it is in fact is not in that folder anyways. it is a library: any idea that what is missing here? -
Problem with django after installing anaconda
I am working on a Django project and this is what I am getting when I try to run the server. It used to work totally fine but I think the path is missing for virtualenv. I installed anaconda yesterday and the path variable is changed in advanced system settings. How can I revert them back to original settings? Total python newbie here. Kindly help. C:\Users\13157\django_project>python manage.py runserver Traceback (most recent call last): File "manage.py", line 9, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 20, in <module> main() File "manage.py", line 11, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? C:\Users\13157\django_project> -
django. Form creates blank objects for empty fields. How to prevent this/only create objects for populated fields?
I have several models linked to a single form. The form creates and saves individual model objects. Here are the models. class Quarterback(models.Model): name = models.CharField(max_length=20) score = models.IntegerField(blank=True, null=True) class Runningback(models.Model): name = models.CharField(max_length=20) score = models.IntegerField(blank=True, null=True) class Widereceiver(models.Model): name = models.CharField(max_length=20) score = models.IntegerField(blank=True, null=True) class Tightend(models.Model): name = models.CharField(max_length=20) score = models.IntegerField(blank=True, null=True) class Kicker(models.Model): name = models.CharField(max_length=20) score = models.IntegerField(blank=True, null=True) This is the form. class PlayerForm(forms.Form): quarterback_name = forms.CharField(label='Quarterback', max_length=100, required=False) runningback_name = forms.CharField(label='Runningback', max_length=100, required=False) widereceiver_name = forms.CharField(label='Widereceiver', max_length=100, required=False) tightend_name = forms.CharField(label='Tightend', max_length=100, required=False) kicker_name = forms.CharField(label='Kicker', max_length=100, required=False) def save(self): quarterback_name = self.cleaned_data.get('quarterback_name') Quarterback.objects.create(name=quarterback_name) runningback_name = self.cleaned_data.get('runningback_name') Runningback.objects.create(name=runningback_name) widereceiver_name = self.cleaned_data.get('widereceiver_name') Widereceiver.objects.create(name=widereceiver_name) tightend_name = self.cleaned_data.get('tightend_name') Tightend.objects.create(name=tightend_name) kicker_name = self.cleaned_data.get('kicker_name') Kicker.objects.create(name=kicker_name) The problem I'm having is that I want the option to save only one object and leave the other form fields empty. This sort of works. I can save just one field and therefore create only one object, but my form seems to be creating blank objects for the fields that are left empty. I want to stop these blank objects being created so I tried a few things out. I tried adding an else/if and a "pass" if the field … -
Django Model Design many-to-one?
I'm trying to create two models in Django, 'Paragraph' and 'Sentences'. I still do not seem to understand how the many-to-one function works. If I want there to be a paragraph that holds multiple sentences; do I simply add a ForeignKey(Paragraph) into the Sentences model? That way I can have more than one sentence store inside the Paragraph model. Thank you for any insight as I try to learn Django. -
How to raise multiple ValidationError on Django Rest API?
Suppose I have three serializers in function and I want to check the validation. If any errors occur in the condition it Response error message at a time My function: def employ_create(request): if request.method == 'POST': employ_basic_info = data['basic_info'] employ_academic_info = data['academic_info'] employ_address = data['address'] employ_basic_info_serializer = EmployBasicInfoSerializers(data=employ_basic_info) employ_academic_info_serializer = EmployAcademicInfoSerializers(data=employ_academic_info) employ_address_serializer = EmployAddressInfoSerializers(data=employ_address) if employ_basic_info_serializer.is_valid() and employ_academic_info_serializer.is_valid() and employ_address_serializer.is_valid(): employ_basic_info_serializer.save(employ_id=user_obj) employ_academic_info_serializer.save(employ_id=user_obj) employ_address_serializer.save(employ_id=user_obj) return Response(status=rest_framework.status.HTTP_200_OK) status_errors = { 'employ_basic_info_error':employ_basic_info_serializer.errors, 'employ_academic_info_error':employ_academic_info_serializer.errors, 'employ_address_error':employ_address_serializer.errors, } return Response({'stutase':status_errors}, status=rest_framework.status.HTTP_400_BAD_REQUEST) I want to return employ_basic_info_serializer, employ_academic_info_serializer, employ_address_serializer errors if any errors occur. How can I do it? pls, help me... -
Django - No Category matches the given query
I'm implementing a view that outputs a table as a .csv file, but when I try to run it, it throws a 404 error with this description, and it says that it was raised by a view called "catalog.views.product_list", which doesn't exist anymore, as I deleted it. views.py: @login_required def export_csv(request): categories = Category.objects.filter(company=request.user.profile.company) queryset = Product.objects.filter(category__in=categories) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = f'filename=productos.csv' writer = csv.writer(response) writer.writerow(['Id de Producto', 'Categoría', 'Nombre del producto', 'SKU', 'Código de barras', 'Marca', 'Proveedor', 'Color', 'Medidas', 'Descripción', 'Observaciones', 'Precio 1', 'Precio 2', 'Precio 3', 'Impuesto (%)', 'Costo de fabricación']) for item in queryset: writer.writerow([item.id, item.category.name, item.name, item.sku, item.barcode, item.brand, item.provider, item.color, item.measures, item.description, item.observations, item.price_1, item.price_2, item.price_3, item.tax, item.fabrication_cost]) return response urls.py from django.urls import path from . import views app_name = 'catalog' urlpatterns = [ path('catalog/list/', views.ProductList.as_view(), name='product_list_table'), path('catalog/add/', views.create_product, name='add_product'), path('catalog/category/add/', views.CategoryCreate.as_view(), name='add_category'), path('catalog/<slug>/list/', views.CategoryProductList.as_view(), name='category_product_list_table'), path('catalog/<int:id>/<slug:slug>/', views.product_detail, name='product_detail'), path('catalog/<int:id>/<slug:slug>/edit/', views.edit, name='product_edit'), path('catalog/export_csv/', views.export_csv, name='export_all_csv'), ] The button that triggers the view: <li class="nav-item"> <a href="{% url 'catalog:export_all_csv' %}" class="btn btn-success btn-sm" download="Productos" tabindex="0" data-toggle="popover" data-trigger="focus" title="¡Archivo descargado!" data-content="El archivo ha sido descargado exitosamente."> <i class="uil-file"></i> Exportar a Excel </a> </li> I don't get how a view that was deleted already is causing … -
How to fix AttributeError: 'Like' object has no attribute 'filter'
I am trying to add a condition to my notification to check if a user's total number of likes for all the posts related to him and send a notification if reached a certain number. I have filtered the total likes by the post author but I keep receiving AttributeError: 'Like' object has no attribute 'filter' To summarize here is the post model class Post(models.Model): author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='author') num_likes = models.IntegerField(default=0, verbose_name='No. of Likes') likes = models.ManyToManyField(User, related_name='liked', blank=True) Here is the likes model class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=8) def like_progress(sender, instance, *args, **kwargs): like = instance.filter(post__author=Post.author).count() post = like.post sender = like.user if like == 12: notify = Notification(post=post, sender=sender, user=post.author, notification_type=3) notify.save() My Question: How to fix this error? -
Django SQLite on Heroku doesn't recognize any of the changed models and throws a "relation doesn't exist" error
I changed the name of several models on Django. Successfully ran makemigrations and migrate. I can interact with the SQLite directly as admin or through requests on localhost. before changing the tables I had deployed to Heroku and it was working. when I changed the model names and pushed to Heroku (after successfully running on localhost) I get issues. When I login as admin to the site (on Heroku) I can interact with tables like User and Token, but not with the newly updated models. as soon as I click on them I get bellow error. when I click on add to these models, the columns appear but as soon as I hit save I get below error as well. ProgrammingError at /admin/app_name/model_name/ relation "app_name_model_name" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "app_name_model_name" I kept the Debug=True to see what's going on otherwise I get "500 Internal Server Error". I have added heroku's site as "ALLOWED_HOSTS". When I was trying to make the migrations work, I had delete the files on the migration folder. not sure if there is a similar process on Heroku or if I'm missing something else? By the way I have ran the …