Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Webfaction Access to font at domain/fonts/fontname.ext from origin 'http://mydomain' has been blocked by CORS policy: No 'Access-Control-Allow-Origin'
I have django 2.1.5 with python3.7 app worket well on local... I have create static app in my webfaction dashboard Static-Only (no .htaccess). All work fine except certains fonts i have this message this error in my browser: Access to font at 'http://domain/static/plugins/elegant_font/html_css/fonts/ElegantIcons.woff' from origin 'http://domain' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. (index):942 GET http://domain/static/plugins/elegant_font/html_css/fonts/ElegantIcons.woff net::ERR_FAILED** How can i solved it i have trying many solution (django-cors-headers and others) But not work. I need if possible step by step help ... -
Django Admin Interface - Privileges On Development Server
I have an old project running (Django 1.6.5, Python 2.7) live for several years. I have to make some changes and have set up a working development environment with all the right django and python requirements (packages, versions, etc.) Everything is running fine, except when I am trying to make changes inside the admin panel. I can log on fine and looking at the database (sqlite3) I see my user has superuser privileges. However django says "You have no permissions to change anything" and thus not even displaying any of the models registered for the admin interface. I am using the same database that is running on the live server. There I have no issues at all (Live server also running in development mode with DEBUG=True has no issues) -> I can see the history (Change Log) - Nothing else I have also tried to create a new superuser (which it does) but same problem here. I'd appreciate any pointers (Maybe how to debug this?) -
DJANGO render to PDF , QUERYSET
i am working on my django-admin, and i am trying to render to pdf my obj. This is my def: def Imprimir(self, request, obj): data = { 'id':obj.values_list('id', flat=True), 'freguesia': obj.values_list('freguesia',flat=True), 'rua': obj.values_list('rua',flat=True), 'porta': obj.values_list('porta',flat=True), 'tavaria':obj.values_list('tipo_avaria',flat=True), } pdf = render_to_pdf('daa/imprimir/avarias_pdf.html', data) return HttpResponse(pdf, content_type='application/pdf') https://i.stack.imgur.com/22V1I.png The problem is only show my queryset and the ID, i want to show the name of the queryset not the id. anyone can help me? -
Django receiving QueryDict instead of JSON (from jQuery post)
I have a Django Rest API on back-end that stores questions and answers. I also have question sessions, it's an array of questions that has to be processed within 1 request. The problem is, it works well when I send those requests from curl but when I do this via jquery Django receives QueryDict instead of json. My js: $.post('http://127.0.0.1:8000/api/sessions/create/', { questions: JSON.stringify(questions) }) When I log JSON.stringify(questions) I see it's looking like it has to be: [{"description":"test5","type":"YESNO","to_close":5,"choices":""},{"description":"test5","type":"YESNO","to_close":5,"choices":""}] I can even copy and paste it to curl, and it will work: curl -X POST http://127.0.0.1:8000/api/sessions/create/ -H 'Content-Type: application/json' --data '{"questions":[{"description":"test4","type":"YESNO","to_close":5,"choices":""},{"description":"test3","type":"YESNO","to_close":5,"choices":""}]}' But when I do via JS, Django receives it this way: <QueryDict: {'questions': ['[{"description":"test5","type":"YESNO","to_close":5,"choices":""},{"description":"test7","type":"YESNO","to_close":5,"choices":""}]']}> My post method looks like this: def post(self, request, **kwargs): """Create a session of questions""" question_data = request.data.pop('questions') session = QuestionSession.objects.create() for question in question_data: Question.objects.create( description=question['description'], question_type=question['type'], answers_to_close=question['to_close'], question_session=session) serializer = QuestionSessionSerializer(data=request.data, many=True) serializer.is_valid() serializer.save() return Response({ 'status': 'SUCCESS', 'message': 'A new session has been created!' }) What is wrong? Since I can easily do it via curl, I think the problem is in jquery request. -
Django 1.11 get() missing 1 required positional argument: 'pk'
I'm using Django 1.11 and I'm having a issue with path parameters. I'm getting an error like this for all requests involving path parameters. Error: TypeError at /posts/2 get() missing 1 required positional argument: 'pk' urls.py ... url(r'^posts',PostView.as_view()), url(r'^posts/<int:pk>/',PostView.as_view()), ... views.py .. #-------- API for CRUD -----------------# class PostView(APIView): permission_classes = (IsAuthenticated,) def get_object(self,pk,user_id): try: return Post.objects.get(pk=pk,user_id=user_id) except Post.DoesNotExist: raise Http404 def get(self,request): post = Post.objects.get(user=request.user.id) serializer = PostSerializer(post) return Response({"success":True,"data":serializer.data},status=status.HTTP_200_OK) def put(self, request, pk): post = self.get_object(pk,request.user.id) serializer = PostSerializer(post, data=request.data) if serializer.is_valid(): serializer.save(user=request.user.id) return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def post(self,request): params = request.data params['user'] = request.user.id serializer = PostSerializer(data=request.data) serializer.is_valid(raise_exception=True) saved_data = self.perform_create(serializer) post = PostSerializer(saved_data) return Response({"success":True, "message":"Post Added Successfully","data":post.data}, status=status.HTTP_201_CREATED) def perform_create(self, serializer): return serializer.save() ... url example : GET : localhost:8000/posts/2 Can someone tell me how to pass positional parameters. -
Can soneone give me an Idea for authentication an Django Company Application via AD / SSO
Right now i'm developing an company application based on django. For authentication and authorization right now i use django-auth-ldap. But i will add a SSO feature, so my guys working in the company don't need to login if they are working on an company computer. For authorization purpose i use the group mechanism from django-auth-ldap, but django-auth-ldap don't support sso on my web application. Has anyone an Idea for: Company application, User base is Microsoft Active Directory right managemend should be done via AD-groups django-auth-ldap is working, bug users has to login in the application working on an company computer (running kerberos) should auto-login to the web-application rights managemend should work using django-auth-ldap Thanks a lot for an idea to let this run. Robert -
How to filter an object with choice filed values in django_filter
I have following choice field in my model IPInfo class IPInfoModel(models.Model): TYPE_INTRANET = 1 TYPE_INTERNET = 2 IP_TYPES = ( (TYPE_INTRANET, u'INTRANET'), (TYPE_INTERNET, u'INTERNET'), ) ip = models.GenericIPAddressField("IP", unique=True) ip_type = models.SmallIntegerField(choices=IP_TYPES) and I use django_filters to filter IPInfo. from django_filters import rest_framework as django_filters class IPInfoFilter(django_filters.FilterSet): ip_type = django_filters.ChoiceFilter(choices=IPInfoModel.IP_TYPES) class Meta: model = IPInfoModel fields = ["ip_type",] class IPInfoViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): queryset = IPInfoModel.objects.all() serializer_class = IPInfoSerializer filter_class = IPInfoFilter I want to filter IPInfo on ip_type. How can I filter IPInfo by either "INTRANET" or "INTERNET". not use "1" or "2". -
Mock an entire python module for django testcases
I'm currently trying to mock a credentials.py module which is not available during the tests when running them with Gitlab Runner in the pipeline (credentials are on .gitignore). My test_views.py looks like this: @patch('battery_upgrade_web.views.BatteryUpgradeView.credentials', new=credentials_example) class IndexViewTest(TestCase): @patch('battery_upgrade_web.views.BatteryUpgradeView.credentials', new=credentials_example) def setUp(self): # A client simulates a user interacting with the code at the view level # Lot of working mocks self.c = Client() @patch('battery_upgrade_web.views.credentials', new=credentials_example) def test_valid_data(self): resp = self.c.post('/', data={'parameter': 324}) My views.py: from battery_upgrade_web import credentials class BatteryUpgradeView(generic.TemplateView): def post(self, request, *args, **kwargs): #lot of code to execute My problem is, that I can't only patch the variables in credentials.py but I have to patch the whole module and replace it with credentials_example.py. My solution above works locally with existing credentials.py, it also mocks the credentials.py and replaces it with my credentials_example.py during tests. But when I delete credentials.py, the test throws following error message when running >python web/manage.py test battery_upgrade_web: Creating test database for alias 'default'... Traceback (most recent call last): File "web/manage.py", line 16, in <module> execute_from_command_line(sys.argv) # lot of tracebacks File "C:\Users\e\AppData\Local\Continuum\anaconda2\envs\BatteryUpgrade36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_loal File … -
Django design model - when a data of status field changes, remaining models status change with it
Its my first time trying django as my first programming project. I have a hierarchy structure of Company -> Business -> Outlets using foreign key. I would like to know is there anyway to structured it in a way where the Company status is saved as inactive status, the remaining business, outlets models that will be triggered as inactive status. from django.db import models from django.contrib.auth.models import User # Create your models here. class Common_Info(models.Model): """(Common description)""" name = models.CharField(blank=True, max_length=100) slug = models.SlugField(unique=True, max_length=120) address_1 = models.CharField(max_length=50, null=True) address_2 = models.CharField(max_length=50, null=True) address_3 = models.CharField(max_length=50, null=True) post_code = models.CharField(max_length=6, null=False) registration_no. = models.CharField(max_length=15,null=False) gst_no. = models.CharField(max_length=15,null=True) telphone_no. = models.CharField(max_legth=15, null=False) fax_no. = models.CharField(max_legth=15, null=True) email_address = models.EmailField(max_length=254,null=False) """(Status choice)""" Active_Status = 1 Inactive_Status = 0 STATUS_CHOICES = ( (Active_Status, 'Active'), (Inactive_Status, 'Inactive'), ) status = models.IntegerField(choices=STATUS_CHOICES, default=Active_Status) create_date = models.DateTimeField(auto_now_add=True) create_user = models.ForeignKey(settings.AUTH_USER_MODEL) modified_date = models.DateTimeField(auto_now_add=True) modified_user = models.ForeignKey(settings.AUTH_USER_MODEL) class Meta: abstract = True class Company(Common_Info): """(Company additional description)""" gst_no. = models.CharField(max_length=15,null=True) class Meta: verbose_name ='Company' verbose_name_plural = "Companies" def __unicode__(self): return u"Company" class Business(Common_Info): """(Business description)""" parent=models.ForeignKey(Company, on_delete=models.CASCADE) gst_no. = models.CharField(max_length=15,null=True) class Meta: verbose_name ='Business' verbose_name_plural = "Businesses" def __unicode__(self): return u"Business" class Outlet(Common_Info): outlet_code = models.CharField(max_length=3, unique=True) … -
'QuerySet' object does not support item assignment
class PostDetailView(DetailView): model = Post template_name = 'detail.html' def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) instance = Post.objects.get(pk=self.kwargs.get('pk')) user = instance.post_user context['comments'] = Comment.objects.filter(comment_post=instance.pk) context['comments']['profile'] = Profile.objects.get(user=user) return context This is my view so far. When i use that code i get this error 'QuerySet' object does not support item assignment. How do i attach the line below correctly? context['comments']['profile'] = Profile.objects.get(user=user) -
Querying objects from 1:M related Models DRF
Designed a Django Model with multi-level 1:M relations, able to get the json response writing Serializers in DRF. It looks easy to perform CRUD operations but only particular to that table, I am expecting response something similar to the response below , then came across a term called Nested Serializers, As I am not much aware of that, can any one suggest me to have one for the below model { "Blocks": [ { "id": 1, "name": "A", "Floor": [ { "id": 1, "name": 0, "books": [ { "id": 1, "name": "White Tiger" }, { "id": 1, "name": "The Alchemist" } ] }, { "id": 2, "name": 1, "books": [ { "id": 1, "name": "Facebook" }, { "id": 1, "name": "The Master Blaster" } ] } ] }, { "id": "2", "name": "B", "Floor": [ { "id": 1, "name": 0, "books": [ { "id": 1, "name": "Know Your self" }, { "id": 1, "name": "The Naga" } ] }, { "id": 2, "name": 1, "books": [ { "id": 1, "name": "The Data Analyics" }, { "id": 1, "name": "Become Master of R" } ] } ] } ] } -
Error fetching data through database in django
from django.shortcuts import render from django.http import HttpResponse def index(request): all_employee = employee.objects.all() html = '' for employee in all_employee: url = 'mainpage/' + str(employee.id) + '/' html += '' + url + '' return HttpResponse(html) def details(request, id): return HttpResponse("This is the details for" + str(id) + " ") the line all_employee = employee.objects.all() is giving the error and when I use this command in shell it is giving this [, , ] instead of each row data -
Cannot get dictionary values in jinja2 templates (Django)
I am trying to access the value of the class dictionary in jinja2 template. I have structure like this: class ClassName: ... return {'key_name': 'value1', 'key_name2': {'inside_key':'inside_value'} def get_data_from_dictionary(request): data = ClassName() return render(request, 'data.html', {'data' :data}) My data.html page looks like this: <!DOCTYPE html> <html> <body> <h1>{{ data.key_name }}</h1> <h2>{{ data.key_name2.inside_key }} </body> </html> I do not get any error and I see a blank page in browser. I have allready tried to call class like this: {{ data[key_name] }} But when I do this, I get an error: django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '[key_name]' from'pres_key[key_name]' What I am doing wrong?? -
Migrating to Bokeh >1.0: Missing 'arguments' parameter in server_session
Background: I have legacy production code which embeds Bokeh applications inside Django. The purpose is to serve user-specific dashboards. The Bokeh code accesses username arguments from the request, per the documentation. The applications were built using bokeh 0.13. On the Django side, the username argument is passed as in the example below: Example snippet from views.py: from bokeh.util import session_id from bokeh.embed import server_session def get_bokeh_script(user, url_suffix): bokeh_session_id = session_id.generate_session_id() bokeh_url = "https://" + settings.BOKEH_HOST + ":" + settings.BOKEH_PORT + url_suffix script = server_session(url=bokeh_url, session_id=bokeh_session_id, resources=None, arguments={"username":user.username}) return script def my_view1(request): url_suffix = "/my_suffix" script = get_bokeh_script(request.user, url_suffix) return render(request,'dashboard/index.html',{'script':script}) Current scenario: I need to migrate the code to bokeh >1.0, particularly for the on_session_destroyed method of the Document() object. However, it appears that the arguments parameter of server_session has been removed, per the migration guide (see also discussion here). Question: Is there a workaround that will enable me to pass username as an argument from Django to Bokeh, in version 1.0.* ? -
How to add a custom boolean action button in Django Admin?
I have a model which is registered with the admin. models.py class Post(models.Model): title = models.CharField(max_length=100) tag = models.CharField(max_length=3) is_enabled = models.BooleanField(default=False) Now, I want that the admin can only enable or disable the Post by interacting with is_enabled field of the model. admin.py class PostAdmin(admin.ModelAdmin): list_display = ['id', 'title', 'tag', 'is_enabled'] list_display_links = None readonly_fields = ['id', 'title', 'tag'] actions = ['enable_selected', 'disable_selected'] def enable_selected(self,requst,queryset): queryset.update(is_enabled=True) def disable_selected(self,requst,queryset): queryset.update(is_enabled=False) enable_selected.short_description = "Enable the selected Post" disable_selected.short_description = "Disable the selected Post" I have successfully added these actions on the dropdown, however I need to add this in the form of a button on the list, also I need to know how can I call a function when the button is hit to update the is_enabled field. -
How to use Django-filters with large data?
I am using Django-filter with django_filters.ModelChoiceFilter. I am facing the issue that the website is very slow if I have large data in Suburb table. class PDetailFilter(django_filters.FilterSet): class Meta: model = PDetail fields = { # 'code': ['icontains'], # 'bu_name': ['icontains'], # 'bc_effect_date' : ['year__gt', 'year__lt', ], } # Filter by Suburb suburb = django_filters.ModelChoiceFilter(label="Suburb", queryset=Suburb.objects.all()) -
serializer call is showing an TypeError: Object of type 'ListSerializer' is not JSON serializable?
Iam trying to call a serializer in django GET request But it shows up an TypeError: Object of type 'ListSerializer' is not JSON serializable Please help me if i went wrong somewhere. Thanks in Advance. class Member(MemberMixin, APIView): serializer_class = MemberSerializers def get(self, request, format=None): objects = MemberSerializers(Members.objects.all(), many=True) self.meta_data = "GET" self.module = "Member" self.data = objects if objects is None: self.error = "datas are not found" return Response(self.response_obj, status=status.HTTP_404_NOT_FOUND) else: return Response(self.response_obj, status=status.HTTP_200_OK) pass -
Changing BoundField value after initializing and validating form
I am trying to manually change the name of a form field after it initialized in a CBV. You could do this after initializing: form = self.get_form() # it is initialized here form.cleaned_data['name'] = form.instance.name + ' (new)' But I need to change the value after validating, so form.cleaned_data is no longer involved. I need to directly change the value of the BoundField. How can I do that? Or how can I do what I am trying to do in any other way? -
Django - csv.reader and save()/update
I am trying to update a field or multiple fields from my DB by reuploading a CSV-File with a changed value. I tried this: views.py def file_upload(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): id = 0 das2 = CSV3.objects.all().values_list() csv_file = request.FILES['file'] with open(str(csv_file)) as file: reader = csv.reader(file) for row in reader: id += 1 try: _, p = CSV3.objects.get_or_create(id = id, defaults = {'gebaeudebereich' : row[0], 'gebaeudenummer' : row[1], 'ebene' : row[2], 'raum' : row[3], 'dose' : row[4], 'switch_ip' : row[5], 'switch_port' : row[6], 'datum' : row[7], 'akteur' : row[8]}) except IntegrityError: for i in das2: i[1] = row[0] i.save() return redirect('appp:index') form = UploadFileForm() return render( request, "appp/file_upload.html", {"form": form} ) I looped through the values and set value 'gebaeudebereich' to the gebaeudebereich value in the CSV-File (I would do this with the other fields too but this is the idea I tried). It is not saving anything and it does not give me an error, just doesn't do anything. The try clause works just fine. my models.py class CSV3(models.Model): gebaeudebereich = models.CharField(max_length=100) gebaeudenummer = models.CharField(max_length=100) ebene = models.CharField(max_length=100) raum = models.CharField(max_length=100) dose = models.CharField(max_length=100) switch_ip = models.CharField(max_length=100) switch_port = models.CharField(max_length=100) datum = … -
How to export inline text fields into xlsx (or csv)?
I am currently capable of exporting one of the models into xlsx files with the variables that are added in the models.py. However, one of the models that I have has an inline with a text field - and I wish to add this text field into the xlsx export. Does anybody have a previous experience with this? Thanks in advance! -
How to specify help text in a Django Cloudinary Field
How do I include a help_text in CloudinaryField() options in django models I've tried setting it by extending CloudinaryField and passing options. class CloudinaryField(BaseCloudinaryField): def upload_options(self, model_instance): return { 'public_id': pid, 'unique_filename': False, 'overwrite': True, 'resource_type': 'image', 'tags': ['user', 'avatar'], 'invalidate': True, 'quality': 'auto:eco', } -
Django Formset: multichoice queryset filter is not working for my formset after many attempts
I have Contestant model that has many-to-one relationship with Category. I want the creator of the award to only have access to last 15 categories of the award he has created in instantiating contestant model. That's, the multichoice queryset in the Contestant field(category) will only show the list of the last 15 categories being created in the Category Model. I have made different efforts, but the code is either not working or giving '['ManagementForm data is missing or has been tampered with']' error. I have made countless re-factorization of codes and I have tried to adopt solutions I found on internet. But they didn't work. # MY CATEGORY MODEL class Category(models.Model): award = models.ForeignKey(Award, on_delete=models.CASCADE) award_category = models.CharField(max_length=150, blank=True, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.award_category # MY CONTESTANT MODEL class Category(models.Model): award = models.ForeignKey(Award, on_delete=models.CASCADE) award_category = models.CharField(max_length=150, blank=True, null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.award_category #MY VIEW def get_award(request, pk): new_award = get_object_or_404(Award, pk=pk) Contest_Formset = modelformset_factory(Contestant, fields('contestant_name', 'category',), extra=15) formset = Contest_Formset(request.POST) for form in formset: form.fields['category'].queryset = Category.objects.filter(user=request.user)[1:15] if request.method == 'POST' and form.is_valid(): myform = form.save(commit=False) myform.award_name = new_award myform.save() return redirect('award_details', pk=new_award.pk) else: formset = Contest_Formset() context = { 'new_award': … -
How to deploy a djanho backend and react frontennd app to same domain
So I googled around for the answer to this question and found a way to deploy just a react app to github pages using this medium article. The issue is my react app has a django back end. So github pages won't work. I also know how to deploy a django site to heroku. I also know you can deploy a react app to heroku. But deploying them separately makes them have different domains. Now is there a way to deploy a fullstack django and react app to heroku so both has same domain? -
Addig form fields to a custom user model in django admin panel
I'm going through the django for beginners book, testing the code from the chapter 8 about the Custom user model. The goal is to add the field age in the auth user model by subclassing the AbstractUser model. First we create out CustomUser in models.py from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True) Then creating CustomUserCreationFrom and CustomUserChangeFrom in forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationFrom(UserCreationForm): class Meta(UserCreationForm.Meta): model = CustomUser fields = UserCreationForm.Meta.fields + ('age',) class CustomUserChangeFrom(UserChangeForm): class Meta(UserChangeForm.Meta): model = CustomUser fields = UserCreationForm.Meta.fields And finally, the CustomUserAdmin in admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationFrom, CustomUserChangeFrom from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationFrom form = CustomUserChangeFrom model = CustomUser list_display = ['username', 'email', 'age', 'is_staff',] admin.site.register(CustomUser, CustomUserAdmin) And of course telling django about our custom auth model in settings.py: AUTH_USER_MODEL = 'users.CustomUser' Logged as a super user, and when trying to add a new user, there is no field age in the creation form. Am I missing something? -
Django - logout users on browser close or after timeout
I have added my own login/logout page. I want to make session expires either on browser close or when timeout is reached. I found 2 parameters which I have included in setting.py: SESSION_EXPIRE_AT_BROWSER_CLOSE SESSION_COOKIE_AGE But it seems that they are only working for admin panel, nor for my own. Should I have done something more?