Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ForeignKey to specific queryset django
Is there a way to refer to specific object of Model? Suppose I have some models like below: # models.py class VehicleCategoryCode(models.Model): category = models.CharField(max_length=5) name = models.CharField(max_length=20) class Code(models.Model): category = models.ForeignKey(VehicleCategoryCode, on_delete=models.CASCADE) index = models.CharField(max_length=4, blank=True) label = models.CharField(max_length=50) order = models.CharField(max_length=20, blank=True) is_active = models.BooleanField(default=True) # pay attention to the Model class Vehicle(models.Model): label = models.CharField(max_length=80) model = models.CharField(max_length=30) Currently Vehicle is not linked to any model. Now Code model is ForeignKey to VehicleCategoryCode, which has two objects. In the VehicleCategoryCode the first object label (for convenience sake) will be referenced by Vehicle.label, and the second object model (once again for convenience) will be referenced by Vehicle.model. So each field in Vehicle can refer to the same model, but different objects. So basically I'm wondering if something like the pseudo code below can be achieved anyhow. class Vehicle(models.Model): label = models.ForeignKey(VehicleCategoryCode__name='label', on_delete=models.CASCADE) model = models.ForeignKey(VehicleCategoryCOde__name='model', on_delete=models.CASCADE) Any suggestion or advice would be appreciated. Thank you. -
I want to make a payment system
I am trying to make a payment system.In my site I have a virtual coin called C Coin. So whenever customer will try to make payment with c coin the product can be bought with c coin just like other payment process. For example a product price is 2000 $ and a customer has 2000 c coin in his account when he will try to buy with c coin the logic will be like this (using my imagination) if customer has enough balance to buy he can purchase, his balance will be like this (total price of product - balance). i have this method in my head but cant transform this method to reality. Here is my views.py class Index(View): def get(self, request): cart = request.session.get('cart') if not cart: request.session['cart'] = {} #products = None products = Product.get_all_products() cats = Category.get_categories() brands = Brand.get_brands() sliders = Slider.objects.all() offers = Offer.objects.all() categoryID = request.GET.get('category') brandID = request.GET.get('brand') if categoryID: products = products.filter(category__id=categoryID) if brandID: products = products.filter(brand__id=brandID) args = { 'products': products, 'cats': cats, 'brands': brands, 'sliders': sliders, 'offers': offers } return render(request, 'Home/index.html', args) def post(self, request): product = request.POST.get('product') cart = request.session.get('cart') remove = request.POST.get('remove') if cart: quantity = … -
In Django Stripe not allow to create a new Card
Why stripe(version=2.55) doesn't allow me to create a new card. its show me error return super(StripeObject, self).__getitem__(k) KeyError: 'sources' Whats wrong in my code? I think error is here stripe_card_response = customer.sources.create(source=token) class CardManager(models.Manager): def add_new_card(self, billing_profile, token): if token: customer = stripe.Customer.retrieve(billing_profile.customer_id) stripe_card_response = customer.sources.create(source=token) new_card = self.model( billing_profile=billing_profile, stripe_id=stripe_card_response.id, brand=stripe_card_response.brand, country=stripe_card_response.country, exp_month=stripe_card_response.exp_month, exp_year=stripe_card_response.exp_year, last4=stripe_card_response.last4 ) new_card.save() return new_card return None -
Dictionaries and for loops in functions
I am currently working on my first website, which is a dna translator that you can translate your dna into a certain protein. To do that, I've created a class in views that goes like this: class TranslatorView(View): template_name = 'main/translated.html' mapper_1={ #Here's the protein dictionary "aat": "Asparagine", "aac": "Asparagine", "aaa": "Lysine", "aag": "Lysine", "act": "Threonine", "acc": "Threonine", "aca": "Threonine", "acg": "Threonine", "agt": "Serine", "agc": "Serine", "aga": "Arginine", "agg": "Arginine", "att": "Isoleucine", "atc": "Isoleucine", "ata": "Isoleucine", "atg": "Methionine", "cat": "Histidine", "cac": "Histidine", "caa": "Glutamine", "cag": "Glutamine", "cct": "Proline", "ccc": "Proline", "cca": "Proline", "ccg": "Proline", "cgt": "Arginine", "cgc": "Arginine", "cga": "Arginine", "cgg": "Arginine", "ctt": "Leucine", "ctc": "Leucine", "cta": "Leucine", "ctg": "Leucine", "gat": "Aspartic", "gac": "Aspartic", "gaa": "Glutamic", "gag": "Glutamic", "gct": "Alanine", "gcc": "Alanine", "gca": "Alanine", "gcg": "Alanine", "ggt": "Glycine", "ggc": "Glycine", "gga": "Glycine", "ggg": "Glycine", "gtt": "Valine", "gtc": "Valine", "gta": "Valine", "gtg": "Valine", "tat": "Tyrosine", "tac": "Tyrosine", "taa": "Stop", "tag": "Stop", "tct": "Serine", "tcc": "Serine", "tca": "Serine", "tcg": "Serine", "tgt": "Cysteine", "tgc": "Cysteine", "tga": "Stop", "tgg": "Tryptophan", "ttt": "Phenylalanine", "ttc": "Phenylalanine", "tta": "Leucine", "ttg": "Leucine", } def translate_protein(self,phrase): protein = "" for letter in phrase: if letter.lower() in self.mapper_1: protein += self.mapper_1[letter.lower()].upper() if letter.isupper() else self.mapper_1[letter] return protein def get(self, request, … -
Unknown field(s) (username) specified for User. Check fields/fieldsets/exclude attributes of class CustomUserAdmin
After creating a custom user for my python django app, i started getting the error stated on the title. It only happens when i wan't to add a new user from the admin panel that's when i get the error "Unknown field(s) (username) specified for User. Check fields/fieldsets/exclude attributes of class CustomUserAdmin." I have tried searching for answers everywhere on the internet but no luck. admin.py: # accounts/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import User class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = User list_display = ['email', 'first_name','last_name', 'image', 'country_code','country', 'phone','state_province','city_town','address', 'postal_code',] add_fieldsets = UserAdmin.add_fieldsets + ( (None, {'fields': ('email', 'first_name', 'last_name', 'image', 'country_code','country', 'phone','state_province','city_town','address', 'postal_code',)}), ) fieldsets = ( (None, { "fields": ( ('email', 'first_name', 'last_name', 'image', 'is_staff', 'country_code','country', 'phone','state_province','city_town','address', 'postal_code',) ), }), ) search_fields = ('email', 'first_name', 'last_name') ordering = ('email',) admin.site.register(User, CustomUserAdmin) models.py: from django.contrib.auth.models import AbstractUser, BaseUserManager ## A new class is imported. ## from django.db import models from django_countries.fields import CountryField from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import AbstractUser from django.db import models class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations … -
Specifying user ID in Django
I have this model where I calculate different values based on certain fields. For example, when I calculate the total, I use the field price and * it with the quantity field. When I want to get the margin, I take the calculated total and deduct it from a field in a different class known as sales. What has been hard to implement for me, is how to automatically get the user id, such that, when the deduct function is called, it deducts from that user and not the previous entry. I have been looking for ID vs PK but I not sure how to use them. Please shed some insights. from django.db import models from numpy import array class CowData(models.Model): Product = models.CharField(max_length=20, default="") user = models.CharField(max_length=20, null=False,unique=True) item = models.CharField(max_length=20, null=True) quantity = models.IntegerField() price = models.DecimalField(decimal_places=2, max_digits=10, default=0) total = models.DecimalField(editable=True, decimal_places=2, max_digits=2, blank=True, null=True, unique=False) def __str__(self): return self.user def save(self, *args, **kwargs): self.total = array(self.total) self.total = self.price * self.quantity super().save(*args, **kwargs) class Sales(models.Model): sales = models.IntegerField(default=0, blank=False, null=False) margin = models.IntegerField(editable=True, blank=True, null=True) user = models.ForeignKey(CowData,to_field='user',max_length= 20 ,null=False, on_delete=models.CASCADE, related_name='username') def save(self, *args, **kwargs): self.margin = self.sales - CowData.objects.get(pk = 5).total if self.sales > … -
Why doesn't the MathJax preview show when using ckeditor and Django?
I'm currently trying to create a simple website using Django, with ckeditor for form fields. I would also like to integrate some Mathematics into my forms, hence why I downloaded the Mathematical Formulas plugin for ckeditor. I followed this tutorial to implement the plugin but MathJax doesn't work. This is what I added to my settings.py file CKEDITOR_CONFIGS = { 'default': { 'toolbar':'full', 'height': '400px', 'width': '100%', 'extraPlugins': ','.join( [ 'mathjax', 'widget', 'lineutils', 'dialog', 'clipboard', ]), }, } I copied the MathJax folder I downloaded into my project's static directory. I then refer to this in my models.py file: from django.db import models from django.contrib.auth.models import User from ckeditor.fields import RichTextField class Entry(models.Model): entry_title = models.CharField(max_length=100) #entry_text = models.TextField() entry_text = RichTextField(blank = True, null = True,config_name = 'default', external_plugin_resources=[( 'mathjax', '/static/entries/vendor/ckeditor_plugins/mathjax/', 'plugin.js', )]) entry_date = models.DateTimeField(auto_now_add = True) entry_author = models.ForeignKey(User, on_delete = models.CASCADE) class Meta: verbose_name_plural = "entries" def __str__(self): return f'{self.entry_title}' When I use my form, I can see the mathematical formulas symbol: Math symbol on ckeditor form When I click on it, ckeditor gives me the freedom to type whatever I want into the Tex field: Typing in Tex However, it doesn't give me a preview … -
Django: Creating a queryset by filtering out values based on threshold value(sum) particular to a column
Models: class Worker(models.Model): name = models.CharField('Worker Name', max_length=100, unique=True) joining_date = models.DateField('Joining Date', auto_now_add=True) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.name = self.name.title() super(Worker, self).save() def __str__(self): return self.name class Meta: db_table = 'workers_details' class Article(models.Model): name = models.CharField('Article Name', max_length=200, unique=True) date_created = models.DateField('Created Date', auto_now_add=True) def __str__(self): return str(self.name) + str(self.id) class Meta: db_table = 'articles' class ArticleDetail(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) date_created = models.DateField(auto_now_add=True) last_updated = models.DateField(auto_now=True) work_type = models.CharField('Type of Work', max_length=255) def __str__(self): return str(self.article.name) + " " + str(self.work_type) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.work_type = self.work_type.title() super(ArticleDetail, self).save() class Meta: db_table = 'article_details' class ArticleRate(models.Model): article_detail = models.ForeignKey(ArticleDetail, on_delete=models.CASCADE) effective_date = models.DateField("Effective Date") rate = models.FloatField("Rate") def __str__(self): return str(self.article_detail.article.name) + " " + str(self.article_detail.work_type) + " " + \ str(self.rate) class Meta: db_table = 'article_rate' class DailyRecord(models.Model): date = models.DateField() worker_name = models.ForeignKey(Worker, on_delete=models.PROTECT) rate = models.ForeignKey(ArticleRate, on_delete=models.PROTECT) pieces = models.IntegerField('No. Of Pieces') minutes_printing = models.FloatField('Screen Printing Time') def __str__(self): return str(self.date) + " " + str(self.worker_name.name) + " " + \ str(self.rate.article_detail.article.name) class Meta: db_table = 'daily_record_table' get_latest_by = 'id' As anyone can see through my models that there are different types of articles and in them, there is a … -
Unable to save m2m model form django
I have four fields in a model, one of which is a foreign key field and the other three are m2m fields. The form is opened in the modal, but the data is not being saved, no error is being given. I don't understand what I did wrong. I would be very grateful for a little help. Model: class ProductAttributes(models.Model): product = models.ForeignKey('Product', blank=True, null=True, on_delete=models.SET_NULL) size = models.ManyToManyField('ProductSize', blank=True) colour = models.ManyToManyField('ProductColour', blank=True) cupsize = models.ManyToManyField('ProductCupSize', blank=True) def __str__(self): return self.product Form: class ProductAttributesForm(forms.ModelForm): product = forms.IntegerField(label=('ID'),required=True, disabled=True) size = forms.ModelMultipleChoiceField(queryset=ProductSize.objects.all(),widget=Select2MultipleWidget, required=False) colour = forms.ModelMultipleChoiceField(queryset=ProductColour.objects.all(),widget=Select2MultipleWidget, required=False) cupsize = forms.ModelMultipleChoiceField(queryset=ProductCupSize.objects.all(),widget=Select2MultipleWidget, required=False) class Meta: model = ProductSize fields = ['product','size','colour','cupsize'] Template: {% load crispy_forms_tags %} <form id="Form" method="post" action="{% url 'accpack:products_attributes_create' product %}" class="js-product-create-form col s12" > {% csrf_token %} {% crispy form form.helper %} </form> View: def save_attribute_form(request, form, template_name, pk): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True data['form_data']= formdata else: data['form_is_valid'] = False context = {'form': form, 'product':pk} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) def attribute_create(request, pk): if request.method == 'POST': form = ProductAttributesForm(request.POST, initial={'product': pk}) else: form = ProductAttributesForm(initial={'product': pk}) return save_attribute_form(request, form, 'main/products/partial_product_attribute_form.html', pk) -
I want to store the id of one model in to another model -Django using Views
Hi, I'm new in Django. I'm working with web application where logged In user , can add a customer. the data have to store in two phase on phase is visit detail and in other phase all data will be saved through addcus Visit_Detail model is the main Model and all the other Models have Foreign Key of Visit_Detail. ***** The Problem I'm facing is that how to get the value of Visit_detail.id and sore it in another view as a Foreign key.** Here are my Models UNIVERSAL/model class Visit_Detail(models.Model): date_of_visit = models.DateTimeField(auto_now_add=True) reason_of_visit = models.CharField(max_length=200) number_of_visitors = models.IntegerField() visitors_added_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.reason_of_visit class Customer_Status_Detail(models.Model): customer_visit_id = models.ForeignKey(Visit_Detail, on_delete=models.CASCADE) customer_follow_up_by = models.ForeignKey(User, on_delete=models.CASCADE) customer_pipeline_status = models.CharField(max_length=50) customer_decision_time = models.CharField(max_length=50) customer_follow_up_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.customer_pipeline_status CUSTOMER/model class Customer_Presentation_Detail(models.Model): customer_visit_id = models.ForeignKey(UNIVERSAL.Visit_Detail, on_delete=models.CASCADE) customer_presented_follow_up_visitor_added_by = models.ForeignKey(User, on_delete=models.CASCADE) customer_presentation_at = models.CharField(max_length=30) customer_presentation_at_other = models.CharField(max_length=30, null=True) customer_material_shared = models.CharField(max_length=30) customer_material_shared_qty = models.CharField(max_length=30, null=True) customer_feedback = models.CharField(max_length=1000) customer_suggestions = models.CharField(max_length=1000) customer_concerns = models.CharField(max_length=1000) def __str__(self): return self.customer_name class Customer_Agent_Detail(models.Model): customer_visit_id = models.ForeignKey(UNIVERSAL.Visit_Detail, on_delete=models.CASCADE) customer_agent_business_address = models.CharField(max_length=500) customer_agent_works_in = models.CharField(max_length=500) customer_agent_area = models.CharField(max_length=500) customer_agent_customer_in = models.CharField(max_length=500) customer_agent_office = models.CharField(max_length=500) def __str__(self): return self.customer_agent_business_address class Customer_Buyer_Detail(models.Model): customer_visit_id = models.ForeignKey(UNIVERSAL.Visit_Detail, on_delete=models.CASCADE) customer_buyer_investment_purpose … -
Django Custom login using email not working
I am trying to log a user in via email in django, everything is working fine(code wise), no errors and functions execute in a right manner. However, when I perform a check in the template it always return false. Here is my code: authenticate_user.py def authenticate(self, request, email=None, password=None): try: user = User.objects.get(email=email) except User.DoesNotExist: messages.add_message(request, messages.INFO, 'Email or Password is not correct.') print("User not found") return None else: user_password_is_valid = check_password(password, user.password) if user_password_is_valid: print("User found") return user else: messages.add_message(request, messages.INFO, 'Email or Password is not correct.') return None return None And for the handle_login view: def handle_login(request): context= { 'title': 'Login' } if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] user = authenticate(request, email=email, password=password) print('User is', user) # This prints user no problem if user is not None: login(request, user) # No errors up to this point return redirect(reverse('mainapp:homepage')) else: return redirect(reverse('mainapp:homepage')) Now upon checking -> {% user.is_authenticated %} in the template.html it always return false. -
Problem in showing foreign key relation in view
I have a Land model with three relation which one of them is Letter and the model is: class Letter(models.Model): land = models.ForeignKey('Land', on_delete=models.DO_NOTHING) image = models.ImageField(null=True, upload_to=letter_image_file_path) text = models.TextField(null=True, blank=True) def __str__(self): return str(self.id) and its serializer is class LettersSerializer(serializers.ModelSerializer): class Meta: model = Letter fields = ('id', 'text', 'image', 'land',) read_only_fields = ('id',) and Land serializer is: class LandSerializer(serializers.ModelSerializer): utm_points = UTMPointsSerializer(many=True, read_only=True) letters = LettersSerializer(many=True, read_only=True) their views are : class BasicViewSet(viewsets.ModelViewSet): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) class LandViewSet(BasicViewSet): serializer_class = LandSerializer queryset = Land.objects.all() class UTMPointViewSet(BasicViewSet): serializer_class = UTMPointsSerializer queryset = UTMPoint.objects.all() class LettersViewSet(BasicViewSet): serializer_class = LettersSerializer queryset = Letter.objects.all() but when I send GET request it doesn't show letters field: here is the response: { "id": 1, "utm_points": [] } although utm_points and letters are exactly the same but they have different results. Land model has user relation which I removed it as simplicity. After some trials and errors I have no idea why the result does't have letters field. -
Django: Making a master site using django tenants
I would want to make my Blog django project tenant aware, whereby I have a master site and two tenants. I have been able to create the tenants, the problem is with the master site. I would want the master site to show all tenant articles. How do I go about this? I have created my master site from the settings.py file below, I get the error below: ProgrammingError at / relation "articles_article" does not exist LINE 1: ...cle"."thumb", "articles_article"."author_id" FROM "articles_... settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition SHARED_APPS = ( 'django_tenants', # mandatory 'customers', # you must list the app where your tenant model resides in 'django.contrib.contenttypes', # everything below here is optional # 'django.contrib.auth', 'django.contrib.staticfiles', 'django.contrib.sessions', # 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', ) TENANT_APPS = ( 'django.contrib.auth', 'django.contrib.staticfiles', 'django.contrib.sessions', # 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.admin', 'django.contrib.contenttypes', 'articles', 'accounts', ) INSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS] TENANT_MODEL = "customers.Client" # app.Model TENANT_DOMAIN_MODEL = "customers.Domain" # app.Model MIDDLEWARE = [ 'django_tenants.middleware.main.TenantMainMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Reader.urls' PUBLIC_SCHEMA_NAME = 'public' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { … -
django MultiValueDictKeyError is bothering me
sorry, im not good at eng.. what's wrong with my code?? plz help me ss.. Environment: Request Method: POST Django Version: 3.1.2 Python Version: 3.7.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crudapp.apps.CrudappConfig', 'crudmember.apps.CrudmemberConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\datastructures.py", line 76, in getitem list_ = super().getitem(key) During handling of the above exception (('title', '')), another exception occurred: File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Lenovo\5lues\선린 205\정통\board\djangoproject\crudapp\views.py", line 25, in postcreate blog.title = request.POST['title',''] File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\datastructures.py", line 78, in getitem raise MultiValueDictKeyError(key) Exception Type: MultiValueDictKeyError at /crudapp/postcreate/ Exception Value: ('title', '') -
running this django project but its showing me this error in manage.py
this is the error its showing me while running the django project of searchable dropdown list. I did exactly as mentioned in the youtube video but these are all the errors its showing me File "manage.py", line 23, in <module> main() File "manage.py", line 19, in main execute_from_command_line(sys.argv) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 345, in execute settings.INSTALLED_APPS File "C:\ProgramData\Anaconda3\lib\site-packages\django\conf\__init__.py", line 83, in __getattr__ self._setup(name) File "C:\ProgramData\Anaconda3\lib\site-packages\django\conf\__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "C:\ProgramData\Anaconda3\lib\site-packages\django\conf\__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\ProgramData\Anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\mahima\Downloads\dropdown\ddl\ddl\settings.py", line 58, in <module> 'DIRS': [os.path.join(BASE_DIR,'templates')], NameError: name 'os' is not defined this is my manage.py file. I have mysql installed.Can anybody tell me how to fix all these errors? I'm a newcomer #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ddl.settings') try: from django.core.management import execute_from_command_line except ImportError … -
Best way in the django templates to highlight active nav link based on path
When a navigation link is clicked and page is redirected to that link, I am trying to highlight the active link in the nav bar. I was able to achieve the highlighting by using if and else. But I would like to know is there any way better than this. Right now I have to duplicate this code again and again. <li class="nav-item"> <a {% if request.path == '/register' %} class="active nav-link" {% else %} class="nav-link" {% endif %} href=" {% url 'register' %} "> Register </a> </li> -
Python Scripts and Classes outside Django App
Apologies if this is a duplicate question. I tried searching up my question but didn't find anything. I have a Django Project with 3 Django Apps and the project directory looks like this Project |__ App_1 |__ App_2 |__ App_3 |__ views.py |__ models.py |__ scripts |__ class1.py The scripts folder has python scripts that run algorithms using data from the database. I am using the Django Queryset to retrieve data. The class1.py file would look something like this: from App_1.models import table1 . . . When doing that, I get this error: ModuleNotFoundError: No module named 'App_1' Curious, I moved class1.py to the App_1 folder and I got this error. ImportError: attempted relative import with no known parent package I am a bit confused as to why BOTH methods did not work. What would be the best way to go about this? Ideally, I want to setup my scripts so I can just declare an object in a view-based function in App_1/views.py -
rna to protein translator
I am currently working on my first website, which is a dna translator that you can translate your dna into a certain protein. To do that, I've created a class in views that goes like this: class TranslatorView(View): template_name = 'main/translated.html' mapper = { "a": "u", "t": "a", "c": "g", "g": "c" } mapper_1={ #Here's the protein dictionary "aat": "Asparagine", "aac": "Asparagine", "aaa": "Lysine", "aag": "Lysine", "act": "Threonine", "acc": "Threonine", "aca": "Threonine", "acg": "Threonine", "agt": "Serine", "agc": "Serine", "aga": "Arginine", "agg": "Arginine", "att": "Isoleucine", "atc": "Isoleucine", "ata": "Isoleucine", "atg": "Methionine", "cat": "Histidine", "cac": "Histidine", "caa": "Glutamine", "cag": "Glutamine", "cct": "Proline", "ccc": "Proline", "cca": "Proline", "ccg": "Proline", "cgt": "Arginine", "cgc": "Arginine", "cga": "Arginine", "cgg": "Arginine", "ctt": "Leucine", "ctc": "Leucine", "cta": "Leucine", "ctg": "Leucine", "gat": "Aspartic", "gac": "Aspartic", "gaa": "Glutamic", "gag": "Glutamic", "gct": "Alanine", "gcc": "Alanine", "gca": "Alanine", "gcg": "Alanine", "ggt": "Glycine", "ggc": "Glycine", "gga": "Glycine", "ggg": "Glycine", "gtt": "Valine", "gtc": "Valine", "gta": "Valine", "gtg": "Valine", "tat": "Tyrosine", "tac": "Tyrosine", "taa": "Stop", "tag": "Stop", "tct": "Serine", "tcc": "Serine", "tca": "Serine", "tcg": "Serine", "tgt": "Cysteine", "tgc": "Cysteine", "tga": "Stop", "tgg": "Tryptophan", "ttt": "Phenylalanine", "ttc": "Phenylalanine", "tta": "Leucine", "ttg": "Leucine", } def translate(self, phrase): translation = "" for letter in phrase: if letter.lower() in … -
Django X-CSRF token cannot be set in javascript fetch
I am trying to generate a csrf token in javascript and use that with a POST request using fetch. In my html, I have the following script tag under head to generate the csrf token: <head> <script type="text/javascript"> var user = '{{request.user}}' function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); console.log(csrftoken) </script> </head> Then under body, I have the following script tag where I retrieve the csrftoken variable and pass it to the 'X-CSRFToken' header in fetch(): <body> <script type="text/javascript"> console.log('Hello World') console.log(csrftoken) var updateButtons = document.getElementsByClassName('update-cart') for(i = 0; i < updateButtons.length; i++){ updateButtons[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId: ', productId, 'action: ', action) console.log('user: ', user) if(user === 'AnonymousUser'){ console.log('Not logged in.') }else{ updateUserOrder(productId, action) } }) } function updateUserOrder(productId, action){ console.log('User is authenticated. Sending data...') console.log(csrftoken) var url = '/update_item/' fetch(url, … -
Django: Read image path field from MySQL
im curently making a mini product eshop for my studies. So i have the image path in MySQL database like LOAD_FILE(C:\\product.jpg) and i want to access it in my Django project. It seems that im stuck for days. I have 2 questions. 1st, what Model Field should i use to read the image from the database's image path. And 2nd one how to read this image? class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.DecimalField(max_digits=7,decimal_places=2) image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url -
Url Pattern not matching in Routers | Django Restframewok
I have configured a viewset inheriting viewsets.ModelViewSet in views.py. And updated the urls.py to use Routers as follows router = DefaultRouter() router.register(r'snippets/<int:id>', SnippetViewSet) urlpatterns = [ path('', include(router.urls)), ] But when accessing this URL pattern it says there is no matching pattern and results in page not found. NB: Django version : 3.1, djangorestframework version 3.12.2 -
i cant seem to link to html pages in a website using django
ive been trying to develop a website using django, I can open the homepage but whenever I click on a link that's supposed to direct me to another page, it won't work def homepage(request): return render(request,'AlzaidStudApp/homepage.html') I'm not sure if I should add a new function for the rest of the pages or not urlpatterns = [ path('', views.homepage, name='home-page'), ] -
How to iterate through an html list and save the rows separately based on the content using django?
I am saving an html list into a database using python. The problem is in the html form I don't want to enter a video for every row. The code to retrieve the form data looks like this: def addworkout(request): if request.method == 'POST': exercise = request.POST.getlist('exercise[]') sets = request.POST.getlist('sets[]') reps = request.POST.getlist('reps[]') rest = request.POST.getlist('rest[]') tempo = request.POST.getlist('tempo[]') notes = request.POST.getlist('notes[]') dateInput = request.POST['date'] video = request.FILES.getlist('video[]') I tried something like this because I want to be able to leave the video row empty on some of the form rows: if dateInput == "" and video: #for x in range(len(exercise)): # workout = userworkouts(exercise=exercise[x], sets=sets[x], reps=reps[x], rest=rest[x], tempo=tempo[x], notes=notes[x], userid=request.user.id, date=date.today(),video=video[x]) #workout.save() elif dateInput == "" and not video: #for x in range(len(exercise)): # workout = userworkouts(exercise=exercise[x], sets=sets[x], reps=reps[x], rest=rest[x], tempo=tempo[x], notes=notes[x], userid=request.user.id, date=date.today()) # workout.save() else: # for x in range(len(exercise)): # workout = userworkouts(exercise=exercise[x], sets=sets[x], reps=reps[x], rest=rest[x], tempo=tempo[x], notes=notes[x], userid=request.user.id, date=dateInput,video=video[x]) # workout.save() that obviously didn't work because I either need to leave them all blank or enter a video for every row. I then tried something like this trying to iterate over it and check each instance like this: for x in range(len(exercise)): if dateInput[x] == … -
payload for POST and PUT methods in swagger
im using yasg library for make a doc for my apis.. but i have a problem: GET and DELETE methods are fine but when i want use POST or PUT method i cant define payload for them.. in parameters section it says: No parameters this is my code : class CreateGroupView(APIView): def post(self, request): try: serializer = GroupSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status.HTTP_201_CREATED) else: return Response(status=status.HTTP_400_BAD_REQUEST) except: return Response({'data': 'somethings wrong'}, status.HTTP_500_INTERNAL_SERVER_ERROR) what can i do? -
Newline for Django form field
I am using {{ FORM | linebreaksbr}} in templates, but this code put <br> in my textarea...