Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AES - changing a string to byte resulting in extra "/" how to avoid it
import unittest import base64 from py3rijndael import Rijndael import os import codecs #plain text a=input("Please Enter Plain text: ") plain_text = a.encode('utf-8') padded_text = plain_text.ljust(32, b'\x1b') #key key=input() key_bytes = codecs.encode(key, 'UTF-8') #key_bytes = key.encode('utf-8') #two change string to byte #base64_key_bytes = base64.b64encode(key_bytes) #base 64 encryption key_bytes = key_bytes[2:-1] print(key_bytes) #encryption rijndael_key = Rijndael(key_bytes, block_size=32) cipher = rijndael_key.encrypt(padded_text) print(cipher) I m changing a string (generated using os.urandom() and passed the form ) to byte to use as a key for aes algorithm but its resulting in adding one extra "/" to the actual required values please help me with this -
MySQLdb._exceptions.ProgrammingError: %d format: a number is required, not bytes [closed]
3: Please press 3 to process one posting. Please select action: 3 You have selected: 3 Starting ... UniquePostingID: 800 from here the error ocurrs: mysqldb 800 Traceback (most recent call last): File "D:\Projects\FBMarketPlace\env\lib\site-packages\MySQLdb\cursors.py", line 201, in execute query = query % args TypeError: %d format: a number is required, not bytes During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:/Projects/FBMarketPlace/main.py", line 35, in <module> main() File "D:/Projects/FBMarketPlace/main.py", line 26, in main post_one.post_one() File "D:\Projects\FBMarketPlace\post_one.py", line 39, in post_one cursor.execute(config.sql_one_posting, PostID) File "D:\Projects\FBMarketPlace\env\lib\site-packages\MySQLdb\cursors.py", line 203, in execute raise ProgrammingError(str(m)) MySQLdb._exceptions.ProgrammingError: %d format: a number is required, not bytes I am using this query but it's not working and in MySQL it is showing a syntax error: SELECT vwAllUniqueListings.*, tblPersons.fbEmailAddress, tblPersons.fbPassword, tblPersons.fbExactName FROM vwAllUniqueListings LEFT OUTER JOIN tblPersons ON vwAllUniqueListings.personUniqueID = tblPersons.personUniqueID WHERE **(vwAllUniqueListings.UniquePostingID =%d)** ORDER BY vwAllUniqueListings.UniquePostingID* This is occurring in a Django/MySQLdb application. -
SQL identifier parts must be strings
I am trying to create a database based on user input. Whenever I tried I have following error "SQL identifier parts must be strings". Please check and support to clear this issue. def dbcreation(request): if "GET" == request.method: dbname = request.GET.get('username') return render(request, 'dbcreation.html', {}) else: dbname = request.GET.get('username') con = psycopg2.connect(user='postgres', host='127.0.0.1',password='test@123') con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = con.cursor() cur.execute(sql.SQL("CREATE DATABASE {}").format(sql.Identifier(dbname))) # print("Your DB has been created!.. Your DB Name is :" + dbname + ";") return render(request, 'dbcreation.html', {'username': dbname}) <form role="form" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <label for="username">Enter Workspace Name Here :</label> <input id="username" type="text" name="username"> <input type="submit" value="OK"> </form> -
Dajngo- Error Field 'id' expected a number but got string
There is a table like this: +---+----+-------+------+ | | id | color | type | +---+----+-------+------+ | 1 | 1 | Blue | 2 | +---+----+-------+------+ | 2 | 2 | Green | 4 | +---+----+-------+------+ | 3 | 3 | White | 5 | +---+----+-------+------+ | 4 | 4 | Red | 6 | +---+----+-------+------+ | 5 | 5 | Gray | 8 | +---+----+-------+------+ In template, there are two fields to do search in this table. One field for searching for color that is a string, and the other for type that is a number. In views.py I have this filter: results = models.MyModel.objects.filter(Q(color__iexact=search_query) | Q(type=search_query)) If I search for a number it shows some results, while searching for a string results in error as below: ValueError at /search/ Field 'id' expected a number but got 'White'. What should I do to correct it? -
Django-allauth templates missing from site-packages
I installed allauth. all up and running correctly etc but now i want to customise my forms I cannot find the allauth templates inside my site-packages. Wondering if there is a step I missed during installation to make sure these are available? -
Emails can't be sent to my gmail using Django
what i have in settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'pi**@gmail.com' EMAIL_HOST_PASSWORD = '********' what i have on forms.py from django import forms class contactEmail(forms.Form): contact_name=forms.CharField(required=True) contact_email=forms.EmailField(required=True) subject=forms.CharField(required=True) contact_message=forms.CharField(widget=forms.Textarea,required=True) what i have on views.py from django.shortcuts import render from Myportfolio.forms import contactEmail from django.core.mail import send_mail from django.conf import settings def contact(request): if request.method=='GET': form=contactEmail() else: form=contactEmail(request.POST) if form.is_valid(): name=form.cleaned_data['contact_name'] subject = form.cleaned_data['contact_subject'] email=form.cleaned_data['contact_email'] message=form.cleaned_data['contact_message'] send_mail(name, subject, email, message, ['pinkymononyane@gmail.com', email]) return render(request, 'Myportfolio/contact-me.html', {'form': form}) what i have on contact-me.html <form method="post" class="breakable contactUsForm " data-thanks-msg="Thank you for contacting me, I have received your message and I will come back to you shortly" data-date-format="m/d/Y" data-click-action=""> {% csrf_token %} <div class="col-md-12"> <div class="row"> <div class="col-md-12"> <div class="form-group"> <input type="text" name="contact_email" placeholder="From Email address" class="form-control s123-force-ltr" data-rule-email="true" data-msg-email="Please enter a valid email." required data-msg-required="This field is required."> </div> </div> <div class="col-md-12"> <div class="form-group"> <input type="text" name="contact_subject" placeholder="Subject" class="form-control"> </div> </div> </div> <div class="form-group"> <input type="text" name="contact_name" placeholder="name" class="form-control" required data-msg-required="This field is required."> </div> <div class="form-group"> <textarea class="form-control" name="contact_message" placeholder="Message" style="min-height: 100px;" required data-msg-required="This field is required."> </textarea> </div> <button type="submit" class="btn btn-primary btn-block">Contact Me</button> </div> <input type="hidden" name="w" value=""> <input type="hidden" … -
Global variables not receiving data from computed variables hence data can't be displayed on html doc using django
***here is what I have in my models.py from django.db import models # Create your models here. global_msp = 0 global_mspSales = 0 global_ago = 0 global_agoSales = 0 class Stock(models.Model): global global_msp global global_ago msp = models.IntegerField(blank=True, null=True) msp2 = models.IntegerField(blank=True, null=True) ago = models.IntegerField(blank=True, null=True) total = models.IntegerField(blank=True, null=True) date_posted = models.DateTimeField(auto_now=True) def __str__(self): return 'Stock{}'.format(self.id) class Meta: verbose_name_plural = 'Opening Stock' def Total(self): x = self.msp y = self.msp2 ans = x + y return ans total = property(Total) global_msp = total global_ago = ago class Sales(models.Model): global global_mspSales global global_agoSales msp_sales = models.IntegerField(blank=True, null=True) # msp sales value put by user ago_sales = models.IntegerField(blank=True, null=True) # ago sales value put by user total_sales = models.IntegerField(blank=True, null=True) # to be automatically computed msp_price = models.IntegerField(blank=True, null=True) # msp price value put by user ago_price = models.IntegerField(blank=True, null=True) # ago price value put by user msp_mult_price = models.IntegerField(blank=True, null=True) # to be automatically computed ago_mult_price = models.IntegerField(blank=True, null=True) # to be automatically computed total_mult_price = models.IntegerField(blank=True, null=True) # to be automatically computed def __str__(self): return 'sales {}'.format(self.id) class Meta: verbose_name_plural = 'Sales Unit & Cash' global_mspSales = msp_sales global_agoSales = ago_sales def salesTotal(self): x = self.msp_sales + self.ago_sales … -
Django JsonResponse doesnt work when using a helper function
Question summary: How can I use helper functions(not the view itself) to send JsonResponse? Issue summary: I am trying to send a JsonResponse containing dynamically updated data to a ChoiceField and I have achieved partial success but I lack understanding of something foundamental in the process obviously. The idea is when the date in the corresponding field changes, to fire up a function that gets the available hours from the DB for the selected day and updates the hours field for a date. The available hours are fetched by another helper function that belongs to the Form itself(code below). I have achieved partial success where everything works when the JsonResponse is sent directly by the View, however since I have to do this in 2 places at least, I would like to keep the code DRY. Therefore I wanted to implement a helper function that is called whenever the request.is_ajax() and sends the response to the endpoint. Below is the default code that works. View: def booking(request): if request.method == "POST": form = BookingForm(request.POST) if form.is_valid(): ////Creates a booking and redirects to home return redirect('home') else: form = BookingForm() if request.is_ajax(): date = request.GET.get('date') new_form = form(data={"timestamp": date}) # hours … -
How to create an immutable copy of the django model in python?
I want to create an immutable copy of the model instance, such that the user be able to access the details of the model, including its attributes, but not the save and the delete methods. The use case is that there are two repos accessing the django model, where one is supposed to have a writable access to the model, while another should only have a readable access to it. I have been researching ways of doing this. One way, I could think is the readable repo gets the model instance with a wrapper, which is a class containing the model instance as a private variable. class ModelA(models.Model): field1=models.CharField(max_length=11) class ModelWrapper: def __init__(self,instance): self.__instance=instance def __getattr__(self,name): self.__instance.__getattr__(name) The obvious problem with this approach is that the user can access the instance from the wrapper instance: # model_wrapper is the wrapper created around the instance. Then # model_wrapper._ModelWrapper__instance refers to the ModelA instance. Thus instance = model_wrapper._ModelWrapper__instance instance.field2="changed" instance.save() Thus, he would be able to update the value. Is there a way to restrict this behaviour? -
django redirect after post with post parameters after update
I was looking for help but couldn't find any suitable solution. I would like to ask about redirect after POST. Situation looks as below step by step: Simple search form with POST with parameter called 'find' within form. Search form appears on every site and if i call search on site with devices i'm checking referrer and i'm doing query for device model fields and results go to devices.html template. Same situation is when I search within localization site, checking for referrer and querying for model fields of localization model and returning query result in localization.html template. When I try to update device i'm opening new edit device template with url '/edit/device/dev_id' when every field of this model is shown so i can update some fields manually. After commiting changes on edit site device 'post' goes to url 'update/device/dev_id' and changes to device are saved properly. The problem is how can I redirect after updating device to step number one where are the results of search view for devices? If i redirect after update ('update/device/dev_id') device to 'request.META.get('HTTP_REFERER')' i'm getting 'edit/device/dev_id' url ? Worth to mention is that method POST for search form sends text search input to action="/search" and … -
Question and answer object matching in quiz
I have a question answer quiz. I have 2 pages. On the first page the user fills in the question and writes the answer, on the second page these questions come out and then have to have the Answer model input to check if the question was answered correctly, but when I return the questions to html and output the answer fields do not match without manually selecting. Here is such a result . I want the instance to automatically match but I do not want to pass the id in the view. I want all the questions to come out on one page. I could not figure out if I should use the model formset or anything else. How to automatically match the Answer input query models.py from django.db import models class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE, related_name="questions") answer=models.CharField(max_length=100,blank=True) def __str__(self): return str(self.questin) forms.py from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Question,Answer class QuestionForm(forms.ModelForm): class Meta: model=Question fields="__all__" class AnswerForm(forms.ModelForm): class Meta: model=Answer fields="__all__" views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts … -
Parse JSON nested data from Requests POST response
I'm working on a project using Python(3.7) in which I have to parse a JSON returned from the POST request using Requests library. I googled a lot and tried too many solutions but nothing helped me, so don't mark this as duplicate, please! Here's what I have tried: def process_req(payload): try: headers = { 'Content-Type': 'application/json' } data = payload resp = requests.post( 'http://<EXAMPLE_URL>', data=data, headers=headers ) print('returned data: {}'.format(resp.content.decode('utf8').replace("'", '"'))) resp = resp.content.decode('utf8').replace("'", '"') When I print the resp it provide the following JSON: { "code": "00", "message": "Successful", "data": "{\"requestId\":\"0012602\",\"responseCode\":\"68\",\"responseDescription\":\"Invalid Institution Code\"}" } Now, I need to access the data field of that JSON, here what I tried: resp['data'] But it returns an error as: string indices must be integers -
What is the best practice to let users set a variable which is then be available for all views?
The app I'm working on is a kind of an internal portal for the big Holding (Group of Companies), where various financial and non-financial data stored for all the companies of the Holding. Users are logging into the portal and on the home page they see the list of all Companies that they are authorized to see. Then user should be able to enter into one particular Company from the list and afterwards all subsequent views should show data filtered only for that selected Company until user does not exit it and enter into another Company from home page. I'm trying to achieve this functionality by following but I'm not sure is it proper django way to do it: In views.py I have Mylogin view which is setting global variable Selected_Company='None' when User logs in. Then when User selects any particular Company to work with that Selected_Company variable gets that company's name as a value. All other views which show company related data have a django filter showing model objects matching with the value of Selected_Company. If you know any other proper way to do it, I'd appreciate your advice. Thx -
django test - how to avoid the ForeignKeyViolation
I am struggling to create tests with django with objects that have foreign keys. The tests run with no errors when run individually, but when running all, i get ForeignKeyViolation in the teardown phase (which I don't understand what it does and can't find any info on it). When starting the testsuite I am creating a bunch of dummy data like this: def setUp(self) -> None: create_bulk_users(5) create_categories() create_tags() create_technologies() self.tags = Tag.objects.all() self.categories = Category.objects.all() self.technologies = Technology.objects.all() The problems I need help figuring out are: What exactly the teardown phase does? Are there any detailed docs on it? How should I structure my tests so to avoid the ForeignKeyViolation issue? -
django subprocess.call doesn't work properly when deployed with apache
I have an apache server on centos 7 that run django, in django web I receive http request and pass some parameters to another python file (call file_1) via subprocess.call, in file_1 I'm trying to access database (sqlite3) and change the value in it, for some reason the database doesn't change anything. But when I tested with the following they ran correctly: 1. python command with parameters: python3 file_1 para_1 para_2 2. run webserver with command: python3 manage.py runserver 0.0.0.0:80 -
Django model.py Many To Many Error Query clash
I am trying to create my model.py with a many to many relationship between 2 tables as per the Django practice like follows: class Options(models.Model): # Many to many relationship with Payment OPTIONS_CHOICES = ( ('yearly', 'YEARLY'), ('bi-yearly', 'BI-YEARLY'), ('quarterly', 'QUARTERLY'), ('monthly', 'MONTHLY'), ('weekly', 'WEEKLY'), ('daily', 'DAILY')) can_be_paid_yearly = models.CharField(max_length=25, choices=OPTIONS_CHOICES, default='yearly') payment = models.ManyToManyField('Payment', through='PaymentOptions') def __str__(self): return self.can_be_paid_yearly class Payment(models.Model): # Many to many relationship with Options price = models.PositiveIntegerField() deposit = models.PositiveIntegerField() options = models.ManyToManyField('Options', through='PaymentOptions') def __str__(self): return self.price, self.deposit class PaymentOptions(models.Model): payment = models.ForeignKey('Payment', on_delete=models.SET) options = models.ForeignKey('Options', on_delete=models.CASCADE) This is the error I get: ERROR: rental.Options.payment: (fields.E303) Reverse query name for 'Options.payment' clashes with field name 'Payment.options'. HINT: Rename field 'Payment.options', or add/change a related_name argument to the definition for field 'Options.payment'. rental.Payment.options: (fields.E303) Reverse query name for 'Payment.options' clashes with field name 'Options.payment'. HINT: Rename field 'Options.payment', or add/change a related_name argument to the definition for field 'Payment.options'. How to fix this error and what am I doing wrong? -
Django: export excel using openpyxl
I've faced a problem with exporting of an instance of a model. I have a function that renders a detail view of model and I'd like to export some information about that instance in excel, but my code doesn't work. Hope you have a answer! Thanks)) **def exportToExcel(wb): with NamedTemporaryFile() as tmp: wb.save(tmp.name) tmp.seek(0) stream = tmp.read() response = HttpResponse(content=stream, content_type='application/ms-excel', ) response['Content-Disposition'] = 'attachment; filename=Inform.xlsx' return response def equipment_SIDatailView(request, pk): equip_obj=Equipment_SI.objects.get(pk=pk) parts_obj=Equip_SI_part.objects.filter(name_of_equip=equip_obj) wb = Workbook() ws = wb.active ws.title = "Kniga" ws['A1']='Название оборудования' ws['A2']=equip_obj.name_of_equipment book = exportToExcel(wb) dict={'partis':parts_obj,'equip':equip_obj,'book':book} return render(request,'reestrOMVOiG/equipment_datail.html', context= dict)** HTML **<p><b>Примечание:</b> {{equip.fact}}</p> <p><b>Наименование оборудования:</b> {{equip.name_of_equipment}}</p> <a href="{{book}}">Карточка</a>** -
How to call a function within a function from another function in Django
I'm trying implement Test numbering scheme. On the screen to display/modify a numbering scheme there is a button to test that scheme. Goal of that button is, that the numbering scheme can be tested using the def testnums, which should calll the def nextNums. The result should be displayed in a way you can define, but as such, that the user can easily see, if the increment produced the desired result. [Test numbering scheme][1]`@login_required def nextNums (request, inAppName): try: numsEntry = get_object_or_404(RDdbNums, application=request.inAppName) except: numsEntry = RDdbPref() numsEntry.application = inAppName numsEntry.nextnbr = inAppName + "-000001" numsEntry.scheme = inAppName + "-nnnnnn" numsEntry.ncount = 6 numsEntry.reccount = 1 numsEntry.recincr = 1 numsEntry.Comment = "default value created by rddb" numsEntry.createdBy = request.user numsEntry.modifiedBy = request.user nextNumNbr = numsEntry.nextnbr writeLogfileEntry(request, 0, 'nextNums.nextnbr ' + inAppName + ' ' + nextNumNbr) numsEntry.nextnbr = numsEntry.scheme writeLogfileEntry(request, 0, 'numsEntry.scheme ' + inAppName + ' ' + numsEntry.nextnbr) numsEntry.nextnbr = (numsEntry.nextnbr.replace("YYYY", datetime.datetime.today().strftime('%Y'))) numsEntry.nextnbr = (numsEntry.nextnbr.replace("yy", datetime.datetime.today().strftime('%y'))) numsEntry.nextnbr = (numsEntry.nextnbr.replace("MM", datetime.datetime.today().strftime('%m'))) numsEntry.nextnbr = (numsEntry.nextnbr.replace("DD", datetime.datetime.today().strftime('%d'))) nextNumTxt = str(numsEntry.reccount) while len(nextNumTxt) < numsEntry.ncount: nextNumTxt = '0' + nextNumTxt if numsEntry.ncount == 9: numsEntry.nextnbr = (numsEntry.nextnbr.replace("nnnnnnnnn", nextNumTxt)) elif numsEntry.ncount == 8: numsEntry.nextnbr = (numsEntry.nextnbr.replace("nnnnnnnn", nextNumTxt)) elif numsEntry.ncount == 7: numsEntry.nextnbr = … -
A function with the given name and argument types was not found. Why can't I search for trigram in m-t-m field?
I have a provider model that has addresses that are linked with many-to-many relationship: addresses/models.py: class Street(models.Model): town = models.ForeignKey(Town, default=None, related_name='streets', on_delete=models.CASCADE, verbose_name='') name = models.CharField(max_length=200, db_index=True, verbose_name='', help_text='') slug = models.SlugField(max_length=200, db_index=True, verbose_name='') ... The provider model itself providers/models.py: class Provider(models.Model): location = models.ManyToManyField(Street, db_index=True, symmetrical=False, related_name='providers', verbose_name='') name = models.CharField(max_length=200, db_index=True, verbose_name='') slug = models.SlugField(max_length=200, db_index=True, verbose_name='') ... Next, I want to do a search for the client. The bottom line is that the client enters the name of the street, and as a result he gets a list of all providers that match the search query on the street. Since people tend to make mistakes in street names, I decided to use trigram. So this is the search query handler home/views.py: def providers_search(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] results = Provider.objects.annotate( similarity=TrigramSimilarity('location', query), ).filter(similarity__gt=0.3).order_by('-similarity') context = { 'form': form, 'query': query, 'results': results, } return render(request, 'home/search.html', context) And here is a simple form for entering a request home/forms.py: class SearchForm(forms.Form): query = forms.CharField() I end up getting an error that the function similarity(integer, unknown) does not exist (a function … -
How can I improve query performance in Django, N + 1 issue?
I'm having problems with the performance of Django query. Assume I have 3 models and I have 100 rows in Company table: from django.db import models class Company(models.Model): name = models.CharField() def order_count(self): return self.orders.count() def order_sum(self): return (self.orders.all().aggregate(models.Sum('total')))['total__sum'] class Customer(models.Model): company = models.ForeignKey(Company, related_name="customer", on_delete=models.PROTECT) name = models.CharField() def order_count(self): return self.orders.count() class Order(models.Model): company = models.ForeignKey(Company, related_name='orders') customer = models.ForeignKey(Customer, related_name="orders") value = models.FloatField() I want my template to show company's name and sum of its orders, then for each customer of this company, I want to show the customer name with the number of their orders. My query code in views.py is using prefetch like this: queryset = Company.objects.prefetch_related( models.Prefetch('customer', queryset=Customer.objects.prefetch_related('orders')), 'orders') My pseudocode for template: for company in queryset: print(company.name, company.order_count, company.order_sum) for customer in company: print(customer.name, customer.order_count) I've checked with Django Debug Toolbar, it takes 105 queries, with these SQL sentence (pseudo code): SELECT * FROM company SELECT * FROM customer WHERE customer.company_id IN (100 IDs of the companies) SELECT * FROM order WHERE order.customer_id IN (the IDs from previous command)(this duplicates 2 times) SELECT * FROM order WHERE order.company_id IN (100 IDs of the companies) SELECT SUM(order.value) FROM order WHERE order.company_id = %s (this … -
How to render Django page in ASP.NET core page?
I want to render Django Page in asp.net core project and do some database related operation using Django page. So please help me. -
model.save return instance id none
i have 2 models product and review class ProductReview(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) review_heading = models.CharField(max_length=30) review_date = models.DateTimeField(auto_now_add=True) review_description = models.CharField(max_length=200) review_rating = models.PositiveIntegerField() review_product_image = models.ImageField(upload_to='review_image/', blank=True) class Product(models.Model): name = models.CharField(max_length=100) price = models.IntegerField(default=0) category = models.ForeignKey(Category, on_delete=models.CASCADE) description = models.CharField(max_length=300, default='', null=True, blank=True) product_image = models.ImageField(upload_to='', blank=True) is_varient = models.BooleanField(default=False) has_varient = models.BooleanField(default=False) is_published = models.BooleanField(default=False) varient_property = models.ManyToManyField(to='store.AttributeValue', blank=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) i am saving review using form. def post(self, request, *args, **kwargs): form = ReviewForm(request.POST) if form.is_valid(): instance = ProductReview(**form.cleaned_data) instance.save() print(model_to_dict(instance)) # i have also tried form.save() but results the same # form.save() return redirect('OrderView') model_to_dict output is {'id': None, 'user': 1, 'product': 278, 'review_heading': 'nice product', 'review_description': 'ok', 'review_rating': 4, 'review_product_image': <ImageFieldFile: None>} here it returns id=none and nothing get saved. if i save child instance of product it get saved and also returns id=25 but when i save master product then it returns id=none please help me to save master product -
How Do I create database Models in Django?
Before heading straight to my issue,I would like to state that I am a newbie in Django. My database models were created in Sqlalchemy Flask. I want to write the same database model in my Django application as well. To keep it simple this is how a model was created using Sqlalchemy in Flask. flask_model.py class LeadsStatus(db.Model): __tablename__ = 'leads_status' if leadgenapp.config['TESTING']: f_key = 'companies.id' else: __table_args__ = {'schema': tbl_schema} f_key = f'' + tbl_schema + '.companies.id' id = db.Column(db.Integer, primary_key=True, autoincrement=True) company_id = db.Column(db.Integer, db.ForeignKey(f_key), nullable=False, index=True) status = db.Column(db.String(120)) users_id = db.Column(db.Integer) assign_date = db.Column(db.DateTime) companies = db.relationship('Companies', backref='leadstatus') This model contains a foreign key. My issue is while I am creating the same model it throws an error stating that f_key is not defined. This is how I have written the model. django_model.py class LeadsStatus(models.Model): __tablename__ = 'leads_status' # if leadgenapp.config['TESTING']: # f_key = 'companies.id' # else: # __table_args__ = {'schema': tbl_schema} # f_key = f'' + tbl_schema + '.companies.id' id = models.IntegerField(primary_key=True, auto_created=True) company_id = models.ForeignKey(f_key, nullable=False, index=True, on_delete=models.CASCADE) status = models.CharField(max_length=120) users_id = models.IntegerField() assign_date = models.DateTimeField() companies = models.relationship('Companies', backref='leadstatus') I understood the reason of the error but what I cannot understand is how … -
How to Add Delete view according to role based in django
Hi I am working on Tree Structure role. There are 4 roles 1.A 2.B 3.C 4.D Where A can add,delete view B,C,D and B,C,D cannot delete or view A. B can add,delete view C,D but can cannot delete A and its parent. Similary for C and D. I can create different views and use permissions in Django. But I want to implement this using one view.I will be adding the role through url suppose through url and not from choice. Please help me with this. Thanks in Advance. -
Displaying data from one database table without using id and objects.all() -django
I want to display some of the field values from member table (fullname, email, contactno, companyname etc..,) in profile page fieldset. models.py for member table class Member(models.Model): fullname=models.CharField(max_length=30) companyname=models.CharField(max_length=30) Email=models.CharField(max_length=50) password=models.CharField(max_length=12) contactno = models.CharField(max_length=30,default='anything') models.py for profile table. class Profile(models.Model): fullname=models.CharField(max_length=60) contactno=models.CharField(max_length=10) worknumber=models.CharField(max_length=10) email=models.CharField(max_length=30) companyname=models.CharField(max_length=30) timezone=models.CharField(max_length=20) here is the profile page, the data should displayed automatically