Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to write a unit test for uploading an Image in django rest framework
I'm using Django rest frame work to develop a RESTful API. I've implemented a post method that allows a user to upload and image as shown below. I'm using models.ImageField for the document field. Further below I have also implemented the test case I doubt it will work. How do I implement a test case for uploading and image. Post method def post(self, request, *args, **kwargs): """ Creates a document. """ logged_in_user = request.auth['user_id'] # print(request.data) org_id = get_auth(request) name = request.data['name'] document = request.FILES['document'] try: doc_object = Document.objects.create( owner = logged_in_user, org_id= org_id, name=name, document=document ) return Response(status=status.HTTP_201_CREATED) except Exception as e: raise e Test Case def test_can_upload_a_document(self): pic = os.path.join(settings.BASE_DIR, '/media/images/', 'test_pic.png') test_picture = open(pic, 'rb') payload ={ "owner":self.employee.id, "name":"Edward Gates", "document":test_picture, "notes":"Add notes here", "assessment_status":"Pending" } url = reverse('hr:documents') self.client.credentials(HTTP_AUTHORIZATION=self.token) response = self.client.post(url,data=payload,format='mutipart') self.assertEqual(response.status_code, 200) -
Saving translated slug of django modeltranslation not working
I've been breaking my head over this for a day now. I use django-modeltranslation to translate blog-like posts. All works fine, except I also try to automatically translate the slugs from the title, based off of this article: https://raphaelbeck.wordpress.com/2011/04/16/how-to-translate-slug-with-django-modeltranslation/ Only the translated slug is not translated saved to the database. class Item(models.Model): category = models.ForeignKey( 'help.category', on_delete=models.PROTECT, related_name='categories') title = models.CharField(_('Titel'),max_length=255) description = RichTextField(_('Omschrijving')) slug = AutoSlugField(_('slug'), populate_from='title', overwrite=True) class Meta: verbose_name = _(u"Item") verbose_name_plural = _(u"Items") #automatically creating slugs for translations def save(self, *args, **kwargs): for lang_code, lang_verbose in settings.LANGUAGES: if hasattr(self, 'slug_%s' % lang_code) and hasattr(self, 'title_%s' % lang_code): setattr(self, 'slug_%s' % lang_code, slugify(getattr(self, 'title_%s' % lang_code, u""))) print(self.slug_nl) print(self.slug_en) print(self.slug_nl) print(self.slug_en) super().save(*args, **kwargs) def __str__(self): return str(self.title) I added some print funtions to see what actually happens. The console logs are as expected: dutch-slug None dutch-slug english-slug dutch-slug english-slug -> slug_en is translated correctly based on the title in the console, but in the database the dutch slugs are saved. Thanks in advance! Any ideas are greatly appreciated. -
Writing in memory zip file to django FileField
Im trying to read files from FileField, put them all to zip and save that zip to another FileField. Im trying to avoid using temp file but it seems that i might have to. Here is what i got so far: def generate_codified_batch(modeladmin, request, queryset): for batch in queryset: pieces = Pieces.objects.filter(batch=batch) mem_zip = InMemoryZipFile(file_name=batch.name) for piece in pieces: in_file = open(piece.file.path, 'rb') data = in_file.read() mem_zip.append(filename_in_zip=f'/{piece.folder_assigned} /{piece.period}/{piece.codification}. \ {piece.file_name.rsplit(".")[-1]}' , file_contents=data) in_file.close() files_codified = ContentFile(mem_zip.data) Batches.objects.filter(pk=batch.id).update(file_codified=files_codified) InMemoryZipFile is a class from this packet: https://bitbucket.org/ruamel/std.zipfile/src/faa2c8fc9e0072f57857078059ded42192af5435/init.py?at=default&fileviewer=file-view-default#init.py-57 Important are only two last lines files_codified = ContentFile(mem_zip.data) Batches.objects.filter(pk=batch.id).update(file_codified=files_codified) mem_zip.data is a property of InMemoryZip and returns bytes object (from InMemoryZip class): self.in_memory_data = StringIO() @property def data return self.in_memory_data.getvalue() I cannot for the life of me figure out how to read from that bytes object and pass it to FileField. -
get_FIELD_display() does not display correct value
I have been trying to use get_name_display() in my API View but it does not display the text, just number. I have checked the documentation but it does not mention anything about it - it should be working. For instance, the folowing code prints 3 instead of 'GaussianNB'. Model class Algorithm(models.Model): ALGORITHM_NAME = ( (0, 'KNeighborsClassifier'), (1, 'LogisticRegression'), (2, 'LinearSVC'), (3, 'GaussianNB'), (4, 'DecisionTreeClassifier'), (5, 'RandomForestClassifier'), (6, 'GradientBoostingClassifier'), (7, 'MLPClassifier'), ) name = models.CharField(max_length=64, choices=ALGORITHM_NAME) parameters = JSONField() View class CalcUpdateView(UpdateAPIView): queryset = Calc.objects.all() serializer_class = CalcSerializer def perform_update(self, serializer): instance = serializer.save() algorithm = Algorithm.objects.get(pk=self.request.data['algorithm']) print(algorithm.get_name_display()) Thanks in advance for help! -
django form wizard using UserCreationForm
I'm trying to make a 3paged form which is an application form for my school club. I just looked over the formtools official document but I barely understood how to use it. And this is the code for the form. (forms.py) from django import forms from django.contrib.auth.forms import UserCreationForm from .models import HiarcUser, STATUSES, MAJORS, SEMESTERS import json # import request class HiarcUserCreationForm1(UserCreationForm): # 1 email = forms.EmailField(required=True) real_name = forms.CharField(required=True, max_length=20) student_id = forms.CharField(required=True, max_length=7) # validator phone_number = forms.CharField(required=True, max_length=20) status = forms.CharField(required=True, widget=forms.Select(choices=STATUSES)) semester = forms.CharField(required=True, widget=forms.Select(choices=SEMESTERS)) major = forms.CharField(required=True, widget=forms.Select(choices=MAJORS)) minor = forms.CharField(required=True, widget=forms.Select(choices=MAJORS)) class Meta: model = HiarcUser fields = ("email", "real_name", "student_id", "phone_number", "status", "semester", "major", "minor") def save(self, commit=True): user = super(HiarcUserCreationForm1, self).save(commit=False) user.email = self.cleaned_data["email"] user.real_name = self.cleaned_data["real_name"] user.student_id = self.cleaned_data["student_id"] user.phone_number = self.cleaned_data["phone_number"] user.status = self.cleaned_data["status"] user.semester = self.cleaned_data["semester"] user.major = self.cleaned_data["major"] user.minor = self._clean_fields["minor"] ''' webhook_url = system.environment['SLACK_WEBHOOK_URL'] message = "회원가입 신청이 들어왔습니다. \n이름 : {}\n 이메일 : {} \n학과/학번/학년 : {}\n 자세한 사항은 관리자페이지에서 확인해보세요.".format(user.real_name, user.email, user.status) slack_data = { "text": message, "color": "#FAA3E3"} response = requests.post( webhook_url, data=json.dumps(slack_data), headers={'Content-Type': 'application/json'} ) ''' if commit: user.save() return user class HiarcUserCreationForm2(UserCreationForm): # 2 motivation = forms.CharField(required=True, widget=forms.Textarea) portfolio = forms.CharField(widget=forms.Textarea) … -
Exception Value:NOT NULL constraint failed: auth_user.username
I am creating a project to register and view profile using Django. The problem is when I am trying to register a new user I am getting some errors NOT NULL constraint failed: auth_user.username Here is my form.py and view.py file: form.py from django.contrib.auth.models import User from django import forms from django.contrib.auth.forms import UserCreationForm,UserChangeForm class FileDataForm(forms.Form): name = forms.CharField(max_length=50) file = forms.FileField() image = forms.ImageField() class userregister(UserCreationForm): first_name = forms.CharField(max_length=50, required = False ,help_text ='optional') last_name = forms.CharField(max_length=50, required = False ,help_text ='optional') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('first_name', 'last_name', 'email', 'password1', 'password2', ) class editprofileform(UserChangeForm): class Meta: model = User fields = ('first_name', 'last_name', 'email','password') View.py: from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render,redirect,render_to_response from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import View from .models import FileData from .forms import FileDataForm from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from .forms import userregister,editprofileform from django.contrib.auth.forms import UserChangeForm , PasswordChangeForm from django.contrib.auth import update_session_auth_hash # Create your views here. @login_required def home(request): return HttpResponse('<h1>Welcome to your first page<h1>') def registration(request): print request print 'request' if request.method == 'POST': #save the user data … -
Search multiple models (Elasticsearch)
i added a second model to my app and now i also want to search trough the fields for that model and return it in the same view as my first model. views.py #Elasticsearch def globalsearch_elastic(request): qs = request.GET.get('qs') page = request.GET.get('page') if qs: qs = PostDocument.search().query("multi_match", query=qs, fields=["title", "content", "tag"]) qs = qs.to_queryset() else: qs = '' paginator = Paginator(qs, 10) # Show 10 results per page try: qs = paginator.page(page) except PageNotAnInteger: qs = paginator.page(1) except EmptyPage: qs = paginator.page(paginator.num_pages) return render(request, 'MyProject/search/search_results_elastic.html', {'object_list':qs}) currently only PostDocument get searched for a match, how do i add a second one here from documents.py in this function? or to be more specific, what do i have to change in this line to Search multiple documents? qs = PostDocument.search().query("multi_match", query=qs, fields=["title", "content", "tag"]) Thanks in advance -
Django logging to wxpython window?
I'm writing a utility to start up a django server process that outputs its logs to a TextCtrl in a wxpython window. Unfortunately, a couple different approaches have led to weird issues where the operating system (OSX in this case) crashing the program with complaints about "Illegal Instruction" after a few successful log entries. I'm currently doing this by implementing a logging.Handler subclass that posts events to wx that contain the logging records to be shown in the window. Is there a better approach? Thanks! -
.env file in pipenv (django) - ValueError: embedded null character
I got a .env file inside my project SECRET_KEY="vvvvvvvtestvvvvv" I run pipenv shell But I get like a bunch of errors. File "c:\users\sander-pc\appdata\local\programs\python\python37\lib\site-packages\pipenv\core.py", line 172, in load_dot_env dotenv.load_dotenv(dotenv_file, override=True) File "c:\users\sander-pc\appdata\local\programs\python\python37\lib\site-packages\pipenv\vendor\dotenv\main.py", line 262, in load_dotenv return DotEnv(f, verbose=verbose).set_as_environment_variables(override=override) File "c:\users\sander-pc\appdata\local\programs\python\python37\lib\site-packages\pipenv\vendor\dotenv\main.py", line 105, in set_as_environment_variables os.environ[k] = v File "c:\users\sander-pc\appdata\local\programs\python\python37\lib\os.py", line 684, in __setitem__ self.putenv(key, value) What am I doing wrong? -
I'm trying to output a filtered list on my Django template
For example, I have in models.py: class Development(models.Model): id = models.AutoField(primary_key=True) client = models.ForeignKey(InsName, on_delete=models.SET_NULL, null=True, blank=True) platform = models.ManyToManyField(Platform) user = models.ForeignKey(User, on_delete=models.CASCADE) and in views.py (with the corresponding url added to urls.py): class DevelopmentFilterView(generic.ListView): model = Development How do I tell my template to only output a list of the database entries for a certain client? -
Django-filter best practice on model field choice filter
I am struggling with an issue that I would think is pretty common but on which i couldn't find any working example. Say I have a Django Model : class Shop(models.Model): name = models.CharField(max_length=100, verbose_name="Shop Name") ... city = models.CharField(max_length=100, verbose_name="City") ... class Meta: verbose_name = "Chantier" What would be the best way to allow the user to filter Shops by City using django-filter ? So far I've used ModelMultipleChoiceFilter with the widget CheckboxSelectMultiple, but for some reason I'm struggling with getting a clean list of choices (no duplicates) and linking the filtered values to an actual filter query that works (without having to do some complex things). Is there an easy way to do this ? Thanks ! -
Checkbox data not coming through in django
I have a html template with multiple checkboxes, when i run request.POST.getlist(), I get an empty list back regardless of what checkboxes are selected. view class: class AddNewDevice(TemplateView): def get(self, request, *args, **kwargs): context = {} context['devices'] = get_devices(request.user) return render(request, self.template_name, context) def post(self, request, *args, **kwargs): post_data = request.POST print(request.POST.getlist('devices_selected')) save_data(request.POST.getlist('devices_selected')) return redirect('/dashboard.html') html form: <form method='POST'> {% csrf_token %} <div class="card mb-3"> <div class="card-header"> <i class="fas fa-table"></i> devices</div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th></th> <th>Serie Nummer</th> <th>Gebouw</th> <th>Locatie</th> </tr> </thead> <tbody> {% for device in devices %} <tr> <td> <input type="checkbox" value="{{obj.serial_number}}" name="devices_selected"> </td> <td>{{device.serial_number}}</td> <td>{{device.device_building}}</td> <td>{{device.device_location}}</td> </tr> {% endfor %} </tbody> </table> </div> </div> <div class="card-footer small text-muted">Geupdate om 12:00 uur</div> </div> <br> <button type="submit" class="btn btn-primary">Toevoegen</button> <br> </form> As i stated earlier request.POST.getlist('devices_selected') returns an empty list, regardless of what is selected. I want a list with all the values (obj.serial_number) from the selected checkboxes. -
Django 2.1 error while executing makemigrations
I am on my way to move to Django 2.1.5 with Python 3.7 from Django 1.6.0 with Python 2.7 and encountered an error while executing python manage.py makemigrations myapp. Could anyone give me a hint to solve, please? I probably need to modify the model but am not sure what I should start with. Migrations for 'model': model/migrations/0001_initial.py - Create model XXXX - Create model YYYY - Create model ZZZZ Traceback (most recent call last): File "manage.py", line 7, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/makemigrations.py", line 184, in handle self.write_migration_files(changes) File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/makemigrations.py", line 222, in write_migration_files migration_string = writer.as_string() File "/usr/local/lib/python3.7/site-packages/django/db/migrations/writer.py", line 151, in as_string operation_string, operation_imports = OperationWriter(operation).serialize() File "/usr/local/lib/python3.7/site-packages/django/db/migrations/writer.py", line 110, in serialize _write(arg_name, arg_value) File "/usr/local/lib/python3.7/site-packages/django/db/migrations/writer.py", line 62, in _write arg_string, arg_imports = MigrationWriter.serialize(item) File "/usr/local/lib/python3.7/site-packages/django/db/migrations/writer.py", line 279, in serialize return serializer_factory(value).serialize() File "/usr/local/lib/python3.7/site-packages/django/db/migrations/serializer.py", line 37, in serialize item_string, item_imports = serializer_factory(item).serialize() File "/usr/local/lib/python3.7/site-packages/django/db/migrations/serializer.py", line 197, in serialize return self.serialize_deconstructed(path, args, kwargs) File "/usr/local/lib/python3.7/site-packages/django/db/migrations/serializer.py", line 85, … -
Django 2.0 custom middleware process_exception hook not firing
My custom middleware class seems to be skipping the process_exception stage during the response cycle from django.utils.deprecation import MiddlewareMixin class MyMiddleware(MiddlewareMixin): def process_request(self, request): print("Request!") def process_response(self, request, response): print("Response!") return response def process_exception(self, request, exception): print("Exception!") Middleware configured.... DJANGO_MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ] LOCAL_MIDDLEWARE = [ 'path.to.MyMiddleware', ] MIDDLEWARE = DJANGO_MIDDLEWARE + LOCAL_MIDDLEWARE and buried in my view code: def some_view(request): ... raise Exception("foo") However when I hit the url I get this in the console log: Request! Internal Server Error: /my/url/ Traceback (most recent call last): ... long traceback ... File "/path/to/my/views.py", line 184, in some_view raise Exception("foo") Exception: foo ERROR django.request 2019-01-24 11:50:48,270 [exception.py handle_uncaught_exception 118] Internal Server Error: /my/url/ Traceback (most recent call last): ... long traceback ... File "/path/to/my/views.py", line 184, in some_view raise Exception("foo") Exception: foo Response! As you can see, process_exception isn't called at all, process_request and process_response both. And for some reason the exception traceback is shown twice before my middleware's process_response is even hit. The response that is passed to process_response for my middleware is a standard Django 500 debug page suggesting that the exception has been handled already, but I was under … -
Creating a new model object populating a form
I made another post before about this but I think I explained myself wrong. I have my class called 'Empresa'. Users of the webpage can registrate their own company ('Empresa') by populating a ModelForm in a view. The problem is that I can't find the syntaxis anywhere. I have: models.py: from django.db import models class EmpresaManager(models.Manager): def create_empresa(self): empresa = self.create() return empresa class Empresa(models.Model): codigo = models.CharField(max_length=3, null=False, default='000') nombre = models.CharField(max_length=100, null=False, default='Sin nombre') email = models.EmailField(null=False, default='email@empresa.com') direccion = models.CharField(max_length=100, null=False, default='Sin direccion') localidad = models.CharField(max_length=100, null=False, default='Sin localidad') codDgi = models.SmallIntegerField(null=True) docDgi = models.CharField(max_length=13, null=True) sIva = models.CharField(max_length=1, null=True, default='1') mesCierre = models.IntegerField(null=True, default=0) fecIni = models.DateField(null=True) ruca = models.IntegerField(null=True) novedad = models.CharField(max_length=50, null=True, default='') fecNovedad = models.DateTimeField(null=True) ultVersion = models.CharField(max_length=20, null=True, default='') logo = models.ImageField(null=True) habilitado = models.CharField(max_length=1, null=True, default='S') codEmpresa = models.CharField(max_length=3, null=True) codComp = models.CharField(max_length=3, null=True, default='') objects = EmpresaManager() forms.py: from django import forms from django.forms import ModelForm from .models import Empresa class RegistroEmpresaForm(ModelForm): class Meta: model = Empresa fields = ["nombre", "docDgi", "email"] views.py: from django.shortcuts import render from Empresa.forms import RegistroEmpresaForm from Empresa.models import Empresa from django.http import HttpResponse def registrado(request): form = RegistroEmpresaForm(request.POST or None) titulo = "Registro SIG … -
Django Monitoring Web App IoT project using LoRaWAN with Arduino+Dragino nodes
I have a project "Django Monitoring Web App IoT project using LoRaWAN with Arduino+Dragino nodes". And I would like to ask what limitations will I have, if it is possible for 100% to pull/push data to the app and how does this concept seems to be. I have something like this in mind Whole concept. I appreciate any help and advice. Thank you very much! -
Django Import Export Object of type Post is not JSON serializable
Hi all please bear with me if this is a trivial question as i am just starting off with Django. I am using Django-Import-Export to integrate import/export actions to the Django Admin interface. Every thing works fine after subclassing my admin class with ImportExportActionModelAdmin. However one of the fields in the model is a JSONField and it is exported as is (as expected). I want the keys in the JSON to be converted into separate fields when I export it. Sample Code: class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) details = JSONField(null=True, blank=True, default=dict) objects = models.Manager() def __str__(self): return self.title class PostResource(resources.ModelResource): details = fields.Field(attribute='details', widget=JSONWidget) class Meta: model = Post fields = ('details',) class PostAdmin(ImportExportActionModelAdmin): resource_class = PostResource After doing this, when I try to export the data from the Admin interface it gives me the following error in the browser. Object of type Post is not JSON serializable Request Method: POST Request URL: http://127.0.0.1:8000/admin/post/post/ Django Version: 2.1.3 Exception Type: TypeError Exception Value: Object of type Post is not JSON serializable Thanks in advance -
How can I filter a query by a foreign key?
I'm trying to get a list of "Peliculas" filtered by their "Director" in my DirectorDetailView I can't find the correct syntax to do this. Django Version: 2.1.4 #MODEL DIRECTOR class Director(models.Model): nombre = models.CharField( max_length=100 ) fecha_nacimiento = models.DateField() fecha_defuncion = models.DateField( 'Fallecido', null=True, blank=True, ) foto = models.ImageField( upload_to='images/directores/', default='images/directores/sin_foto.jpg' ) #MODEL PELICULA class Pelicula(models.Model): titulo = models.CharField( max_length=100 ) url_trailer = models.CharField( max_length=100 ) fecha = models.DateField() notas_posibles = ( (1, 1), (2, 2), (3, 3), (4, 4), (5, 5) ) nota = models.IntegerField( default=3, choices=notas_posibles ) sinopsis = models.TextField( max_length=400, default="Sin sinopsis" ) caratula = models.ImageField( upload_to='images/peliculas/caratulas', default='images/peliculas/caratulas/sin_caratula.jpg' ) imagen_promocional = models.ImageField( upload_to='images/peliculas/imagenes_promocionales', default='images/peliculas/imagenes_promocionales/sin_imagen.jpg' ) genero = models.ManyToManyField( Genero, blank=True, related_name='genero' ) director = models.ForeignKey( Director, on_delete=models.SET('Sin Director') ) #MY VIEW class DirectorDetailView(DetailView): model = Director template_name = "videoclub/director.html" def get_context_data(self, **kwargs): print(self.model) context = super(DirectorDetailView, self).get_context_data(**kwargs) context['peliculas'] = Pelicula.objects.all() #HERE return context With this code i receive all the "Peliculas" but i only one to get those made by the Director of my view. Dont really know what i'm doing wrong. I dont even know if i have to do this with "DetailView" Ty guys! -
Django search_fields(fld1, fld2, tab2_name) adding DUPLICATE left outer join with tab2 to django query as it have .annotate(x_count=Count('tab2'))
View class AppliancePoolViewSet(VneCommonViewSet): serializer_class = vne_serializers.AppliancePoolSerializer search_fields = ('pk', 'name', 'notes', 'appliances__name') # filter appliance pools by customer def get_queryset(self): customer = getattr(self.request.user, 'customer', None) if not customer: return models.AppliancePool.objects.none() return models.AppliancePool.objects.filter( customer=1).prefetch_related('appliances' ).annotate(appliance_count=Count('appliances')) First it is adding join for annotate, and later search_field is also adding the same join again as it have field 'appliances__name', which is causing incorrect data for appliance_count. How can I restrict addition of duplicate join which is done by Django filters using search_fields attribute? -
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