Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot assign "'2'": "PatientProfile.user" must be a "User" instance. django
All data is saving fine but issues are while saving a ForignKey. 1 is User and another one is Address these both are FORIEGNKEY. -
How to read the content on an exception raised by a third party app in django?
Need help in a situation. I have made a request to a third party app and it is raising an exception so i want to read message of this exception exceptions.AlreadyExistError: Reason = Entered bank Account is already registered:: response = {"status": "ERROR", "subCode": "409", "message": "Entered bank Account is already registered"} request_id = fdd54b5c25c73cc3d437188278b0be26 try: add_beneficiary = Beneficiary.add( bankAccount=order.payee_bank_account_number) except Exception as e: print(e) #Reason = Entered bank Account is already registered:: response = {"status": "ERROR", "subCode": "409", "message": "Entered bank Account is already registered"} request_id = c57d9df21bd413d9a46eaec82a590e9b How do I read the message of the exception -
How to add multiple Model in one form in django
Hi I'm creating a Django project where i want multiple model in one form class. here is my Model.py class Robot(models.Model): robot = models.CharField(max_length=100) short_Description = models.CharField(max_length=200) status = models.CharField(max_length=20) parameter = models.CharField(max_length=200) jenkins_job = models.CharField(max_length=100, default='JenkinsJobName') jenkins_token = models.CharField(max_length=100, default='JenkinsToken') jenkins_build = models.CharField(max_length=10, default=0) jenkins_build_status = models.CharField(max_length=20, default="Never Run") class Lookup(models.Model): Name = models.CharField(max_length=100, unique=True) Value = models.CharField(max_length=50) Type = models.CharField(max_length=30) Description = models.CharField(max_length=200) Here's my form.py class RobotReg(forms.ModelForm): class Meta: model = Robot fields = ['robot', 'short_Description', 'status', 'parameter','jenkins_job','jenkins_token'] widgets = { 'robot':forms.TextInput(attrs={'class':'form-control','id':'robot'}), 'short_Description':forms.TextInput(attrs={'class':'form-control', 'id':'SD'}), 'status':forms.TextInput(attrs={'class':'form-control'}), 'parameter':forms.TextInput(attrs={'class':'form-control', 'id':'parameter'}), 'jenkins_job':forms.TextInput(attrs={'class':'form-control', 'id':'JJ'}), 'jenkins_token':forms.TextInput(attrs={'class':'form-control', 'id':'JT'}), } class LookupReg(forms.ModelForm): class Meta: model = Lookup fields = ['Name', 'Value', 'Type', 'Description'] widgets = { 'Name':forms.TextInput(attrs={'class':'form-control','id':'Name'}), 'Value':forms.TextInput(attrs={'class':'form-control', 'id':'Value'}), 'Type':forms.TextInput(attrs={'class':'form-control', 'id':'Type'}), 'Description':forms.TextInput(attrs={'class':'form-control', 'id':'Description'}), } In form.py i dont want to create two different class for my models. I want two models fields in my Robotreg Class. -
Django Authentication: Super User Can't Login
I have a django app and now need to add users. I am able to create superusers and to login with them through py manage.py runserver but can't login through the docker run webpage. I've read a few things that say the cause of this might be wsgi but I can't figure out how or why this happens. Here are the relevant bits of code Dockerfile FROM python:3.6 COPY manage.py gunicorn-cfg.py requirements.txt .env ./ RUN pip install -r requirements.txt COPY app app COPY authentication authentication COPY core core RUN python manage.py makemigrations RUN python manage.py migrate EXPOSE 5005 CMD ["gunicorn", "--config", "gunicorn-cfg.py", "core.wsgi"] settings.py import os from decouple import config from unipath import Path BASE_DIR = Path(__file__).parent CORE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = config('DEBUG', default=True, cast=bool) # load production server from .env ALLOWED_HOSTS = ['localhost', '127.0.0.1', config('SERVER', default='127.0.0.1')] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', # Enable the inner app 'authentication' ] ROOT_URLCONF = 'core.urls' TEMPLATE_DIR = os.path.join(CORE_DIR, "core/templates") # ROOT dir for templates TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'core.wsgi.application' DATABASES = { 'database': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '../database.sqlite3', … -
DjangoCMS views.py class automatic generated
I have a question I have created a form with an automatically generated class using javascript and now I have to add a views.py in DjangoCMS or Python with that automatically generated class so that it sends the form with extra options that are in the screenshot. I hope you guys can help me and that I have been clear. This is the code from views.py, Sorry its Dutch: def lxbox(request): if request.method == 'POST': name = request.POST.get('name') surname = request.POST.get('surname') company = request.POST.get('company') reference = request.POST.get('reference') email = request.POST.get('email') remarks = request.POST.get('remarks') typeFixture = request.POST.get('typeFixture') numberFixture = request.POST.get('numberFixture') groundFault = request.POST.get('groundFault') numberInput = request.POST.get('numberInput') numberControl = request.POST.get('numberControl') numberGroup = request.POST.get('numberGroup') numberLight = request.POST.get('numberLight') groundFaultextra = request.POST.get('groundFaultextra') numberInputextra = request.POST.get('numberInputextra') numberControlextra = request.POST.get('numberControlextra') numberGroupextra = request.POST.get('numberGroupextra') numberLightextra = request.POST.get('numberLightextra') writeroot = request.POST.get('writeroot') data = { 'name': name, 'surname': surname, 'company': company, 'reference': reference, 'email': email, 'remarks': remarks, 'typeFixture': typeFixture, 'numberFixture': numberFixture, 'groundFault': groundFault, 'numberInput': numberInput, 'numberControl': numberControl, 'numberGroup': numberGroup, 'numberLight': numberLight, 'groundFaultextra': groundFaultextra, 'numberInputextra': numberInputextra, 'numberControlextra': numberControlextra, 'numberGroupextra': numberGroupextra, 'numberLightextra': numberLightextra, 'writeroot': writeroot, } writeroot = ''' Naam: {} Achternaam: {} Bedrijf: {} Referentienummer: {} Email: {} Opmerkingen: {} Type Armatuur: {} Aantal Armaturen per groep: {} Aardlek: {} Extra … -
i want to save my host to database and also create a shortlink using hashlib django
My problem i am facing is that first i cannot save my urls to database, second i cannot generate shorl links for my urls(i,e. my local host) and third, i want to display both on the templates. I used hashlib md5 to short the url, but i am not able to do that. URLS.py path('SaveURL/', views.SaveURL, name='SaveURL'), path('create_short_url/', views.create_short_url, name='create_short_url'), VIEWS.py def SaveURL(request): full_url = request.get_host() obj = URL.create_short_url('full_url') url = URL(full_url=full_url, obj=obj) url.save() return render(request, 'link.html', {"full_url": obj.full_url, "short_url": request.get_host()+'/'+obj.short_url}) #generating short link def create_short_url(self, request, full_url): temp_url = md5(full_url.encode()).hexdigest()[:8] try: obj = self.objects.create(full_url=full_url, short_url=temp_url) except: obj = self.objects.create(full_url=full_url) return render(request, 'link.html', {"obj": obj}) MODELS.py #Model to save url of the pages class URL(models.Model): full_url = models.CharField(unique=True, max_length=400) short_url = models.CharField(unique=True, max_length=20) This is where I want to display my localhost URL and generated shortlink. <!-- Copy to Clipboard --> <center><label for="text_copy" class="text-primary">Link to be shared</label> <input type="text" class="form-control border-0 d-block bg-dark text-white" id="text_copy" value="http://127.0.0.1:8000/product/product_view/{{ results.uid }}"/> </center><center><div class="container"> <button onclick="copyToClipboard('#text_copy')" type="button" class="col mr-3 btn btn-light btn-rounded" data-mdb-ripple-color="dark">Copy</button> </center> </div> <!-- Copy to Clipboard --> <center><label for="text_copy" class="text-primary"> Short Link to be shared</label> <input type="text" class="form-control border-0 d-block bg-dark text-white" id="text_copy1" value="http://127.0.0.1:8000/product/product_view/{{ results.user_id }}"/> </center><center><div class="container"> <button onclick="copyToClipboard('#text_copy1')" type="button" … -
Django serializers usage with data transfer objects
I am from Java background and I am getting a bit confused with the serialization in Django Let's say I have this requirement I need to fetch the results of stocks from an exchange. So the request will be like { "exchange" : ["exchange1", "exchange2"], "stock_name" : ["stock1", "stock2"] } In Spring I would write a RequestDto like this, class StockResultRequestDto{ List<String> exchange; List<String> stockName; } and In the controller method getMethod(@RequestBody StockResultRequestDto request) and Jackson library behind the scenes would take care of the serialization. In Django Rest as well, I was thinking to have it similar @dataclass class StockResultRequestDto: exchange: List[str] stock_name: List[str] But since we don't have a builtin serializer in python, I understand, I will need to write serializer as well. class StockMarketRequestSerializer(serializers.Serializer): exchange = serializers.CharField(max_length=100, many=True) stock_name = serializers.CharField(max_length=200, many=True) @api_view(['POST']) def get_stock_result(request): serializer = StockMarketRequestSerializer(data=request.data, many=True) serializer.is_valid(raiseException=False) stockMarketDto = StockResultRequestDto(**serializer.validated_data) <--- Is it advised to create a dto when I can pass around serializer.validated_data? Coming to output considering I don't have a database involved, I fetch the results from a different server class StockResult: stockName: str netProfit: float revenue: float I do business logic and finally, I will have something like stock_result_response = [list … -
How to add UserCreationForm to HTML/Bootstrap template in Django
I am creating a registration page for my website. I am following this tutorial. I have a bootstrap/html template with a form (Down Bellow), and I want to replace the html form with a UserCreationForm that I have already made in my forms.py file. The tutorial says to replace the html input fields with my user creation fields, but then bootstrap cannot style them. Can someone please help me so the default form fields have my python usercreationform? My code is down bellow. Register.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:400,700"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="{% static "registerstyles.css" %}"> <title>GoodDeed - Register</title> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> </head> <body> <div class="signup-form"> <form action="" method="post"> {% csrf_token %} <h2>Sign Up</h2> <p>Please fill in this form to create an account!</p> <hr> <div class="form-group"> <div class="row"> <div class="col"> <input type="text" class="form-control" name="first_name" placeholder="First Name" required="required" ></div> <div class="col"><input type="text" class="form-control" name="last_name" placeholder="Last Name" required="required"></div> </div> </div> <div class="form-group"> <input type="email" class="form-control" name="email" placeholder="Email" required="required"> </div> <div class="form-group"> <input type="password" class="form-control" name="password" placeholder="Password" required="required"> </div> <div class="form-group"> <input type="password" class="form-control" name="confirm_password" placeholder="Confirm Password" required="required"> </div> <div class="form-group"> … -
DJANGO Check if a user is in a group before posting ! If a user is either in that group or not , messages always tells me that I'm not
So I was taking an Udemy Course, and I tried to verify if a user has joined a group, only in that moment he can post something. If not, the user is going to be redirected to a page, with a Django message. But either the user is a member or not, I receive the message that he is not. What do I have to change? I'm desperate. models.py ## MODELS.PY ## from django.db import models from django.urls import reverse from django.conf import settings from groups.models import Group from misaka import html from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): user = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group,related_name='posts',null=True,blank=True,on_delete=models.CASCADE) def __str__(self): return self.message def save(self,*args,**kwargs): self.message_html = misaka.html(self.message) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('posts:single',kwargs={'username':self.user.username, 'pk':self.pk}) class Meta(): ordering = ['-created_at'] unique_together = ['user','message'] views.py ## VIEWS.PY ## #POSTS VIEWS.PY from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from django.views import generic from django.http import Http404 from django.contrib import messages from groups.models import Group,GroupMember from braces.views import SelectRelatedMixin from django.http import HttpResponseRedirect from django.urls import reverse from posts.models import Post from . import models from . import forms from django.contrib.auth import … -
How to fix Django "ModuleNotFoundError: No module named 'application'" on AWS?
I am trying to redeploy a Django web application on AWS. My elastic beanstalk environment has been red a couple of times. When I ran eb logs on the cli, I am getting a "ModuleNotFoundError: No module named 'application' error". I think this has got to do with my wsgi configuration. I have deployed this web app on AWS before. I messed up when I tried deploying a new version then decided to just start over. Here is my wsgi.py configuration: ```import os from django.core.wsgi import get_wsgi_application from django.contrib.staticfiles.handlers import StaticFilesHandler os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = StaticFilesHandler(get_wsgi_application())``` When I deploy the app, it's giving me a 502: Bad gateway error. Let me know if you would like more info on the issue. Any pointers would be greatly appreciated. -
How to access constant with class pointer in python - AUTH_USER_MODEL = 'django_restframework_2fa.User'
I have defined AUTH_USER_MODEL = 'django_restframework_2fa.User' in the settings.py file of Django application. Now, I want to access that User() class using AUTH_USER_MODEL constant. How can this be done? I tried to access it like this settings.AUTH_USER_MODEL(**data) which should be equivalent to User(**data) -
Django lookups - filter charfield that contains a number
I'd like to perform a query on a model with a charfield and I want to filter only the records that have a number contained in that charfield. My model: class LocationCache(models.Model): location_name = CharField(primary_key=True, max_length=100, blank=True) longitude = FloatField() latitude = FloatField() def __str__(self): return self.location_name Are there any lookups like this? LocationCache.objects.filter(location_name__is_number=True) -
Column does not exist foreign key table in Django
In django, I created a new model in my application (The app name is quiz) like this: class Score(models.Model): person1 = models.ForeignKey(Personality, on_delete=models.CASCADE, related_name="person1", blank=True, null=True, default=0) person2 = models.ForeignKey(Personality, on_delete=models.CASCADE, related_name="person2", blank=True, null=True, default=0) score = models.DecimalField(default=0, max_digits=5, decimal_places=2) I then proceeded to do makemigrations and migrate, which was successful. I also registered this model with the admin. But whenever I try to open it's page on the admin site, I get this message: P.S. I'm using PostgreSQL as my backend -
Getting Illegal instruction: illegal hardware instruction python manage.py runserver on Apple M1 chip
I am trying to bring up a Django project with the below dep: python 3.6 and django>2.0 All dependencies have been successfully installed but when I try to bring the server up it gives me the below error and exit after that: [1] 3298 illegal hardware instruction python manage.py runserver I am using MacOS Big Sur 11.2.2 with Apple M1 chip. -
How can I prefetch nested tables?
I'm working on an app with a DRF API. Development has been going on for some months, but only now are we running into performance issues when populating the database with actual data. I have done some profiling and found out that many endpoints query the database hundreds of times to fetch the necessary data. This is something that can be solved with select_related and prefetch_related, that much I know, but I'm having a hard time picturing it. Models class LegalFile(models.Model): code = models.CharField(max_length=75) description = models.CharField(max_length=255) contactrole = models.ManyToManyField(LegalFileContactRole, blank=True, related_name='contactroles') class LegalFileContactRole(models.Model): contact = models.ForeignKey(Contact, on_delete=models.DO_NOTHING, blank=True, related_name='legal_file_contact') subtype = models.ForeignKey(ContactSubType, on_delete=models.DO_NOTHING, related_name='legal_file_contact_role', null=True) class Contact(models.Model): name = models.CharField(max_length=150) surname_1 = models.CharField(max_length=50,blank=True, null=True) surname_2 = models.CharField(max_length=50,blank=True, null=True) class ContactSubType(models.Model): pass Say I want to list all the LegalFiles in the database, and fetch the names and both surnames of the contacts associated to each LegalFile through LegalFileContactRole. Is there a DRYer way than using lowercase notation to prefetch like LegalFile.prefetch_related('contactrole__contact__name', 'contactrole__contact__surname_1', 'contactrole__contact__surname_2')? This kind of nested relationship is a recurring thing in the app. -
I have a problem in my Django project when I try to push to heroku a problem occurs
django.db.utils.IntegrityError: column "pinned" of relation "blog_post" contains null values I migrated and did everything in localhost and Heroku server but I don't know how to solve this error. -
Django Super User Can't Login
I have created a few superusers and tried logging in as all of them but none of them work.The admin website just says: Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive and I'm pretty sure everything I entered was correct so I don't know where the problem could be coming from. Any ideas of how to fix this? -
Django get Category all data on Cart Page?
hi i am new in Django i want to select category all data on Cart Page. So user can see related all items if he/she want to buy more products. i don't know how i can get a category all data on cart page? View.py import random import string import stripe from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import redirect from django.shortcuts import render, get_object_or_404 from django.utils import timezone from django.views.generic import ListView, DetailView, View from django.db.models import Q from .forms import CheckoutForm, CouponForm, RefundForm, PaymentForm from .models import Item, OrderItem, Order, Address, Payment, Coupon, Refund, UserProfile stripe.api_key = settings.STRIPE_SECRET_KEY def create_ref_code(): return ''.join(random.choices(string.ascii_lowercase + string.digits, k=20)) def search_product(request): if request.method == "GET": query_name = request.GET.get('search', None) if query_name: results = Item.objects.filter( title__icontains=query_name) return render(request, 'product.html', {"results": results}) def products(request): context = { 'items': Item.objects.all() } def is_valid_form(values): valid = True for field in values: if field == '': valid = False return valid class CheckoutView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = CheckoutForm() context = { 'form': form, 'couponform': CouponForm(), 'order': order, 'DISPLAY_COUPON_FORM': True } Thanks enter image description here -
Sending data with files or image using axios and Django?
I am using axios with Django to send data to server and I have a form with input of type 'file' I am trying to send the form data using axios and it saves the data but the the Image does not upload to media folder this is my settings.py STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'core/static'), ] I am using a core for my python code and this is my python code def on_save(self, request, *args, **kwargs): self.row = None model_form = self.form if not self.has_user_add_perm(self.row): response = message.not_has_permission() else: form = model_form(request.POST, request.FILES) form_validated = form.is_valid() if form_validated: obj = self.save_form(request, form) self.save_model(request, obj, form) response = message.save_successfully() else: response = message.check_input(form.errors.as_json()) return JsonResponse(response) def on_update(self, request, *args, **kwargs): obj = request.POST.get('updateForm') model_form = self.form obj_for_update = get_object_or_404(self.model, pk=obj) if not self.has_user_edit_perm(obj_for_update) or not self.has_user_view_perm(obj_for_update): response = message.not_has_permission() else: form = model_form(request.POST, request.FILES, instance=obj_for_update) form_validated = form.is_valid() if form_validated: obj = self.save_form(request, form) self.save_model(request, obj, form) response = message.update_successfully() else: response = message.check_input(form.errors.as_json()) return JsonResponse(response) def post(self, request, *args, **kwargs): if 'saveForm' in request.POST.keys(): try: with transaction.atomic(): return self.on_save(request, *args, **kwargs) except JsonResponseException as e: return … -
Correct way to handle .wasm.gz and .data files in Django?
I'm currently dealing with a problem in my django web application that is running locally on 192.168.0.168. I'm making use of an OCR library that makes use of .wasm.gz files and .data files. In the documentation they mention: " In some cases you need to configure your webserver to serve data and wasm.gz files.". My first idea was to add the following mimetypes in django: mimetypes.add_type("application/x-gzip", ".wasm.gz", True) mimetypes.add_type("application/octet-stream", ".data", True) I'm however still seeing the error: error wasm-instantie. It somehow can't instantiate wasm because django needs to serve the wasm.gz and .data files correctly. These have been added however to the static folder and I'm able to download them if I manually browse to the link. Does anyone have any idea what I need to do to serve these correctly? -
Object permissions in Django Rest Framework
I am trying to do something which seems so straight-forward with Django Rest Framework and object permissions but there doesn't seem to be a simple way to go about it. Here are the (simplified) models I am talking about:- class Team(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Player(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) class Invitation(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE) I want to:- a) allow any authenticated user to create a Team but to prevent anyone but that user from changing or deleting that team b) allow any Player of that Team to create an Invitation for that Team but no-one else to be able to I decided to go with DjangoObjectPermissions in order to implement a). So my first problem seems to be that, in order to allow anyone to create a Team, I need to give ALL users the add_team permission which seems a bit unnecessary to me. Then I'll need to give any "normal" players I create the view_team permission on that Team but only the owner gets change_team and delete_team on that Team. Which is fine. But the bigger problem is when I try and work out permissions for the Invitation model. I can't give … -
Django Limit Access to Foreign Key without Proper Preload
I have 2 models, and I want to limit query access of some fields (the foreign key fields) from being loaded in memory, and throw an error in case someone tries to access them to avoid memory issues. class GenericItem(models.Model): name = models.Charfield(max_length=100) structure = models.TextField() class CustomItem(models.Model): name = models.Charfield(max_length=100) date = models.DateTimeField(auto_now_add=True) item_structure = models.ForeignKey(models.GenericItem) GenericItem.structure is a big text, and I want to prevent queries that want to access it from CustomItem without preloading it. Any idea how this could be done in a good manner? -
sorting search results in django
I'm have a django app with the following model. class Posts(models.Model): post = models.TextField(max_length=1500) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) likes = models.ManyToManyField(User, related_name="post_likes") category = models.CharField(max_length=50, default=None) To allow the users search for a particular blog and then display those objects I have the following view. def index(request): if request.method == "GET": search = request.GET.get("input") posts = Posts.objects.filter(category__icontains=f"{search}") else: posts = Posts.objects.all() params = {'blog': posts} return render(request, 'index.html', params) In the above view , variable search contains what user has searched for, that I'm receiving through a form. But I also want to provide a sort functionality after user has searched for a blog. Like user searches for "recipes", I need to show them all the search results and then let him sort them based on likes and recent etc. How do I do it since I'm losing search terms just after displaying the results. -
Problem with importing pisa from xhtml2pdf
I am trying the following code from an online tutorial on Django. Everything is working fine but when I import 'pisa' from xhtml2pdf, I get an error, "Import xhtml2pdf could not be resolved". What could be the issue? I have installed xhtml2pdf.Is there another python file I need to have? Please help me with resolving this issue. from django.shortcuts import render, get_object_or_404 from profiles.models import Profile from django.http import JsonResponse from .utils import get_report_image from .models import Report from django.views.generic import ListView, DetailView, TemplateView from .forms import ReportForm from django.conf import settings from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa from sales.models import Sale, Position, CSV from products.models import Product from customers.models import Customer import csv from django.utils.dateparse import parse_date from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin class ReportListView(LoginRequiredMixin, ListView): model = Report template_name = 'reports/main.html' class ReportDetailView(LoginRequiredMixin, DetailView): model = Report template_name = 'reports/detail.html' class UploadTemplateView(LoginRequiredMixin, TemplateView): template_name = 'reports/from_file.html' @login_required def csv_upload_view(request): print('file is being') if request.method == 'POST': csv_file_name = request.FILES.get('file').name csv_file = request.FILES.get('file') obj, created = CSV.objects.get_or_create(file_name=csv_file_name) if created: obj.csv_file = csv_file obj.save() with open(obj.csv_file.path, 'r') as f: reader = csv.reader(f) reader.__next__() for row in reader: data = "".join(row) data = … -
Django Views.py setup
I'm getting a RecursionError: maximum recursion depth exceeded while calling a python object enter code here from django.conf.urls import url enter code here from . import views enter code here urlpatterns = [ enter code here # Home page enter code here path(r'^$', views.index name='index') enter code here # show all topics enter code here url(r'^topics/$', view.topics, name='topics') enter code here ]