Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Personalizations field error when sending multiple dynamic template emails in sendgrid
I'm trying to send a bulk email using Sendgrid Dynamic Templates in Django and getting this error: The personalizations field is required and must have at least one personalization. Using sendgrid 6.9.7 Does anyone see where I might be going wrong: from django.conf import settings from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, To def send_mass_email(): to_emails = [ To(email='email1@gmail.com', dynamic_template_data={ "thing_i_want_personalized": 'hello email 1', }), To(email='email2@gmail.com', dynamic_template_data={ "thing_i_want_personalized": 'hello email 2', }), ] msg = Mail( from_email='notifications@mysite.com>', ) msg.to_emails = to_emails msg.is_multiple = True msg.template_id = "d-template_id" try: sendgrid_client = SendGridAPIClient(settings.SENDGRID_API_KEY) response = sendgrid_client.send(msg) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e) print(e.body) return The output is HTTP Error 400: Bad Request b'{"errors":[{"message":"The personalizations field is required and must have at least one personalization.","field":"personalizations","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#-Personalizations-Errors"}]}' -
Modeling frontend and backend in a use case diagram
I am trying to make a use case diagram for my project, the backend is going to be made using Django rest framework and the front end using react, my question is how can i model this situation in the right way, should i model the frontend and represent the backend as an actor or the opposite, since i am thinking of making a mobile application as a second front end? -
Problem trying to add my individual products to cart
I have created a button on my webpage, I want to add my individual product to a shopping basket when I press this button, but for some reason I am getting the following error: productindividual?id=1:117 POST http://127.0.0.1:8000/apiadd/ 500 (Internal Server Error) addToCart.onclick @ productindividual?id=1:117 VM4764:1 Uncaught (in promise) SyntaxError: Unexpected token I in JSON at position 0 Promise.then (async) addToCart.onclick @ productindividual?id=1:129 Below is my code: <script> window.onload = ()=>{ let params = window.location.search; let urlParams = new URLSearchParams(params); let productID = urlParams.get("id"); // http://127.0.0.1:8000/api/products/id if(productID != null && typeof(productID)!= 'undefined'){ fetch('http://127.0.0.1:8000/api/products/'+productID) .then(resp => resp.json()) .then(data => { console.log(data); if('detail' in data){ // display some generic product not found error alert("Product Not Found!"); } else{ let name = data['name']; let desc = data['description']; let price = data['price']; let image= data['image']; // display the product data let specific1Tag = document.getElementById("myname"); // returns the specific DOM node , the P tag with id="myparagraphid" specific1Tag.innerHTML=name; let specific2Tag = document.getElementById("mydesc"); // returns the specific DOM node , the P tag with id="myparagraphid" specific2Tag.innerHTML=desc; let specific3Tag = document.getElementById("myprice"); // returns the specific DOM node , the P tag with id="myparagraphid" specific3Tag.innerHTML=price; let specific4Tag = document.getElementById("myimg"); // returns the specific DOM node , the P tag … -
django async/background for long running task
I have a django app with an endpoint that kicks off a long running task. I want to do this in the background. I know I could do this with celery or django-q, but I wanted to try something simpler first. First thing I tried was ajax. In the python code I did this: cookie = request.META.get('HTTP_COOKIE') csrf_cookie = request.META.get('CSRF_COOKIE') host = '{}://{}'.format(request.scheme, request.META['HTTP_HOST']) data = {...} resp = requests.post('{}/report/TASKS/Work/ajax/run.json'.format(host), headers={'COOKIE': cookie, 'X-CSRFToken': csrf_cookie, 'referer': host}, data=data) The function being called has the @login_required decorator, and when that runs it does the auth as the anonymous user, which fails so it redirects to the login page. The thread sending in the request is logged in and I have verified the cookies are all correct. Why would it use the anonymous user? How can I get it to auth using the logged in user? Tried something else next - instead of using ajax I call it with multiprocessing.Process. This fails because the thread does not have a database connection. Anyone have any thought on how I could make this work? -
Deploying Django API on Heroku- after changing DEBUG = False (in settings.py) and deploying my app, URLconf defined in URLS.PY are not listed
I have created Django API with three apps (users, task, house) with with help of routers show data in ViewSets. Some of these routers have to register multiple ViewSets. When testing endpoints both locally and on remote server (Heroku gunicorn) they are working. As app should be deployed in DEBUG=False mode, when I changed that in settings.py I came across a problem.! I changed DEBUG=False as expected to be on a live server. When I entred domain name generated by Heroku, I got message ::::: Not Found – The requested resource was not found on this server. I tried to enter endpoints manually (domain_name/endpoint) and it worked. Obviously I do not have anything under path(' ', include(...............)) as there is no priority for any of the three apps. I you have any idea/suggesting on how to get listed URLS admin/, api/ as on local server please let me know. Many thanks in advance. -
UnboundLocalError in django while passing an sql query
This is my error message: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/mainpage.html Django Version: 3.2.12 Python Version: 3.7.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', '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', 'whitenoise.middleware.WhiteNoiseMiddleware') Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user\desktop\dentist\website\views.py", line 40, in mainpage c.execute(query) Exception Type: UnboundLocalError at /mainpage.html Exception Value: local variable 'query' referenced before assignment This is my python views.py def logout(request): try: del request.session['your-email'] except KeyError: pass result_dict = {} result_dict['logout_success'] = 'See you next time! You have sucessfuly logged out' return render(request, 'home.html', result_dict) def mainpage(request): if 'your-email' not in request.session: if request.method == "POST": email = request.POST['your-email'] password = request.POST['your-password'] if email!='' and password!='': verification = "SELECT * FROM users WHERE email = '" + email + "' AND password = '" + password + "';" c = connection.cursor() c.execute(verification) account_exist = c.fetchall() results_dict = {} if not account_exist: results_dict = {'error':'Please try again. Entered username or password is wrong'} return render(request, 'login.html',results_dict) request.session['your-email'] = email else: query = "SELECT email, display_name, age, phone_number, vaccination_status, rating, count_rate FROM users … -
Django Python: Get the uploaded file name and add it to the body of the email message
This question is different than how to get uploaded file name in django as I need to add the file name to the body of the email message, and since all my email post and file upload code is in views.py, I'm not using a models.py file. How do I get the uploaded file name file and add it to the message part f'{form_data["message"]}' of the email? I'm not attaching the file to the email; I'm simply uploading it to the server via the forms.py. But I need to add the file name in the body of the email so I know which file has been uploaded by which email user. I am also aware that Django adds a random string of characters to the uploaded file name if it sees an existing file with the same name n the upload directory, so in that case, I need that file name included. Is that handled by file? views.py import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from django.shortcuts import render, get_object_or_404, redirect from django.core.files.storage import FileSystemStorage from contactform.forms import ContactForm from contact.settings import EMAIL_HOST_USER, EMAIL_PORT, EMAIL_HOST_PASSWORD, EMAIL_HOST def thanks(request): return render(request, 'thanks.html', {}) def contact(request): if request.method == … -
Python Django how to save many to one relationship JSON data in sqlite
I was wondering how I should go about saving data items in tables which have a many to one relationship with a model Here is the code that I got so far: models.py: class Recipes(models.Model): name = models.CharField(max_length=120, default='') pub_date = models.DateTimeField('date published') style = models.CharField(max_length=200, default='') brewer = models.CharField(max_length=100, default='') type = models.CharField(max_length=20, default='All Grain') version = models.CharField(max_length=20, default='1') batch_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0) boil_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0) boil_time = models.DecimalField(decimal_places=1, max_digits=4, default=0.0) efficiency = models.DecimalField(decimal_places=1, max_digits=4, default=75.0) ibu = models.DecimalField(decimal_places=1, max_digits=4, default=0.0) abv = models.DecimalField(decimal_places=2, max_digits=4, default=0.0) notes = models.TextField(default='') carbonation = models.DecimalField(decimal_places=2, max_digits=4, default=0.0) primary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) secondary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) age = models.DecimalField(decimal_places=1, max_digits=4, default = 0) __fermentables = [] @classmethod def create(cls,attr): recipe = cls() # do something with the book for k in Recipes._meta.fields: if k.name in attr: setattr(recipe,k.name,attr[k.name]) return recipe @classmethod def addFermentables(self,items): for itm in items: self.__fermentables.append(itm) return self.__fermentables @classmethod def addHops(self,items): for i in items: return i class RecipeFermentable(models.Model): recipe = models.ForeignKey(Recipes, on_delete=models.CASCADE) name = models.CharField(max_length=200, default='') amount = models.DecimalField(decimal_places=2, max_digits=8, default=0.0) extract = models.DecimalField(decimal_places=1, max_digits=8, default=0.0) type = models.CharField(max_length=20, default='') color= models.DecimalField(decimal_places=1, max_digits=8, default=0.0) fermentable = models.ForeignKey(Fermentable, on_delete=models.RESTRICT) def create(cls, attr, recipes): … -
How to append a list of users emails linked with a manytomany relation to other Model
First please take a look on the data structure. there are Three models class Partner(models.Model): name = models.CharField(max_length=100, blank=True, null=True) group = models.OneToOneField( Group, on_delete=models.DO_NOTHING, blank=True, null=True) class CustomUser(AbstractUser): email = models.EmailField(_('email address'), unique=True) partner = models.ManyToManyField( Partner, blank=True) class Quote(models.Model): partner = models.ManyToManyField( Partner, blank=True, related_name='quote_partners') There can be multiple partners inside the Quote and CustomUser partner field. I want to make a list of users email who are linked with Partner inside the partner field set in the quote model. This is how I'm doing; quote = Quote.objects.get(id=id) partners = quote.partner.all() for partner in partners: recipient_list = [] for user in CustomUser.objects.filter(groups__partner=partner): recipient_list.append(user.email) Currently quote object has 3 partners and collectively 4 users linked to these partners then there should be 4 emails in the the recipient_list, But this returning empty array []. Please highlight what I'm doing wrong and how to fix it. -
Database name is longer than PostgreSQL's limit of 63 characters. How to Fix it?
I am beginner in Django. I created a database on using postgresql but facing problem when try to makenigration. in my Settings.py 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.path.join(BASE_DIR,'Data_Collection'), 'USER': 'postgres', 'PASSWORD' : '1234', 'HOST': 'localhost', } } when I try to run this command python manage.py makemigrations Im seeing following error/issue: django.core.exceptions.ImproperlyConfigured: The database name 'D:\Masters_FIT\4th\Webdatabese\Project\Code\Data_Collection\Data_Collection' (75 characters) is longer than PostgreSQL's limit of 63 characters. Supply a shorter NAME in settings.DATABASES. If i do changing in my setting then connection is not establishing.. Setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'Data_Collection', 'USER': 'postgres', 'PASSWORD' : '1234', 'HOST': 'localhost', } } Then in get_new_connection connection = Database.connect(**conn_params) File "D:\Masters_FIT\4th\Webdatabese\Project\Code\data\lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? Kinldy someone tell me how to fix it. Thank you -
IntegrityError duplicate key value violates unique constraint
I found this solution on how to fix the problem I was running into: SELECT setval('tablename_id_seq', (SELECT MAX(id) FROM tablename)+1) but I am not familar with SQL statements so I don't understand what to replace the names with here. My table name is "student_course" so I assume that is what goes in tablename, but I do not understand what to do for the 'tablename_id_seq'. The error is occuring at "student_course_id_key", is that what I put for the id seq? -
i can't create user in django
I am trying to create a login and signup feature on my website but for some reason, I can't create a user. and it's not showing any error. I have done these before in another code but I don't know why it is not working in this one. And also when I refresh the website, it asks if it should resubmit the form. These are the codes below index.html <div class="main-register"> <div class="close-reg"><i class="fal fa-times"></i></div> <ul class="tabs-menu fl-wrap no-list-style"> <li class="current"><a href="#tab-1"><i class="fal fa-sign-in-alt"></i> Login</a></li> <li><a href="#tab-2"><i class="fal fa-user-plus"></i> Register</a></li> </ul> <!--tabs --> <div class="tabs-container"> <div class="tab"> <!--tab --> <div id="tab-1" class="tab-content first-tab"> <div class="custom-form"> <form method="post" action="" name="registerform"> {% csrf_token %} {% for message in messages %} <h4 style="color: red;">{{message}}</h4> {% endfor %} <label>Email Address * <span class="dec-icon"><i class="fal fa-user"></i></span></label> <input name="email" type="email" placeholder="Your Mail" onClick="this.select()" value=""> <div class="pass-input-wrap fl-wrap"> <label >Password * <span class="dec-icon"><i class="fal fa-key"></i></span></label> <input name="password" placeholder="Your Password" type="password" autocomplete="off" onClick="this.select()" value="" > <span class="eye"><i class="fal fa-eye"></i> </span> </div> <div class="lost_password"> <a href="#">Lost Your Password?</a> </div> <div class="filter-tags"> <input id="check-a3" type="checkbox" name="check"> <label for="check-a3">Remember me</label> </div> <div class="clearfix"></div> <button type="submit" class="log_btn color-bg"> LogIn </button> </form> </div> </div> <!--tab end --> <!--tab --> <div class="tab"> <div id="tab-2" … -
How to get object uid from previous page in Django web-app?
I`m trying to make a CreateView form that takes the UID of the object as a foreign key from the previous page. Here I got DetailView of Plan model: class PlanDetailView(IsStaffPermissionMixin, DetailView): model = Plan template_name = "backoffice/plans/plan_detail.html" context_object_name = 'plan' def get_object(self): uid = self.kwargs.get("uid") return get_object_or_404(Plan, uid=uid) def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) practice_sessions = PracticeSession.objects.all().filter(plan__uid=self.kwargs.get("uid")) context['practice_sessions'] = practice_sessions return context And here I got a PracticeSession CreateView: class PracticeSessionCreateView(IsStaffPermissionMixin, CreateView): model = PracticeSession template_name = "backoffice/practice_session/practice_session_create.html" fields = ['uid', 'title', 'plan', 'snippet', 'welcome_content', 'done_content', 'order_index', ] success_url = reverse_lazy('practice-sessions') As you understand, PracticalSession contains Foreign Key for the Plan model Now I want that when I click on the button to create a PracticalSession (the picture below), I create a form in which the plan field already contains a "uid" of Plan from the page of which I create a new PracticalSession My Form: class PracticeSessionCreateForm(ModelForm): class Meta: model = PracticeSession fields = '__all__' Big THANK YOU In advance !!! -
Having trouble in creating forms in django
This is my models.py file from django.db import models # Create your models here. class Blog(models.Model): name = models.CharField(max_length=120) created_on = models.DateTimeField(auto_now_add=True) class Article(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=120) body = models.TextField() draft = models.BooleanField(default=False) This is my forms.py file from blog.models import Article from django import forms class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ['title', 'body', 'draft'] Can someone tell me how do I insert the first attribute of class Article which is blog in class Articleform? I am learning django and some help will be appreciated. -
Python how to check why 2 things are not equalled
I am trying to run a test to validate that an error is thrown if I try to pick up a closed offer object, but the error is not thrown, because the comparison operator returns false, even though it recognises my offer status as closed. Only relevant code displayed below, not the full actual code: test def test_pickup_closed_offer(self): # open offer created as self.offer in test setup offer = self._CloseOfferWorkflow.close_offer(self.offer.id) logger.debug(offer.status) # CLOSED logger.debug(offer.status == Offer.STATUS.CLOSED) # TRUE with self.assertRaisesMessage(OfferClosedError, "Offer is already closed"): # Failed to raise match = self._PickupOfferWorkflow.pickup_offer( offer_id = offer.id ) django model for Offer from django.db import models from enum import Enum OFFER_STATUS_CHOICES = ( ('AVAILABLE', 'Available'), ('CLOSED', 'Closed') ) class Offer(models.Model): class STATUS(Enum): AVAILABLE = 'AVAILABLE' CLOSED = 'CLOSED' def __str__(self): return self.value status = models.CharField(max_length=256, choices=OFFER_STATUS_CHOICES) pickup_offer method class PickupOfferWorkflow: _OfferController = OfferController() def pickup_offer(self, offer_id): offer = Offer.objects.get(id=offer_id) # Validate input self._OfferController.validate_offer_pickup(offer) OfferController validator def validate_offer_pickup(self, offer): # Validate input self.validate_offer_not_closed(offer.status) def validate_offer_not_closed(self, status): if status == Offer.STATUS.CLOSED: raise OfferClosedError("Offer is already closed", "OFFER_CLOSED") logger.debug(status) #CLOSED logger.debug(Offer.STATUS.CLOSED) #CLOSED logger.debug(status == Offer.STATUS.CLOSED) #FALSE close offer class CloseOfferWorkflow: def close_offer(self, offer_id): offer = Offer.objects.get(id=offer_id) offer.status = Offer.STATUS.CLOSED offer.save() return offer The weird thing is … -
how to pass context (placeholder in my case) to django admin Simple List filter
I am creating a college management system with facility to store quiz/tests in the website and get student performance. I wanted to filter quiz based on month year, such as show all quiz of march 2022. For this purpose, I can not show all months and years in the sidebar, its useless for the first, second it will take lot of space and client has to scroll a lot. So I created a custom Simple Text Input by following some blogs. Here is that generic filter code: class SimpleTextInputFilter(admin.SimpleListFilter): template = 'admin/input_filter.html' def filter(self, request, queryset, value): raise NotImplementedError('Implement this method in subclasses.') def queryset(self, request, queryset): if self.value() is not None: return self.filter(request, queryset, self.value()) def lookups(self, *args, **kwargs): return None def has_output(self): return True def choices(self, changelist): all_choice = next(super().choices(changelist)) all_choice['query_parts'] = ( (k, v) for k, v in changelist.get_filters_params().items() if k != self.parameter_name ) yield all_choice And here is how I am using it: class QuizMonthYearFilter(SimpleTextInputFilter): parameter_name = 'date' title = 'Quiz (Month Year)' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.place_holder = 'MM YYYY' def filter(self, request, queryset, value): try: date = datetime.strptime(value, '%b %Y') except: pass else: return queryset.filter(date__year=date.year, date__month=date.month) and the html is: {% load … -
Django user.checkpassword always returns `FALSE`
I'm using a custom user auth in my Django application, and am trying to login using the API but when I use check_password it always gives me a false even if it's a correct password,, here is my code: CustomUser Model class CustomUserManager(BaseUserManager): def create_user(self, phone, password=None): if not phone: raise ValueError('Users must have a phone number') user = self.model( phone=phone, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone, password): user = self.create_user( phone, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.user_type = 'admin' user.save(using=self._db) return user class CustomUser(AbstractUser): user_type_choices = ( ('client', 'Client'), ('supplier', 'Supplier'), ('admin', 'Admin'), ) username=None phone = models.CharField(max_length=200, unique=True,verbose_name=_("Phone"),help_text=_("Phone number of the user")) user_type = models.CharField(max_length=200, choices=user_type_choices,verbose_name=_("Type"),help_text=_("Type of the user"),default='client') company_name = models.CharField(max_length=200,verbose_name=_("Company Name"),help_text=_("Company name of the supplier"),blank=True,null=True) email = models.EmailField(max_length=200,verbose_name=_("Email"),help_text=_("Email of the supplier"),blank=True,null=True) establishment_date = models.DateField(verbose_name=_("Establishment Date"),help_text=_("Establishment date of the supplier's company"),blank=True,null=True) number_of_projects = models.IntegerField(verbose_name=_("Number of projects"),help_text=_("Number of projects the supplier has"),blank=True,null=True) tax_id = models.FileField(upload_to='media/tax_id',verbose_name=_("Tax ID"),help_text=_("Tax ID of the supplier"),blank=True,null=True) logo = models.FileField(upload_to='media/logo',verbose_name=_("Logo"),help_text=_("Logo of the supplier"),blank=True,null=True) business_register = models.FileField(upload_to='media/business_register',verbose_name=_("Business Register"),help_text=_("Business register of the supplier"),blank=True,null=True) about_company = models.TextField(verbose_name=_("About Company"),help_text=_("About company of the supplier"),blank=True,null=True) USERNAME_FIELD = 'phone' REQUIRED_FIELDS = [] objects = CustomUserManager() class Meta: verbose_name = _("User") verbose_name_plural = _("Users") And … -
My django admin page gives Page not found (404)
my project was running ok I used my admin page at it was all all right today I tried to open it and it gives a Page not found (404) No Product matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/admin Raised by: store.views.product_detail No Product matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/admin Raised by: store.views.product_detail I havent touched the store app or project files at all at it was waking just fine yesterday now i cannot access admin page project urls from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls', namespace='store')), path('basket/', include('basket.urls', namespace='basket')), path('account/', include('account.urls', namespace = 'account')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) store urls from django.urls import path from . import views app_name = 'store' urlpatterns = [ path('', views.product_all, name='product_all'), path('<slug:slug>', views.product_detail, name='product_detail'), path('shop/<slug:category_slug>/', views.category_list, name='category_list'), ] store views from urllib import request from django.shortcuts import get_object_or_404, render from store.context_processors import categories from .models import Category, Product def product_all(request): products = Product.products.all() return render(request, 'store/home.html', {'products': products}) def category_list(request, category_slug=None): category = get_object_or_404(Category, slug=category_slug) products = Product.objects.filter(category=category) return render(request, 'store/products/category.html', {'category': category, 'products': products}) def … -
Django issue with urls.py about / after path
I'm starting to learn about DJANGO in one course. And I have my HTML and views.py working good, just if I use the / after the path:: path("create/", views.create, name="create"). In my video aulas I saw that the people usually don't put this /, but if I try like that: path("create", views.create, name="create") I have the error 404 Page not found even using /create in my URL. So, why seems that is just me who need's to use this ( / ) ?? -
Django Inner & Left Join
I'm trying to map SQL to Django ORM but without success. I want to map the below SQL query to Django. Can you help me out? SELECT DCon.Name, Dcon.Address1, FROM Fact FPT JOIN Profile DPP ON DPP.ProfileKey = FPT.ProfileKey JOIN Consignee DCon ON DCon.ConsigneeKey = FPT.ConsigneeKey LEFT Join Country DC ON DC.CountryID = DCon.CountryID and DC.IsCurrent = 'Y' WHERE DPP.trackingCode = SomeTrackingCode AND Dpp.Number = SomeNumber This is what i tried so far data = Fact.objects.select_related("profilekey", "consigneekey") class Fact(models.Model): profilekey = models.ForeignKey( "Profile", on_delete=models.PROTECT, db_column="parcelprofilekey" ) consigneekey = models.ForeignKey( "Consignee", on_delete=models.PROTECT, db_column="consigneekey" ) dateordered = models.DateTimeField() dateprocessed = models.DateTimeField() class Country(models.Model): countryid = models.BigIntegerField() countryname = models.CharField(max_length=64) iscurrent = models.CharField(max_length=1) class Consignee(models.Model): Consigneekey = models.BigIntegerField(primary_key=True) name = models.CharField(max_length=500) countryid = models.BigIntegerField() class Profile(models.Model): dimparcelprofilekey = models.BigIntegerField(primary_key=True) number = models.CharField(max_length=50) trackingcode = models.CharField(max_length=64) -
unable to access image from request in django
I am trying to send images in FormData() from react to django. But not images is recieving in the django server. Other text fields are showing in QueryDict but images are not there. react code - let formdata = new FormData(); formdata.append('title', ref_title.current.value); formdata.append('price',ref_price.current.value); formdata.append('description',ref_desc.current.value); formdata.append('images',ref_image.current.files[0],ref_image.current.files[0].name); console.log(formdata.get('images')); axios.post(url, formdata).then(res => { (res.status == 200)?alert('success'):alert('error'); }) django code - print(request.POST.get('title')) print(request.POST.get('price')) print(request.POST.get('images')) # it is returning None print(request.POST) I am getting the following output in django hello 41 None <QueryDict: {'title': ['hello'], 'price': ['41'], 'description': ['hello world']}> There is no images key in QueryDict. How can I access the image? -
Django : How write a decorator that takes an input after a redirect function
I want to write a decorator that takes an input coming from a redirect function (the value : id_contrat). If I explain a little bit more. An user selects a value in a form, then this value is redirect to another view "home". I want to check that the user has the rights on this value ! So I need to get it in my decorator. How do I add this value to my decorator. I tried something but it is not working : TypeError: wrapper_func() got an unexpected keyword argument 'id_contrat' My views : @authenticated_user def selectcontrat(request) : context = initialize_context(request) form_client = SelectClient(request.POST, user=request.user) if form_client.is_valid(): id_contrat = request.POST.get("ID_Customer") return redirect(reverse('home', args=(id_contrat,))) context['form_client'] = form_client return render(request, 'base/selectcontrat.html', context) @authenticated_user @check_user_rights def home(request, id_contrat=None): context = initialize_context(request) return render(request, 'home.html', context) the url definition : from django.urls import path from . import views urlpatterns = [ path('home/<int:id_contrat>/', views.home, name="home"), path('', views.loginAD, name="login"), path('signin', views.sign_in, name='signin'), path('callback', views.callback, name='callback'), path('selectcontrat', views.selectcontrat, name='selectcontrat') the form : class SelectClient(forms.Form): ID_Customer = forms.ChoiceField(label="Company :") def __init__(self, *args, **kwargs) : self.user = kwargs.pop('user') super(SelectClient, self).__init__(*args, **kwargs) id_client_list = AADJNTGroup.objects.filter(ID_User_id=self.user.id).values_list('ID_Group_id', flat=True) id_client_list = list(id_client_list) client_choices = Groups.objects.all().filter(ID__in=id_client_list).values_list('IDCustomer','GroupName') self.fields['ID_Customer'].choices = client_choices the decorator def check_user_rights(id_contrat) … -
how do I get all the objects associated with a foreignkey field
How do I get all the objects associated with the foreignkey field in "ProductImage". So I've multiple images for one "Product" model in "ProductImage", how do I get all of the associated ones. Currently, I'm getting an error "MultipleObjectsReturned at /shop/product-slug" idk what I'm doing wrong, would appreciate it a lot if someone can help! thx! models.py class Product(models.Model): name = models.CharField(max_length=150) description = models.TextField() image = models.ImageField(null=True, blank=True) class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) name = models.CharField(max_length=50) image = models.ImageField(null=True, blank=True, upload_to='productimg/') urls.py path("<slug:slug>", views.detail_view, name="detail_view"), views.py def detail_view(request, slug): products = Product.objects.get(slug=slug) productimg = ProductImage.objects.get(product=products) -
(Django Allauth) 'CustomUser' object has no attribute 'username'
I'm trying to implement a CustomUser model in Django Allauth. When I used the allauth provided login template, I encountered this error My Customer User Model in users/models.py from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class CustomUserManager(BaseUserManager): def create_superuser(self, email, password=None): if password is None: raise TypeError('Password should not be none') user = self.create_user(email, password) user.is_superuser = True user.is_staff = True if user.is_superuser is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if user.is_staff is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') user.save() return user def create_user(self, email, password=None): if email is None: raise TypeError('Users should have a Email') email = self.normalize_email(email) user = self.model(email=email) user.set_password(password) user.save() return user AUTH_PROVIDERS = {'facebook': 'facebook', 'google': 'google', 'twitter': 'twitter', 'email': 'email'} class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True, db_index=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) about = models.TextField(_( 'about'), max_length=500, blank=True) auth_provider = models.CharField( max_length=255, blank=False, null=False, default=AUTH_PROVIDERS.get('email')) USERNAME_FIELD = 'email' objects = CustomUserManager() def __str__(self): return self.email settings.py """ custom user """ AUTH_USER_MODEL = 'users.CustomUser' """ allauth """ AUTHENTICATION_BACKENDS = [ # Needed to login by username … -
Creating a shopping List in Django Admin
I am trying to show the shopping Cart for only a specific user in the Django Admin template . I managed to do it in a normal views like this : order = Order.objects.get(user=self.request.user, ordered=False) but when trying to do the same inside the model items = models.ManyToManyField(OrderItem.objects.get(user=settings.AUTH_USER_MODEL)) I get this error django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. What I'm trying to achieve is to only show the items that the user entered to his shopping cart instead of all the order items in the system so is there a way to filter what is shown in the admin panel based on the user