Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add a new field to oscar dashboard
After following various examples here on stackoverflow my new field isn't showing up on django oscar dashboard here are my models and dashboard fork. catalogue models.py from django.db import models from oscar.apps.catalogue.abstract_models import AbstractProduct class Product(AbstractProduct): file = models.FileField(upload_to='files/%Y/%m/%d') from oscar.apps.catalogue.models import * dashboard/catalogue/forms.py from oscar.apps.dashboard.catalogue import forms as base_forms class ProductForm(base_forms.ProductForm): class Meta(base_forms.ProductForm.Meta): fields = ('file',) I am wondering what i did wrong for people that have faced this issue before I need help. thanks. -
Redirecting from Django App to Asp.Net webpage
I have a Django app that is a form that is supposed to be in multiple languages. Temporarily, I would like to release my app with the English form and use the other language buttons to redirect to an old ASP.Net version of the form while I work on making my form multi-lingual. I did manage to have my form redirect to the right place when I click on my "Spanish" button, but there are missing necessary Session parameters that the ASP.NET form needs to function properly. From my Django app: HTML Template <a href="{% url 'to_spanish' %}"><button type="button" class="btn-outline-secondary">Español</button></a> views.py (redirecting FROM this page) def to_spanish(request): request.session["Language"] = 'Spanish' # request.session["RandomID"] = '' # request.session["email"] = '' # request.session["nameidentifier"] = '' return HttpResponseRedirect('https://lspintake.nbn.org.il/IntakeForm') urls.py urlpatterns = [ path('', views.index, name='Auth0 homepage'), path('IntakeForm/1', views.personal_details_section), path('IntakeForm/2', views.parents_section), path('IntakeForm/3', views.citizenship_section), path('IntakeForm/4', views.idf_section), path('https://www.google.com', views.to_spanish, name='to_spanish'), ] (I used 'google.com' here as a placeholder. It still redirects to the url I put in the view and I'm not really sure what to put in the urls file in that spot.) From the ASP.NET app (what I'm trying to redirect TO): Lines of code are used like this in C# in this app: int … -
jQuery Core test/data/jsonp.php callback Parameter XSS
jQuery Core contains a flaw that allows a cross-site scripting (XSS) attack. This flaw exists because the test/data/jsonp.php script does not validate input to the 'callback' parameter before returning it to users. This may allow a context-dependent attacker to create a specially crafted request that will execute arbitrary script code in a user's browser session within the trust relationship between their browser and the server.| Which version of jquery or django-jquery have this fix? -
In City Field Input Type problem in django
This Is the Code. <div class="col-lg-4 col-sm-12"> <div class="control-group"> <label for="City" class="control-label">City*</label> <div class="controls"> <input type="text" value="{{ org.city }}" id="city" name="city" placeholder="Enter your city" required="" aria-required="true"> </div> <!-- /controls --> </div> <!-- /control-group --> </div> -
django: uploaded images won't be displayed
my uploaded images can't be displayed even though i'm not getting any errors: instead it looks like this and here are my settings and codes: settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static_cdn") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),"media") models: class Post (models.Model): title = models.CharField(max_length=200) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) cover = models.ImageField(null=True, blank=True, upload_to='media/') urls: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views: def posts_create (request): form = PostForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, "Successfully created") return HttpResponseRedirect(instance.get_absolute_url()) context = {'form': form} return render(request, 'post_form.html', context) template: {% extends "base.html" %} {% block title %} {{object.title}} | {{block.super}}{% endblock title%} {% block content %} <div class="center" style=" display: table; margin-right: auto; margin-left: auto;"> {% if object.cover %} <img src="{{object.cover.url}}" class="img-responsive"/> {% endif %} <h1>{{title}} <small style="font-size: small"> {{object.timestamp}}</small> </h1> {{object.content | linebreaks}}<br> <div/> {% endblock content%} -
How to make a Django FormSet accept m2m but store them as multiple FK records?
I need to provide a test for students, but some questions accept multiple answer. Can I make it create multiple records for storing multiple answers instead of using a M2M? e.g. if a student select A and B for a question, would act like the following: StudentAnwer.objects.create(question=question, answer=answer_a) StudentAnwer.objects.create(question=question, answer=answer_b) formsets.py from django import forms StudentAnswerFormSet = forms.inlineformset_factory( Student, StudentAnswer, fields=['question', 'answer', ], formset=forms.BaseInlineFormSet) models.py class Question(BaseModel): title = models.CharField(max_length=250) is_multiple = models.BooleanField(default=False) class StudentAnswer(BaseModel): student = models.ForeignKey(Student, related_name='answers') question = models.ForeignKey(Question, related_name='student_answers') answer = models.ForeignKey(Answer, related_name='student_answers') views.py from formtools.wizard.views import SessionWizardView class StudentWizardView(SessionWizardView): ... def get_answer_form(self, step=None, data=None, files=None): ... question_list = get_question_list() return forms.inlineformset_factory( Student, StudentAnswer, fields=['question', 'answer', ], extra=len(question_list), formset= forms.BaseInlineFormSet) def get_form(self, step=None, data=None, files=None): form = super(StudentWizardView, self).get_form(step, data, files) # determine the step if not given if step is None: step = self.steps.current if step == self.STEP_ANSWER: initial_dict = self.get_form_initial(step) prev_form_data = self.get_cleaned_data_for_step(self.STEP_PROFILE) form = self.get_answer_form(step, data, files) for form_index in range(len(initial_dict.keys())): question = initial_dict[form_index]['question'] answer_list = question.get_answer_list() if question.is_multiple: form.forms[form_index].fields['answer'] = ModelMultipleChoiceField(queryset=answer_list, widget=CheckboxSelectMultiple) else: form.forms[form_index].fields['answer'].widget.choices.queryset = answer_list I'm trying to avoid M2M for making it easier to display the possible answers per question on the template. {{ wizard.management_form }} {{ wizard.form.management_form }} {% … -
Getting Failed to construct 'Worker' with JS worker file located on other domain when using react-pdf
I am using react-pdf to render a PDF file inline on my Django/Wagtail website. To do this, I create a div in my HTML template with ID react, and I run a file called index.js which is a pretty straightforward React file that creates a DocumentViewer element and uses ReactDom to render it to the div with id 'react'. I get an error when running my website on production when loading the worker file from my main bundle, specifically an error about how script worker.js cannot be accessed from origin 'example.com' The exact code is not really relevant (although I can post it if necessary, but the thing that's giving me issues is loading the react-pdf worker. I use the following import statement as the docs recommend: import {Document, Outline, Page} from 'react-pdf/dist/entry.webpack'; I then use webpack to bundle and minify this file, with the following webpack.config.js: var path = require("path"); var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); module.exports = { context: __dirname, entry: './project/app_name/static/js/index.js', output: { path: path.resolve('./project/app_name/static/bundles/'), publicPath: '/static/bundles/', filename: "[name]-[hash].js", }, plugins: [ new BundleTracker({filename: './webpack-stats.json'}), ], module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: ['babel-loader'] } ] }, resolve: { extensions: ['*', '.js', … -
Django Permission Required
I'm trying to check permissions for some api requests. I've already set auth users and auth_user_user_permissions and auth_permissions tables like view_company add_company bla bla, but problem is not that. The problem is when i'm trying yo use decarator which @permission_required('api.view_company', raise_exception=True) it said to me AttributeError: 'CompanyDetailView' object has no attribute 'user' Most probably it's looking for user because its gonna check user_permission is it available to view companies or not but my view which i declared in urls (path('companies//', CompanyDetailView.as_view()),) has not have user object thats why error message returned attribute error, how can i solve this, thanks a lot I tried to set example user in view class in the beginning it worked because view was looking for user object, i can not use that way because every request has different user import rest_framework from rest_framework import status from django.contrib.auth.models import User from rest_framework.views import APIView from rest_framework.response import Response from django.contrib.auth.decorators import permission_required class CompanyDetailView(APIView): @permission_required('api.view_company', raise_exception=True) def get(self, request, id): try: request_data = {} request_data['request_method'] = request.method request_data['id'] = id companies = Company.objects.get(id=id) status = rest_framework.status.HTTP_200_OK return Response(companies, status)``` bla bla bla my error message was : AttributeError: 'CompanyDetailView' object has no attribute 'user' -
Generate Django Password
In my Postgres DB, there is a password column, which has passwords stored in the format argon2$argon2i$v=19$m=512,t=2,p=2$Z1BlYkltRjNhakFE$1cgxZNRetdjoCYwBrjAICA Is there a way to generate this password manually? I am not a backend developer and hence not much idea about how these things are usually handled. -
background-image not showing up in Django
I have an accounts app, and I have an icon in accounts/static/accounts/images/mail-icon.png that I want to use as a background-image in my CSS, and in my template I have: <a id="mail-icon" href="{% url 'register' %}">Registration via Email address</a> In my register.css (which is located in accounts/static/accounts/css/register.css I have: #mail-icon { background-image: url(../images/mail-icon.png); } When I check Network tab of my developer tools, I see that I'm getting a 200 or 304, however the image is not appearing for some reason. I have tried to restart the server but had no success. The image is appearing if I use: <img src="{% static 'accounts/images/mail-icon.png' %}"> What could be the issue? -
Vanilla Python for web development?
I'm about to start a project, I want to do this in Python, I'll been working with PHP an Js for a while so I want to change and learn new language/framework. I know a little of Python and I started to learn Django, but I want to know if there is a way to build a simple program in vainilla Python to fully understand the concepts and how Python work for web development. Like when you work in PHP that you usually develop a program in MVC and after that you use a framework. -
Entire Application in Django shuts down with single error
I am new to Python and django , I was a php developer earlier. My problem here is Entire Application in Django shuts down with single error. for example i start my website with "python3 manage.py runserver 0.0.0.0:8000" example:-- i have two pages home and register 1) if i make error in register page code(register.py) , It shuts down home page too. Is there a way to prevent that as in php one page do not effect other. 2) how to work in django with team one errors full team hangs. 3) How to work with live working websites things may become too risky. also i am not able to find article related to this. kindly help -
How to make a robots.txt on Django
I've seen other answers here, but they aren't really helpful, which is why I am asking. I tried the django-robots framework as well, but it gives me an error when i just put 'robots' in my INSTALLED_APPS INSTALLED_APPS = [ 'index.apps.IndexConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', ] -
cant query from django where field name has double underscore
Cant query from django where field name has double underscore. This is because in the django query language __ has its own meaning so how can i query a field whose actual name is "my__fyeild__name" ? template.fields.filter(my__fyeild__name="aaa") -
What is purpose of routes.js in Django?
I am developing web application using django latest version & I have reference of old website of our company. There are routes.js which is responsible for routing urls. .when('/test/web_test',{ templateUrl: '/test/web_test/', controller: 'testCtrl', resolve: loader(['test/js/test.js?v=1.2']) above kind of url routing kind of new to me. how does above kind of url patterns works & when django calls such routes.js file. -
Django templates - add a block to an imported file though an extended one
Yes, the title is confusing, so here I'm gonna try to put an example base.html: (I omit the non related code) <body class=""> <div class="wrapper"> {% include "includes/sidebarDashboard.html" %} <div class="main-panel"> {% include "includes/headerDashboard.html" %} </div> {% block content %} {% endblock %} </div> </body> headerDashboard.html <div class="container-fluid"> <div class="navbar-wrapper"> <div class="navbar-toggle"> <button type="button" class="navbar-toggler"> <span class="navbar-toggler-bar bar1"></span> <span class="navbar-toggler-bar bar2"></span> <span class="navbar-toggler-bar bar3"></span> </button> </div> {% block breadcrumb %} {% endblock %} </div> </div> So having this, now I want to extend the base and, in that file, try to add the breadcrumb block also. Something like: important-information.html {% extends 'includes/base.html' %} (some loads and styles and scripts..) {% block breadcrumb %} <a class="navbar-brand" href="#">Data Management</a> {% endblock %} {% block content %} (the content) {% endblock %} The result of this is just get the block content filled, but I need to get filled the block breadcrumb too from the same file. Because if not, for every change in any of the 10+ files that extends the body, I have to make changes on the header too and I want to manage everything from the same file. Also I think is always good to ask if what I'm … -
How to update requirements?
I would like to know how to update outdated requirements with the multi requirements files setup that cookie cutter uses (base, local, etc...) ? If i launch a "pip freeze" it will write the requirements in a single file. It will not dispatch them in correct files Do I miss something ? -
Image not uploading to the folder
I want to upload an Image, but it is not showing in the media folder. This is the HTML template <form class="form" action="/profile/edit/{{user.id}}" method="post" enctype="multipart/form-data" style="padding-top:20px;"> {% csrf_token %} <input type="file" class="btn " name="pro_pic" accept=".png, .jpg, .jpeg"> <button type="submit" class="btn text-success" name="pr_pic" id="pic_submit"><i class="fas fa-check"></i> Submit</button> </form> Models.py class UserDetails(models.Model): user_id = models.IntegerField(unique=True) bio = models.TextField(null = True) profession = models.CharField(max_length = 100, null = True) city = models.CharField(max_length = 100, null = True) country = models.CharField(max_length = 100, null = True) img = models.ImageField(upload_to='pic_user', null = True) views.py def edit (request, id = '') : if request.user.is_authenticated == True : if request.method == 'POST' : # MyModel.objects.filter(pk=some_value).update(field1='some value') if request.POST.get('pr_pic') == '' : post_image = request.FILES['pro_pic'] # pic = UserDetails.objects.filter(user_id = id).update(img = post_image) # UserDetails.objects.filter(user_id = id).update(img = post_image) pic = UserDetails.objects.filter(user_id = id) pic.img = post_image pic.save() Whenever an user is created his user_id gets updated in another table(UserDetails model), and the fields are null. But in the HTML ive an option to upload image later (that ive shown in the HTML). I think my views.py is wrong, please help me correct it -
How to display many fields' values with ForeignKey relationship?
Looking for solution of this problem I encountered some similar threads, but referring to older versions of Django/DRF and thus not working in my case. There are these two models: class CsdModel(models.Model): model_id = models.CharField("Item ID", max_length=8, primary_key=True) name = models.CharField("Item Name", max_length=40) active = models.BooleanField(default=True) def __str__(self): return self.model_id class CsdListing(models.Model): model_id = models.ForeignKey(CsdModel, on_delete=models.CASCADE, default=0, related_name='m_id') name = models.ForeignKey(CsdModel, on_delete=models.CASCADE, default=0, related_name='m_name') (...) What I'd like to see, is model_id and name from CsdModel displayed inside a form created based on CsdListing model. But instead, the ID is duplicated: How should I rebuild the model(s) to have both ID and name displayed in the form? -
django - upload file to a specific folder (named after a field from the userprofile)
I have a userprofile that captures the username and the group the user is assigned to. I want the uploaded files to be saved under the group name folder. The folders already exit at the media root, the files shoud be routed to these folder I tried adding a user directory path to the models, it does not solve my problem models.py class uploadmeta(models.Model): path = models.ForeignKey(Metadataform, verbose_name="ID", on_delete=models.PROTECT) doc = models.FileField(upload_to='', verbose_name="Dataset") def get_absolute_url(self): return reverse('file_list', kwargs={'pk': self.pk}) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Group= models.CharField(max_length=500, choices=Group_choices, default='Please Select') def __str__(self): return self.user.username it just creats new folders and saves the files in the media root -
How to debug django web application using specific port & localhost in visual studio code?
I want to debug django web application using visual code for that I have found solution that I have to edit launch.json for debugging django web application. launch.json "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}\\sparrow_fe\\manage.py", "port": "8005", "address" : "192.168.1.195", I have implemented above code in launch.json but still I am not able to start my web application on above port it automatically running on default port & localhost. -
TypeError: 'Tega' object not iterable
Here is my code in views.py user_driver_list = [] tega_list = [] for driversprofiles in check_all_columns: fetched_profile = fetch_rafiki_profile()[0] driver_rafiki_session_existance = RafikiDriverSession.objects.filter(rafiki_number=fetch_rafiki_profile()[0], drivers_profile=driversprofiles) user_driver = User.objects.filter(username=driversprofiles.user) user_driver_list.append(UserSerializer(user_driver, many=True).data) print("A") latest_tegas = Tega.objects.filter(driver_profile=driversprofiles).latest(field_name='start_time') tega_list.append(TegaSerializer(latest_tegas, many=True).data) print("B") I am trying got filter and get all latest Tegas for every matching driver in the check_all_columns QuerySet. -
How to filter_fields from coming list
User can select several genres for story. When I list all stories in Postman I receive genre field in list and when I type in url /stories/?genre=CD, I receive 0 stories. How to filter from coming list? class Story(models.Model): ... genre = MultiSelectField(choices=name_choices) class StoryView(viewsets.ModelViewSet): ... filter_fields = ['genre'] in Postman when listing all stories genre field look like: "genre": [ "FN", "CD" ] -
How to sort a merged querysets Django
I would like to combine multiple SQL queries into a single query, and then sort the merged query by a date field datas = None for product in products: if datas is not None: datas = datas | Data.objects.filter(product=product) else: datas = Data.objects.filter(product=product) datas = datas.all().order_by('created_on') Current result is that each "data set" is "sorted by the created_on field" and they appear one below the other. So essentially sorting is by Product Name, and then by created_on field but what I want is the combined "datasets" to be sorted as one by just the "created on field". -
Django. How to delete items from database with postman, because it doesn't work
So I am making a web app with Django api and everything works pretty fine, just the fact that postman can't delete my items from database. To my mind it is because django gives that confirmation pop up. Everything works from django ui itself, but I need postman to do the thing. How can I solve this?