Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I get path of 3rd party app in Django
I install django_celery_beat app in Django settings.py file INSTALLED_APPS = [ ..., 'django_celery_beat', ] It has its own locale dir. As I understand I need to add this path to LOCALE_PATHS in settings.py. How can I get it? Hardcoding is not an option, of cause. -
How can i multiselect in django admin dropdown on foreignkey data just like manytomanyfield?
models.py from django.db import models class Images(models.Model): def upload_path(instance, filename): return '/images/'.join([filename]) image = models.ImageField(upload_to=upload_path, blank=True, null=True) logits = models.BinaryField() #customer = models.ForeignKey(Customer ,on_delete=models.DO_NOTHING, default=None) class Customer(models.Model): customer_id = models.BigIntegerField(unique=True) first_name = models.CharField(max_length=300) last_name = models.CharField(max_length=300) images = models.ForeignKey(Images ,on_delete=models.DO_NOTHING, default=None) def __str__(self): return str(self.customer_id) My problem is i want to be able to assign multiple images to single user which should be possible because of ForeignKey but i don't seem to get it to work like that. I want multiselect field just like in manytomanyfield but in foreignkey field. -
Set the SECRET_KEY environment variable What should I do?
The configuration of my pole diagram is as follows. maninapp ㄴ mainapp ㄴsettings ㄴ init.py ㄴ base.py ㄴ deploy.py ㄴ local.py .env manage.py if you run python manage.py runserver, django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable It looks like this base.py .. . . BASE_DIR = Path(file).resolve().parent.parent to BASE_DIR = Path(file).resolve().parent.parent.parant manage.py . . . os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mainapp.settings.local') to os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mainapp.settings') There is also a SECRET_KEY key in .env. What should I do? -
href not accepting loop Django
<table id="tabledata" class="tablecenter" style=" position: static; top:50%;"> <tr> <th>Username</th> <th>Email</th> <th>Role</th> <th>Action</th> <th>Remove User</th> </tr> {% for user in all %} <tr> <td>{{user.first_name}} {{user.last_name}}</td> <td>{{user.email}}</td> <td>{% if user.is_staff %} Admin {% else %} Practitioner {% endif %}</td> <td><a class="openButton" onclick="openForm()">Edit</a></td> <td><a href="{% url 'delete_user' pk=user.id %}" class="openButton">Delete</a></td> </tr> {% endfor %} After running the server on local, the page gives syntax error. enter image description here -
URL linking in django is getting failed
Error in line 13, the system shows. It is in Home page of blog project. <h1>Posts</h1> <ul> {% for post in object_list %} <li> <a href=" {% url 'article-detail' post.pk %} "> {{ post.title }} </a> {{ post.author.last_name }} {{ post.author.first_name }} <br /><br /> </li> {{ post.body }} <br /><br /> {% endfor %} </ul> In views.py class AddPostView(CreateView): model = Post template_name = 'add_post.html' fields = '__all__' and in urls.py urlpatterns = [ path('', HomeView.as_view(), name='home' ), path('article/<int:pk>/{% post.title %}', ArticleDetailView.as_view(), name='article-detail'), path('add_post/', AddPostView.as_view(), name='add_post')] Can any one help me please? -
How we can access and save object value of foregn model as default value, if the field is empty while saving the related object model?
class ObjectSEO(models.Model): object= models.ForeignKey(Objects, related_name='seo', on_delete=models.CASCADE) meta_description = models.CharField(max_length=170, help_text="Please add product meta description, max length 170 characters", default="Some Texts" ) meta_keywords = models.CharField(max_length=250, help_text="Please add product keywords separated with comma", default="Some Texts" ) meta_name = models.CharField(max_length=70, help_text="object title" default = Objects.name) Here, I have two models, Objects and ObjectSEO. In ObjectSEO model > site_name column> I want to add foreign key Objects name as default value. How can I do this? Is my approach pythonic? -
Filtering out a foreignkey model out of a foreignkey model
Tryna filter all productimg objects of MainProduct but getting ValueError Cannot use QuerySet for "MainProduct": Use a QuerySet for "Product". but can't use slug or id to filter it out of Product cuz it's homepage home:view [doesnt work] #can't use slug here def home(request): mainproduct = MainProduct.objects.all() productimg = ProductImage.objects.filter( #wanna access all productimg objects of a single product i.e mainproduct product=mainproduct ) shop:view [works] def detail_view(request, slug): products = Product.objects.get(slug=slug) productimg = ProductImage.objects.filter(product=products) shop:model class Product(models.Model): name = models.CharField(max_length=150) class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True, upload_to='somewhere/') home:model class MainProduct(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) title = models.CharField(max_length=50) -
Django, froms in admin are weird, passwords not getting hashed, like what should I do?
I am honestly losing my mind. I just wanted to make a custom user model with an extra field called "CV", and removing the first and lastname and let it be just "name", but... I want to give up programming at tihs point. I had no problem with these small things in the past, liek why is it not working now? I'm literally about giving up my entire programming "career" if you can call it that way... I linked the entire code... ```https://pastebin.com/PeJ4U8wu``` -
Django - profile creation based on is_staff
I am currently working on a job portal project, where I need to create 2 profiles based on is_staff field of default user model of django. one for job seekers and another one for employers (i.e user profile and company profile) I am a beginner to django. I have no idea how to do it, please help me. -
Not Implemented Error in Django Channels Layers
I was following the Django channels tutorial to create a simple chat application. But while trying to check if the channel layer can connect to Redis, I get this Not Implemented Error. >>> async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'}) Traceback (most recent call last): File "<console>", line 1, in <module> File "D:\Web Development\DJANGO\Channels\venv\lib\site-packages\asgiref\sync.py", line 204, in __call__ return call_result.result() File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python310\lib\concurrent\futures\_base.py", line 439, in result return self.__get_result() File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python310\lib\concurrent\futures\_base.py", line 391, in __get_result raise self._exception File "D:\Web Development\DJANGO\Channels\venv\lib\site-packages\asgiref\sync.py", line 270, in main_wrap result = await self.awaitable(*args, **kwargs) File "D:\Web Development\DJANGO\Channels\venv\lib\site-packages\channels_redis\core.py", line 343, in send async with self.connection(index) as connection: File "D:\Web Development\DJANGO\Channels\venv\lib\site-packages\channels_redis\core.py", line 902, in __aenter__ self.conn = await self.pool.pop() File "D:\Web Development\DJANGO\Channels\venv\lib\site-packages\channels_redis\core.py", line 93, in pop conn = await self.create_conn(loop) File "D:\Web Development\DJANGO\Channels\venv\lib\site-packages\channels_redis\core.py", line 79, in create_conn return await aioredis.create_redis_pool(**kwargs) File "D:\Web Development\DJANGO\Channels\venv\lib\site-packages\aioredis\commands\__init__.py", line 188, in create_redis_pool pool = await create_pool(address, db=db, File "D:\Web Development\DJANGO\Channels\venv\lib\site-packages\aioredis\pool.py", line 58, in create_pool await pool._fill_free(override_min=False) File "D:\Web Development\DJANGO\Channels\venv\lib\site-packages\aioredis\pool.py", line 383, in _fill_free conn = await self._create_new_connection(self._address) File "D:\Web Development\DJANGO\Channels\venv\lib\site-packages\aioredis\connection.py", line 121, in create_connection reader, writer = await asyncio.wait_for(open_unix_connection( File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python310\lib\asyncio\tasks.py", line 408, in wait_for return await fut File "D:\Web Development\DJANGO\Channels\venv\lib\site-packages\aioredis\stream.py", line 39, in open_unix_connection transport, _ = await get_event_loop().create_unix_connection( File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python310\lib\asyncio\events.py", line 387, in create_unix_connection raise … -
Extra operation button in django admin panel
I want to add some buttons to do a lot of database operations at once, and I want to place those button(s) at (1) place. How to do that? Extra explains: What I want to do is to clear all "Logs" and set access count (an integer) to 0 in every object inside "Shortcuts. I'm too lazy to do so manually. -
'str' object is not callable error in Django
urls.py urlpatterns = [ path('',include('CyberHealth.urls')) + (static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)) ] This is the error I received path('',include('CyberHealth.urls')) TypeError: 'str' object is not callable Kindly please help me to solve this error.. -
Debug Toolbar not showing
I installed: pip install django-debug-toolbar I have DEBUG=True in my settings I have django.contrib.staticfiles and debug_toolbar in INSTALLED_APPS i have STATIC_URL = '/static/' in STATIC_URL I have 'debug_toolbar.middleware.DebugToolbarMiddleware' high up in MIDDLEWARE_CLASSES I have INTERNAL_IPS = ['127.0.0.1'] in my settings I have urlpatterns = [ ... path('debug/', include(debug_toolbar.urls)) ] and Import debug_toolbar in URLConfig of project. I have run python manage.py collectstatic and Debug Toolbar not showing in my browser How can I fix it? -
Flask Unique SQLAlchemy with Flask-LImiter
I want to make a project with flask where you sign up and sign in and then you can make new posts. I use flask-limiter to prevent users from making new posts. Also, I want the title of the post to be unique because there is an edit page too. Here is the code of flask: def ifonly(): if current_user.name == 'admin': return False else: try: if request.method == 'POST': title1 = request.form['title'] content2 = request.form['content'] post70 = Post.query.filter_by(title=title1).first() if post70: return redirect('/home') else: if len(title1) > 5 and len(title1) < 50 and len(content2) > 5: global post1 post1 = Post(title=title1,content=content2,name=current_user.name,author=current_user.id) db.session.add(post1) db.session.commit() return True except: flash("nooo") else: return False @app.route('/makepost/',methods=['POST','GET']) @limiter.limit('10 per 10 minutes',cost=ifonly) def makepost(): allposts = Post.query.all() sear = 1 if not current_user.is_authenticated: return redirect('/login') poster = Users.query.filter_by(name=current_user.name).first() try: if request.method == 'POST': title = request.form['title'] content = request.form['content'] if len(title) < 5: flash("Title must be at least 5") if len(title) > 50: flash("Title must be 50 characters max") if len(content) < 5: flash('Content must be at least 5 letters') if len(title) > 5 and len(title) < 50 and len(content) > 5: sear = 2 post69 = Post.query.filter_by(title=title).first() if sear == 2: global post1 post1 = Post(title=title,content=content,name=current_user.name,author=current_user.id) … -
Django com DetailView E ModelForm
Estou tentando utilizar o FormView com DetailView mas não estou obtendo o comportamento esperado. O que estou procurando é que ao clicar no nome do cliente na minha ListView, quero que o campo cliente da servico/models.py já seja associado a este nome e gere um formulário com os outros campos. restantes. servico/views.py class AssociarServicoDetail(FormView, DetailView): model = Clientes template_name = 'servico/associar_detail.html' form_class = ServicoForms success_url = reverse_lazy('pages:home') cliente/models.py class Clientes(models.Model): nome_cliente = models.CharField(max_length=70, verbose_name='Nome Completo') telefone = models.CharField(max_length=15, verbose_name='Telefone') email = models.EmailField(unique=True, blank=True, verbose_name='E-mail') data_criacao = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.nome_cliente def get_absolute_url(self): return reverse('servico:associar_detail', kwargs={'pk': self.pk}) servico/models.py class servico(models.Model): choices_services = [('1', 'Tatuagem'), ('2', 'Piercing')] cliente = models.ForeignKey(Clientes, on_delete=models.CASCADE) lista_servico = models.CharField(max_length=1, choices=choices_services, blank=False, null=False) tatuador = models.ForeignKey(User, on_delete=models.CASCADE) marcar_servico = models.BooleanField(default=True) servico/forms.py class ServicoForms(forms.ModelForm): class Meta: model = servico fields = '__all__' -
Graph not being displayed on django framework
I want to display a graph using C3 Javascript library which displays future prices of textile raw materials on django framework. When I run the code it does not display the graph and when I inspected it gave the following error : Failed to load resource:allpredicted.js:1 the server responded with a status of 500 (Internal Server Error). Can anyone tell what could be the problem? I tried changing location of static and template folders but nothing worked. This is the javascript file which creates graph allpredicted.js /* * Parse the data and create a graph with the data. */ function parseData(createGraph) { Papa.parse("201222-yarn-market-price-china--034.csv1.csv", { download: true, complete: function(results) { createGraph(results.data); } }); } function createGraph(data) { var years = ['x']; var pred_appended = ["Cotton Yarn1"]; for (var i = 1; i < data.length; i++) { if (data[i][0] === undefined) { years.push (null); } else { years.push (data[i][0]); } if (data[i][2] === undefined) { pred_appended.push (null); } else { pred_appended.push (data[i][2]); } } console.log(years); console.log(pred_appended); var chart = c3.generate({ data: { x: 'x', //xFormat: '%d/%m/%Y', // 'xFormat' can be used as custom format of 'x' columns: [ years, // ['x', '20130101', '20130102', '20130103', '20130104', '20130105', '20130106'], pred_appended ] }, axis: { … -
Upload file from html when block public access is true
I am using django-s3direct to file upload https://github.com/bradleyg/django-s3direct Using IAM role setting because I upload the file from the server on ECS container. Now I set the blockPublicAccess of S3 false. When uploading images from html, there comes error. https://s3.ap-northeast-1.amazonaws.com/static-resource-v/images/c64d6e593de44aa5b10dcf1766582547/_origin.jpg?uploads (403 (Forbidden) ) initiate error: static-resource-v/line-assets/images/c64d6e593de44aa5b10dcf1766582547/_origin.jpg AWS Code: AccessDenied, Message:Access Deniedstatus:403 OK, it is understandable. Browser try to access the for initiation. However there is any way to upload file from browser when blockPublicAccess is true?? -
Test a decorated fucntion in Python
I have a python function which is decorated. @retry_if_access_token_expired(app_id) def add_something( self, *, argument1, argument1 = None, ): """adding something""" I've written tests for the given as below. @patch("other inside function to mock") @patch("other insdie function to mock 2") def test_add_something( self, mock_1, mock_2 ): """ some logic to test the add something method """ But I am getting this error that says add_somehthing takes 1 positional argument. TypeError: add_something() takes 1 positional argument but 3 were given Any help would be appreciated. -
how to pass null value to just one specific key of the one object using same DRF serializer
I'm just passing the same object 2 times in the same serializer but I want to pass key: "retweet": null in one object and in another object I want to pass some values like some many-to-many field values because key "retweet" is many-to-many field and having data Thanks in advance! -
wkhtmltopdf-django dynamic template to render
Is there any way to generate a PDF dynamically, with content being fetched from the database? My goal is to allow my users to generate their own PDF design from a wysiwyg editor. This is my model class DocumentService(models.Model): name = models.CharField(max_length=60, blank=True) html_content = models.TextField(blank=True) I use django-wkhtmltopdf to render html to PDF. response = PDFTemplateResponse( request=request, template="document.html", filename=filename, context=data, show_content_in_browser=True, cmd_options=cmd_options, ) How can I render the content of this record into my PDF? document = DocumentService.objects.get(pk=1) document.html_content # <-- this content The HTML content should be something like this <html> <body> <p> <strong>Date: </strong> {{date}} <strong>User: </strong> {{user.name}} <strong>Email: </strong> {{user.email}} <strong>Info: </strong> {{user.info}} ... </p> </body> </html> -
Can't set default image django
I was create a profile for user. I done set up all the Media and Static. But when I set default and upload_to in image field, it error not found image. I had try all the different Path image but it doesn't work either. Can someone check the path for me. Thank a lot ! path in setting: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media/images') MEDIA_URL = '/media/' url project: urlpatterns = [ path('admin/', admin.site.urls), path('',views.IndexPage.as_view(),name='index'), path('welcome/',views.WelcomePage.as_view(),name='welcome'), path('bye/',views.ByePage.as_view(),name='bye'), path('about/',views.AboutPage.as_view(),name='about'), path('profile/', include('accounts.urls')) ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) model: class UserInfoCnc(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to = 'profile_pics', default='profile_pics/xinlacho.JPG' ,blank=True show image in html: <img class='img-thumbnail' src="{{ userinfocnc.profile_pic.url }}" alt="Error load image"> file media and static in project: -
Move HTML variable through views to python script in Django
While working in Django I am trying to take a variable from HTML input, pass it to views.py for some decision making, then pass it from views.py to a separate python script in my project. Here is my upload form in my HTML file, this step works fine: <form method="POST" enctype="multipart/form-data" action="{% url 'upload' %}"> {% csrf_token %} <input type='file' name='document' accept='.csv' required><br> <label for='axis'>Which column is the x-axis?<label> <input type='number' name='axis' id='axis' required><br> <button type='submit' name='csvreader'>Bar Graph</button> <button type='submit' name='line_plot'>Line Graph</button> <button type='submit' name='scatter_plot'>Scatter Plot</button> </form> Then in my views.py, I use it to check if the value is valid before calling the python script, also works fine: def upload(request): if request.method == 'POST': form = UploadFileForm(request.POST.get, request.FILES) file=request.FILES['document'] df = pd.read_csv(file,header=None) data = pd.DataFrame(df) length = len(data.columns) item = Item() item.text = request.POST.get('axis', '') item.save() request.session['item.text'] = item.text if ((int(item.text) < 0)) | ((int(item.text) >= length)): HttpResponse("Your axis is not valid") if 'csvreader' in request.POST: csv = CSV.objects.create(doc=file) os.system('python csvreader2.py') if 'line_plot' in request.POST: csv = CSV.objects.create(doc=file) os.system('python line_plot.py') if 'scatter_plot' in request.POST: csv = CSV.objects.create(doc=file) os.system('python scatter_plot.py') return render(request, 'uploaded.html') And finally, I want to use it to define which line of the csv file will be … -
The transaction has been cancelled, but our business server can still receive the webhook with successful payment
This is one of the customers who failed to pay and cancelled the Recurring payment However, my business server receives a Payment sale completed Webhook notification set up on paypal, I'm very confused -
Redirect inside async function
I have a function for creating a Stripe.com checkout session: @csrf_exempt def create_checkout_session(request): if request.method == 'GET': domain_url = 'https://example.com/' stripe.api_key = settings.STRIPE_SECRET_KEY try: order = request.user.profile.order_set.get(ordered=False) all_in_stock = True for orderitem in order.orderitem_set.all(): if orderitem.item.in_stock >= orderitem.quantity: pass else: all_in_stock = False break if all_in_stock: line_items = [] for orderitem in order.orderitem_set.all(): line_item = { 'name': orderitem.item.item_name, 'quantity': orderitem.quantity, 'currency': 'usd', 'amount': int(orderitem.item.price * 100), } line_items.append(line_item) orderitem.item.in_stock -= orderitem.quantity orderitem.item.save(update_fields=['in_stock']) if order.shipping_address.state == 'IL': line_item = { 'name': 'Sales tax', 'quantity': 1, 'currency': 'usd', 'amount': int(order.get_sales_tax() * 100), } line_items.append(line_item) checkout_session = stripe.checkout.Session.create( client_reference_id=request.user.profile.id, success_url=domain_url + 'store/success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'store/cancelled/', payment_method_types=['card'], mode='payment', line_items=line_items, customer_email=request.user.email, expires_at=int(time.time() + 3600), ) return JsonResponse({'sessionId': checkout_session['id']}) else: messages.error(request, "Not enough items in stock to fulfill the order") return redirect("store:order-summary") except Exception as e: return JsonResponse({'error': str(e)}) It is executed with this script: fetch("/store/config/") .then((result) => { return result.json(); }) .then((data) => { const stripe = Stripe(data.publicKey); document.querySelector("#stripeSubmitBtn").addEventListener("click", () => { fetch("/store/create-checkout-session/") .then((result) => { return result.json(); }) .then((data) => { console.log(data); return stripe.redirectToCheckout({sessionId: data.sessionId}) }) .then((res) => { console.log(res); }); }); }); I want to add the functionality to check that all items are still in stock, and if not abort the session. … -
django if user.is_authenticated not working but login user
my problem is that the login operation is done correctly and the session is set up correctly, but user.is_authenticated does not work. The point is that it works when I log in through the admin, but not like this, what can I do to fix it? my code : views.py class LoginView(View): def get(self, request): login_form = LoginForm() context = { 'login_form': login_form } return render(request, 'account/login.html', context) def post(self, request: HttpRequest): login_form = LoginForm(request.POST) if login_form.is_valid(): user_email = login_form.cleaned_data.get('email') user_password = login_form.cleaned_data.get('password') user: User = User.objects.filter(email__iexact=user_email).first() if user is not None: check_password = user.check_password(user_password) if check_password: login(request, user) return redirect('home') else: login_form.add_error('password', 'password is not correct !') else: login_form.add_error('email', 'email dose not exists !') context = { 'login_form': login_form } return render(request, 'account/login.html', context) header_component.html <div class="navbar__list"> <ul class="navbar__links"> {% for link in links %} <li class="navbar__link"><a href="{{ link.url }}">{{ link.name|capfirst }}</a></li> {% endfor %} {% if user.is_authenticated %} <li class="navbar__link"><a href="#">welcome</a></li> <li class="navbar__link"><a href="{% url 'logout' %}">Log out</a></li> {% else %} <li class="navbar__link"><a href="{% url 'login' %}">Login</a></li> <li class="navbar__link"><a href="{% url 'register' %}">Register</a></li> {% endif %} </ul> </div>