Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use ModelChoiceField in DRF?
I am trying to convert my form that was written earlier to django rest serializer but it does't work. Could you help me to solve this problem please? this is my form: class TripSearchForm(forms.Form): departure = ModelChoiceField( queryset=Place.objects.places_for_segment(), widget=autocomplete.ModelSelect2(url="autocomplete") ) destination = ModelChoiceField( queryset=Place.objects.places_for_segment(), widget=autocomplete.ModelSelect2(url="autocomplete") ) How to built proper serializer? -
How to avoid repeating query in loop for fetching data
I am sending site list with some its fields. Where some fields (three types payment amount with different statuses) we are fetching from other tables. Right now for each iteration of loop three queries are executing. I have mentioned below lines which are executing for each iteration In below code I am trying to get all main payment amount and summing that amount. Also there are some statuses of payment like payment raised, payment approved, payment completed. main_payment_raised = sum(mainPaymentVendor.objects.filter(systemId=site['systemId'],approvalStatus='Waiting').values_list('quotation',flat=True)) main_payment_approved = sum(mainPaymentVendor.objects.filter(systemId=site['systemId'],approvalStatus='Approved',paymentStatus='Waiting').values_list('quotation',flat=True)) main_payment_paid = sum(mainPaymentVendor.objects.filter(systemId=site['systemId'],paymentStatus='Confirm',approvalStatus='Approved').values_list('quotation',flat=True)) partial_payment_raised = sum(partialPaymentVendor.objects.filter(systemId=site['systemId'],approvalStatus='Waiting').values_list('amount',flat=True)) partial_payment_approved = sum(partialPaymentVendor.objects.filter(systemId=site['systemId'],approvalStatus='Approved',paymentStatus='Waiting').values_list('amount',flat=True)) partial_payment_paid = sum(partialPaymentVendor.objects.filter(systemId=site['systemId'],paymentStatus='Confirm',approvalStatus='Approved').values_list('amount',flat=True)) extra_payment_raised = sum(extraPaymentVendor.objects.filter(systemId=site['systemId'],approvalStatus='Waiting').values_list('amount',flat=True)) extra_payment_approved = sum(extraPaymentVendor.objects.filter(systemId=site['systemId'],approvalStatus='Approved',paymentStatus='Waiting').values_list('amount',flat=True)) extra_payment_paid = sum(extraPaymentVendor.objects.filter(systemId=site['systemId'],paymentStatus='Confirm',approvalStatus='Approved').values_list('amount',flat=True)) This entire functionality is consuming more time. Is there any optimized way to get result in minimum complexity P.S. I am using Django 1.11 and Python 2.7 -
Django Channels 2 sending knowing only the channel name
In Channels 1, easy enough to send a message to the client knowing the channel name, like: WebsocketMultiplexer(stream, Channel(reply_channel)).send(payload) How is this done in Channels 2? -
Saleor's `completeCheckout` graphql API completes checkout-id even if payment is invalid
I use Razorpay payment gateway in saleor and once an invalid payment_id is passed to checkoutPaymentCreate it creates a payment in payment_payment table. There's no way to validate payment before hitting completeCheckout API. Because of which completeCheckout API completes the checkout even though payment is invalid. I believe the checkout-id should be active if payment is invalid. This helps us to recover from an erroneous state. -
null value in column "job_id" violates not-null constraint
i'm trying to upload a pdf file but i keep getting an integrity error,when i try to submit the pdf file,it looks like i have some blank space in the db which i don't know,may someone please help me! The error is: IntegrityError at /posts/resume/ null value in column "job_id" violates not-null constraint models.py class Jobs(models.Model): title = models.CharField(max_length=80) jobs_type = models.CharField(max_length=80, choices=JOB_CHOICES) description = models.TextField() requirements = models.TextField() posted_date = models.DateTimeField(auto_now_add=True) start_date = models.DateField() deadline = models.DateField() link = models.URLField() slug = models.SlugField(max_length=150) contacts = models.CharField(max_length=80) tags = TaggableManager() class Meta: ordering = ('-posted_date',) class Application(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="application", on_delete=models.CASCADE) job = models.ForeignKey(Jobs, on_delete=models.CASCADE) professional_summary = models.TextField() resume = models.CharField(max_length=150) uploaded_at = models.DateTimeField(auto_now_add=True) form.py class ApplicationForm(forms.ModelForm): resume = forms.FileField(widget=forms.FileInput(attrs={'onchange': 'uploadPreview(this)'})) oss_resume = forms.CharField (widget=forms.HiddenInput(), required=False) class Meta: model = Application fields = ('professional_summary', 'resume', ) views.py class CreateApplicationView(LoginRequiredMixin, CreateView): form_class = ApplicationForm model = Application message = _("Your Event has been created.") success_url = reverse_lazy('posts:list_jobs') def __init__(self, **kwargs): self.object=None super().__init__(**kwargs) def form_valid(self, form): resume = form.cleaned_data['oss_resume'] form.instance.user = self.request.user submit = form.save() submit.user= self.request.user if not resume: return ('posts/no_resume.html') else: submit.save() def get_success_url(self): messages.success(self.request, self.message) return reverse('posts:list_events') def get_object(self): resume = kwargs.get('resume') return Application.objects.get(resume=resume) urls.py url(r'^list-jobs/$', JobsListView.as_view(), … -
How to Model a Matrix Table in Django
Modeling this simple table in Django ORM has plagued me for a while. My desired output is like the following. item_a item_b item_d item_d ----------------------------------------------- item_a 0 2 4 2.2 item_b 1 0 3.5 0.3 item_c 2 4 0 2 item_d 3.2 1 1 0 My requirements: The relationship of the items is a matrix-like table like above. Each row of the above table can be edited. There must be also the possibility of adding new items. The closest thing I've came across is using a manytomany relationship. But in this model my items have a relationship with themselves which makes it puzzling for me. What is the way to model such a relationship in Django models? -
Django images in template through FK
I am using a detail view to show data and I have 2 models. The problem is that one is FK of another and that ones storing pics and I need to show them, HOW?. Can't find the solution. Because of the Detail view. Please HELP file.html <img src="{{object.HallProperties.HallPictures.hall_pic0.url}}" class="w3-circle" style="width:400px" alt=""><hr width="15%"> </div><div class="zoom1"> <img src="{{object.HallProperties.hall_pic1.url}}" class="w3-round" style="width:400px" alt=""><hr width="15%"> </div><div class="zoom2"> <img src="{{object.HallProperties.hall_pic2.url}}" class="w3-round" style="width:400px" alt=""><hr width="15%"> </div><div class="zoom3"> <img src="{{object.HallProperties.hall_pic3.url}}" class="w3-round" style="width:400px" alt=""><br></div> view.py class HallDetail(DetailView): model = HallProperties template_name='hallfiles/hall-details.html' models.py class HallProperties(models.Model): hall_name = models.CharField(max_length = 128) hall_city = models.ForeignKey(CityModel.City, max_length=512) hall_owner = models.ForeignKey( HallOwnerData, on_delete=models.CASCADE, verbose_name="Hall Owner") parking_capacity = models.PositiveSmallIntegerField("Parking Capacity") class HallPictures(models.Model): hall_properties = models.ForeignKey( HallProperties, on_delete=models.CASCADE, verbose_name="Hall link") hall_pic0 = models.ImageField( "Hall Picture 1", upload_to='media/hallpics', blank=True, null=True) hall_pic1 = models.ImageField( "Hall Picture 2", upload_to='media/hallpics', blank=True, null=True) hall_pic2 = models.ImageField( "Hall Picture 3", upload_to='media/hallpics', blank=True, null=True) hall_pic3 = models.ImageField( "Hall Picture 4", upload_to='media/hallpics', blank=True, null=True) -
VS Code doesn't use pipenv .env file
Working with VS Code 1.35.1 on ubuntu 16.04 with a Python 3.7.3 pipenv virtual environment, I am trying to set environment variables in a .env file, but for some reason the file doesn't seem to be recognized. Can someone help me understand what I can do to give my (Django) app access to the environment variables, without needing to manually run pipenv shell. Steps taken: So, this is what I am doing exactly: 1 - I have set the Python interpreter for my project like so: ctrl + shift + p > Python: Select interpreter > Python 3.7.3 64-bit ('environment_name': pipenv) 2 - Created a .env file inside the project root directory: # Django SECRET_KEY="some key here" DEBUG=True ... 3 - Made sure the VS Code Python extension is installed and enabled 4 - Adjusted my Django settings file to get the SECRET_KEY from the environment variables: SECRET_KEY = os.getenv('SECRET_KEY') 5 - Running the Django development server from the VS Code terminal (with pipenv environment activated through ctrl + shift + ~): (environment-name) user@system-name:~/projects/my-project$ python manage.py runserver 6 - No other settings changed I haven't changed any settings, like the python.envFile setting. Settings are left to their defaults. How I … -
How to implement a search function in django
I am a kind of new to Django. And I am setting up a project that can display quotes based on a specific author or writer. I am having trouble creating the search function to display quotes based on the author's name. How do I create a search view function and display it on the template. For example, the user searches the author name from author_name in class Author, then it displays a list of quotes by the author Below is a sample of my models.py file class Author(models.Model): author_name = models.CharField(max_length=50) id = models.AutoField(primary_key=True) description = models.TextField(max_length=500) portrait = models.ImageField() def __str__(self): return self.author_name class Quote(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) quote = models.TextField(max_length=500) def __str__(self): return self.quote -
How to access ManyToMany Fields in Django If Mediator Class is used in relation?
I am beginner for django. I had already tried several times to solve this problem. Please consider my mistake if question is not asked properly. I don't know where I am going wrong. models.py class Participant(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) first_name = models.CharField(max_length=255,blank=True,null=True) last_name = models.CharField(max_length=255,blank=True,null=True) class Assessment(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(blank=True) created = models.DateTimeField(auto_now_add=True,editable=False) modified = models.DateTimeField(auto_now=True) class Seminar(models.Model): topic = models.CharField(max_length=255) date = models.DateField(null=True,blank=True) time = models.TimeField(null=True,blank=True) assessment = models.ManyToManyField(Assessment,blank=True,through='SeminarParticipant') participant = models.ManyToManyField(Participant,blank=True,through='SeminarParticipant') created = models.DateTimeField(auto_now_add=True,editable=False) modified = models.DateTimeField(auto_now=True) class SeminarParticipant(models.Model): assessment = models.ForeignKey(Assessment,blank=True,on_delete=models.CASCADE) seminar = models.ForeignKey(Seminar,blank=True,on_delete=models.CASCADE) participant = models.ForeignKey(Participant,blank=True,on_delete=models.CASCADE) request_time = models.PositiveIntegerField(default=0,validators=[MinValueValidator(0),]) is_survey_completed = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True,editable=False) modified = models.DateTimeField(auto_now=True) Already try to figure this out too: many-to-many select_related in django class-based list view How to Access Many to many field in class based views in Django? views.py class SeminarListView(ListView): template_name = 'show_seminar.html' model = Seminar context_object_name = 'seminar' def get_queryset(self): queryset = Seminar.objects.prefetch_related('assessment_set').filter(participant__user=self.request.user).order_by('created') return queryset show_seminar.html <div class="row mt-5"> {% for obj in seminar %} <div class="col-sm-6"> <div class="card mt-2"> <div class="card-header"> <h4 class="text-center">{{obj.topic}}</h4> </div> <div class="card-body"> <a href="{%url 'seminar:question' 1 %}"><button>Go For Seminar</button></a> </div> <div class="card-footer"> </div> </div> </div> {% endfor %} </div> <div> {% for obj in seminar.seminarparticipant_set.all %} <p>{{obj}}</p> {% endfor … -
How to send whatsapp messages when data is inserted into database using django
I want to send a Whatsapp number to the number inserted into the sqlite. I am new to python and Django. class Invoice (models.Model): product_name = models.CharField(max_length=255) product_description = models.CharField(max_length=255) quantity = models.PositiveIntegerField() unit_price = models.PositiveIntegerField() total_price = models.PositiveIntegerField() buyer_name = models.CharField(max_length=100) buyer_phone_number = models.CharField( validators=[phone_regex], max_length=17) date = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): client = Client(account_sid, auth_token) from_whatsapp_number = 'whatsapp:+14155238886' to_whatsapp_number = 'whatsapp:%d' % buyer_phone_number client.messages.create(body='Invoice created', from_=from_whatsapp_number, to=to_whatsapp_number) super(Invoice, self).save(*args, **kwargs) def __str__(self): return self.product_name It seems it cannot read the variable. -
Should I use djang.contrib.users for federated sigins?
I plan to use it for singing iin though Fb and google I also want to store additional info like whether they are signed in through google or fb. -
Pinax Stripe not validating webhook messages
I've hooked up Stripe webhooks with my Django server running pinax stripe. My Stripe dashboard indicates the webhooks are be successfully handled, but when I look in my site admin page, all webhook messages show validated=Unknown. Also, the webhook payload has not been parsed. As a side note, I've also noticed that running manage.py sync_plans syncs all plan fields except metadata. I am using pinax version 4.4.0 -
How to manually fill a form field after being submitted using a value passed to the URL in Django?
I have this form where the user has to upload a file(receipt) and then connect that file with a foreign key. I have created a simple form which takes the file, and it is working fine too. But, I have to save that file in the database, along with a foreign key to another model. Right now my model just has the file as relation and the foreign key. My form has just the field for the file upload because I obviously do not want the user to select what foreign key it is supposed to be. I want that foreign key to be filled automatically with the value given in the URL. I am calling the function like so: href="{% url 'suppliers:model_form_upload' quiz.id %}" where I am getting the quiz.id correctly. This is my model: class Uploaded_pod(models.Model): document = models.FileField(upload_to='pods/') lr_connected = models.ForeignKey(LR, on_delete=models.CASCADE, related_name='lr_pod') What I Tried This is my views.py function: def pod_upload (request, pk): lr_object = get_object_or_404(LR, id=pk) if request.method == 'POST': form = UploadPODform(request.POST, request.FILES) form.lr_connected = lr_object form.save() if form.is_valid(): form.lr_connected = lr_object form.save() return redirect('home') else: form = UploadPODform() form.lr_connected = lr_object return render(request, 'classroom/suppliers/model_form_upload.html', {'form': form}) As you can see, I am … -
Adding Video Field in Django
I want be add a video field in the django.I am not able to add it. How can I add a videofield in django in the admin portion like that of ImageFeild? -
how to Integrate modules of python scripts and print result on html
I am new to django and python. I want to execute a python script (not from views.py) and display the results to an HTML file as output. The problem is with modules. There are three modules that the python script getoffense.py uses. I have tried to run the script but it gives me modules import error below. I have saved the modules in a directory "modules" in my main app "Project1" and the python script is in my main project i.e. Project1. The modules i have imported are running indirectly when i am running getoffense.py. this is my project tree. C:. ├───.idea └───project1 ├───modules │ └───__pycache__ ├───templates └───__pycache__ when this was not integrated with django the file structure was scripts |--modules |--RestApiClient.py |--config.py |--SampleUtilities.py |--siem |-getoffense.py |--config(type=configuration settings) This worked fine when executed seperatly I tried executing the file in django project as view. please help me out get rid of this issue. I have tried integrating it just as we do views.py and display the data in home.html getoffense.py from django.shortcuts import render import importlib sys.path.append(os.path.realpath('./modules')) client_module = importlib.import_module('./modules/RestApiClient') SampleUtilities = importlib.import_module('./modules/SampleUtilities') def getalloffense(request): # First we have to create our client client = client_module.RestApiClient(version='9.0') # ------------------------------------------------------------------------- # Basic … -
AttributeError: 'QuerySet' object has no attribute 'id'
I-m trying to show a date on the template, and I have that in the get context data but it gives me this error. def get_queryset(self): """Get queryset for loan list.""" approved_loans = self.model.objects.order_by('-date_disbursed').filter( Q(status=Loan.LOAN_STATUS_PENDING) | Q(status=Loan.LOAN_STATUS_ON_LOAN) | Q(status=Loan.LOAN_STATUS_CLOSED) | Q(status=Loan.LOAN_STATUS_WRITTEN_OFF) | Q(status=Loan.LOAN_STATUS_RESCHEDULED) ) loan_performances = LoanPerformance.objects.order_by('loan__id', '-date_created').distinct('loan__id') for loan in approved_loans: loan_performance = loan_performances.filter(loan=loan).first() if loan_performance and loan_performance.interest_due_today and loan_performance.principal_due_today: loan.amount_due = loan_performance.interest_due_today + loan_performance.principal_due_today return approved_loans def get_context_data(self, **kwargs): """Get loan list context.""" context = super(LoanListView, self).get_context_data(**kwargs) loan_manager = LoanManager(self.get_object().id) context['page_name'] = 'loan_list' context['summary'] = { 'end_date': loan_manager.get_repayment_end_date(), } # data uploaded from sheets is stored in session immediately after context['uploaded_data'] = self.request.session.get('uploaded_data') if context['uploaded_data']: del self.request.session['uploaded_data'] return context def get_object(self, queryset=None): """Get loan detail object.""" return self.model.objects.all() -
What should I do - I want to allow user to search by username or email address for password reset
I am using Django in- built password_reset form. But it doesn't allow user to search by username for password reset. It only allows search by email address. I want to allow user to search by username or email for forgot password. -
Admin Panel Showing Only User ManyToManyField Area
my model has manytomany field in django and when I want to show it in admin panel, it appears in other user's objects, how can I show only those objects of that user? -
Writing a csv file into SQL Table using python
Hi I am trying to write a csv file into a table in SQL Server database using python. I am facing errors. Here is the code I am executing. CSV file contains more than 500 rows def LoadFile(self, hierarchySetId, fileName): try: with open('csvfilePath', 'r') as f: reader = csv.reader(f) columns = next(reader) query = ( 'INSERT INTO DummyTprFileType (RBNode1,RBNode2,RBNode3,RBNode4,RBNode5,RBNode6,RBNode7,BusinessSegment,DividendPartner,Region,TPRRBNode1,TPRRBNode2,TPRRBNode3,TPRRBNode4,TPRRBNode5,TPRRBNode6,TPRRBNode7,TPRRBNode8,TPRRBNode9,TPRRBNode10,TPRRBNode11,TPRRBNode12) values ({1})' ) cursor = connection.cursor() for data in reader: cursor.execute(query, data) cursor.commit() except pyodbc.Error as err: print('Error') print(err.args[0]) return True TypeError at /api/tprMappings/loadMappingsFile/ not all arguments converted during string formatting Request Method: GET PyCharm Terminal shows below: (0.000) QUERY = 'INSERT INTO DummyTprFileType (RBNode1,RBNode2,RBNode3,RBNode4,RBNode5,RBNode6,RBNode7,BusinessSegment,DividendPartner,Region,TPRRBNode1,TPRRBNode2,TPRRBNode3,TPRRBNode4 ,TPRRBNode5,TPRRBNode6,TPRRBNode7,TPRRBNode8,TPRRBNode9,TPRRBNode10,TPRRBNode11,TPRRBNode12) values ({2})' - PARAMS = (); args=['IST', 'Global Gas', 'Canada', '', '', '', '', '', 'Post Dividend', 'Americas', 'IST', 'Global Oil', 'Global Crude', 'Canada', 'Canada Crude Trading', '1C', '', '', '', '', '', ''] -
Requested setting INSTALLED_APPS, but settings are not configured
when I try to import "models" into my scraper, I get this error. The error appears when I try running the scraper. from django.movierater.api.models import * Error: from django.movierater.api.models import * ModuleNotFoundError: No module named 'django.movierater' I think the code below is what I need in a scraper, but the problem is also with it: import os os.environ['DJANGO_SETTINGS_MODULE'] = 'movierater.api.settings' django.setup() from movierater.api.models import * When I try : from api.models import * I get: % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Here is my scraper: import requests from bs4 import BeautifulSoup as bs from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from collections import Counter url = 'https://teonite.com/blog/page/{}/index.html' all_links = [] headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0' } with requests.Session() as s: r = s.get('https://teonite.com/blog/') soup = bs(r.content, 'lxml') article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')] all_links.append(article_links) num_pages = int(soup.select_one('.page-number').text.split('/')[1]) for page in range(2, num_pages + 1): r = s.get(url.format(page)) soup = bs(r.content, 'lxml') article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')] all_links.append(article_links) all_links = [item for i in all_links for item in i] … -
Django: Show button in template for certain group level
I have 3 groups: viewer, editor and creator. I want to show the right amount of button according to the permissions. viewer: can see list and detail editor: viewer permissions + can edit creator: editor permissions + can create and delete I've tried to run this for the template: {% load groupfilter %} {% if request.user|group:"creator" %} <p>creator permissions</p> {% endif %}{% if request.user|group:"editor" || request.user|group:"creator" %} <p>editor permissions</p> {% endif %}{% if request.user|group:"editor" || request.user|group:"creator" || request.user|group:"viewer"%} <p>viewer permissions</p> {% endif %} but I get this error: Could not parse the remainder: '||' from '||'. groupfilter.py: from django import template register = template.Library() @register.filter(name='group') def group(u, group_names): return u.groups.filter(name=group_names) What have I done wrong? Is there an easier way to do this? Thanks -
Converting aggregate of total length of ListField value from all rows based on condition on another column in django
I am using this code to find number of values in list field imported_leads based on condition on other column message_from by iterating over for loop. om_leads = OttMessage.objects.filter(message_from=message_from, imported_leads__0__exists=True) total_leads_count = 0 for lead in om_leads: total_leads_count+=1 print total_leads_count Is there any way to find total_leads_count variable value efficiently? I am trying to use aggregate to find total_leads_count but don't know how to use it on ListField in django. Can anybody help me or give some direction. Thanks -
How to disallow adding a specific plugin to a PlaceholderField in a custom Django (CMS) application
I made a custom Django app for adding simple blog posts functionality with different sections that can be hooked to any page showing a selected section. It was made as an Apphook to a Django CMS page. It works by adding the post's title and metadata (date etc.) and upon save there is an Edit button to live edit the post on a page. I am using the PlaceholderField model field which adds a placeholder that accepts all the available plugins. Since I also made a CMS Plugin that can show Latest posts from any available section I would like to prevent users to add the CMS plugin to my post's detail page placeholder since it raises the RecursionError. The thing is, a CMS plugin should not be added to the application's PlaceholderField. I managed to resolve the problem (for now) by adding the CMS_PLACEHOLDER_CONF to my settings.py file with the restriction for my Latest Posts plugin but since it is a GitHub public repo I would like to disallow it in my app's config by default if possible. It currently works as follows. CMS_PLACEHOLDER_CONF = { 'post_detail': { # name of my model's PlaceholderField 'name': _("Post content"), # override … -
Type error in models.py - 'str' object is not callable
After data migration I want to assign settings.AUTH_USER_MODEL user.username to author field. @property def author(self): return self.user.username() #'line-17' getting: TypeError at /posts/ (homepage) 'str' object is not callable models.py in author, line 17