Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setting up gitlab CI with simple django project
I have a very simple django project with a few unit tests on it and I would like to set up Gitlab to run those tests evry time I make a new commit. I use sqlite3 for my database (I plan to change later, but for now I want to keep it simple) and I stored some of my settings variable in a .env file. Here is my .gitlab-ci.yml file (I used the default file proposed by gitlab and removed what I thought I didn't need) : image: python:latest variables: SECRET_KEY: "this-is-my-secret-key" DEBUG: "True" ALLOWED_HOSTS: "['*']" DB_ENGINE: "django.db.backends.sqlite3" DB_NAME: "test_database.sqlite3" STATIC_URL: "/static/" cache: paths: - ~/.cache/pip/ before_script: - python -V - pip install -r requirements.txt test: script: - cd backend - python manage.py test but when I commit, I get this error $ python manage.py test /usr/local/lib/python3.9/site-packages/environ/environ.py:628: UserWarning: /builds/romainros/ynoverflow/backend/ynoverflow/.env doesn't exist - if you're not configuring your environment separately, create one. warnings.warn( Creating test database for alias 'default'... Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/test.py", line 53, in handle failures = test_runner.run_tests(test_labels) File "/usr/local/lib/python3.9/site-packages/django/test/runner.py", line 629, in run_tests old_config = self.setup_databases(aliases=databases) File … -
translate rna to protein
I am currently working on a rna to protein translator. To do that, I've created a class that does two things. Firstly, you input a dna chain and it gets translated into rna (this part works perfectly) Secondly, you get the rna chain translated into a protein (this part doesn't work). Here's the code for the class: class TranslatorView(View): template_name = 'main/translated.html' rna_mapper = { "a": "u", "t": "a", "c": "g", "g": "c" } amino_mapper={ "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": … -
How to show validation error in django admin page with post_save signal?
I need to show validation error in django admin page like a clean function for a django model my post_save function: @receiver(models.signals.post_save, sender=Counter) def execute_after_save(sender, instance, created, *args, **kwargs): counter = Counter.objects.filter(order_id=instance.order_id).values('product_id').annotate(Count('pk')) counter = counter.values('pk__count').get()['pk__count'] if counter is None: counter = 0 if counter > 1: raise ValidationError("Error here") -
Need help in Django Templates(using forloops)
I have 3 models namely Uses, Customer and Services.I have a query whose result is stored in the variable count. This is the query counts = Services.objects.filter(uses__customer=customer).annotate(times_used=Count('uses')) Each count[x] has a variable,x ranges from 0 to infinity. I have used a for loop in my html to get all the Services which I have passed through context in views. Now I need to get unique value of count for each service. How can I do this. Here is my html code <table class='table table-bordered' id='dataTable' width='100%' cellspacing='0'> <thead class='bg-primary'> <tr class='text-white'> <th>Service-Id</th> <th>Service-name</th> <th>Count</th> <th>Price</th> </tr> </thead> <tbody class="text-dark"> <tr>{% for service in services %} <td>{{ service.id }}</td> <td>{{ service.service_name }}</td> <td>#code for printing code# </td> <td>{{ service.price }}</td> </tr>{% endfor %} </tbody> </table> -
Django: How to pass a variable from view to forms?
I have view document and I would like to pass the my_number variable to DocumentForm in order to define what the form should look like. **views.py** def document(request, my_number): form = DocumentForm(request.POST or None) if form.is_valid(): form.save() return redirect(f'/index/') return render(request, 'document.html', {'form': form}) I think I have to pass the my_number for example in such a way: form = DocumentForm(request.POST or None, number=my_number) And in forms.py i have: **forms.py** class DocumentForm(ModelForm): class Meta: model = Document fields = [] person = Person.objects.get(id=number) choices = person.elements for choice in choices: if choice == '1': fields.append('choice_1') if choice == '2': fields.append('choice_2') But I don't know how to call number in: class Meta and in person = Person.objects.get(id=number). I will be very grateful for any suggestions. -
Django Bootstrap Accordion needs double click to expand
When I click the accordion the first time nothing happens. When I click it a second time, it opens and then closes immediately! It's like the second click sends both. Here's my template: {% for category in challenges_by_category_list %} {% if category %} <h2>{{ category.title }}</h2> <div class="accordion" id="accordion{{category.title}}"> {% for challenge in category.challenge_set.all %} <div class="card"> <div class="card-header" id="heading{{challenge.id}}"> <h2 class="mb-0"> <button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapse{{challenge.id}}" aria-expanded="true" aria-controls="collapse{{challenge.id}}"> {{ challenge.question_text }} </button> </h2> </div> <div id="collapse{{challenge.id}}" class="collapse in" aria-labelledby="heading{{challenge.id}}" data-parent="#accordion{{category.title}}"> <div class="card-body"> Anim pariatur cliche reprehenderit, enim eiusmod high </div> </div> {% endfor %} </div> {% endif %} {% endfor %} I wondered whether it's something to do with including bootstrap twice? But here's my base.html includes: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> I've also installed crispy_forms which uses bootstrap, I don't know if that's relevant. -
'QueryDict' object is not callable
when i want run a code, create user in my blog, i get error 500 and 'QueryDict' object is not callable and problem in this row : data = form.data() my code below: def create_post(request): if request.method == 'POST': form = PostFormClass(request.POST) if form.is_valid(): form.save() data = form.data() dump = json.dumps(data) return JsonResponse(dump, content_type="application/json") return JsonResponse({"message": "invalid form"}) else: form = PostFormClass() args = {'form': form} return JsonResponse(args, content_type="application/json") -
My Django model for video upload saying "ValueError"
I am trying to write a small blog where I can be uploading my videos for public download but am getting a server error message when I try click on any video for details. Below is the error that I'm getting when Debug is set to True ValueError at /video/lagos-anthem/ Sample larger than population or is negative Request Method: GET Request URL: https://www.majestylink.com/video/lagos-anthem/ Django Version: 3.1.2 Exception Type: ValueError Exception Value: Sample larger than population or is negative Exception Location: /home/majestyempire/.virtualenvs/majestyenv/lib/python3.7/random.py, line 321, in sample Python Executable: /usr/local/bin/uwsgi Python Version: 3.7.5 Python Path: ['/var/www', '.', '', '/var/www', '/home/majestyempire/.virtualenvs/majestyenv/lib/python37.zip', '/home/majestyempire/.virtualenvs/majestyenv/lib/python3.7', '/home/majestyempire/.virtualenvs/majestyenv/lib/python3.7/lib-dynload', '/usr/lib/python3.7', '/home/majestyempire/.virtualenvs/majestyenv/lib/python3.7/site-packages', '/home/majestyempire/musicblog/myblog'] Server time: Sat, 28 Nov 2020 13:49:35 +0100 -
How to retrieve necessary fields from ModelForms and pass them to views.py properly?
Short background of whole idea: I'm trying to create landing page and for backend I use Python/Django3 framework. I need to create form with such fields as name, surname, email, mobile number and address of customer. I've decided to save all the information that the user enters in the database, and also send it to my email. In order to connect database to forms I use ModelForms in forms.py section (all the required code will be shown below). In order to connect my email to form I use send_mail function from django.core.mail. So when a user fills out his form, he is redirected to the 'thank you' page and all the information from the form is saved in the database and sent to my email. But when I finally wrote the code and started to test functionality, I found out that when I hit 'submit' form button, error <type object 'ClientInfoForm' has no attribute 'cleaned_data'> is raised. I suppose, that method cleaned_data is wrong in my case and I have to replace it with something else but I don't know with what exactly. All the code will be placed below and any help will be helpful. Thank you! Models.py file … -
Using while loop with counter in django template
I need to put a counter in while loop in template. So I did: <tbody> {% with count=1 %} {% while count <={{orders_count}}: %} {% for order in orders %} <tr> <td style="width:5%;"></td> <td>{{count}}</td> <td>{{order.name}}</td> </tr> {% count+=1 %} {% endfor %} {% endwhile %} {% endwith %} </tbody> But finaly I have the following error: Invalid block tag on line 216: 'while', expected 'endwith'. Did you forget to register or load this tag? -
DRF ManytoMany filtering on related model, in subquery?
There are two models, a Page model and a Banner model, which are manyToMany related. The parameters API is twitched, which returns a list of pages and banners for each page. The Banner model has a field is_show by which you need to additionally filter the list of banners, i.e. in the admin panel, the banner can be selected for the model, but if is_show = False, then you do not need to return it to the API. views class PagesListView(generics.ListAPIView, viewsets.GenericViewSet): queryset = Page.objects.all() serializer_class = PageSerializer models class Banner(models.Model): title = models.CharField(verbose_name='Заголовок', max_length=255, null=True, blank=True) is_show = models.BooleanField(verbose_name='Управление отображением', null=False) pages = models.ManyToManyField( Page, blank=True, related_name='banners') class Page(models.Model): name = models.CharField(max_length=255, null=True, blank=True) serializers class BannerSerializer(serializers.ModelSerializer): class Meta: model = Banner fields = '__all__' class PageSerializer(serializers.ModelSerializer): banners = BannerSerializer(read_only=True, many=True) class Meta: model = Page fields = '__all__' The question is how to filter Banner by is_show field? If you just override the queryset for the view like this: queryset = Page.objects.filters(banners__is_show=True) then this is not the desired behavior. In this way, I am filtering the Page list, and I need to "wedge" into filtering the Banner list. -
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', '')