Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Generate PDF from HTML UTF-8 DJANGO
I need to generate a PDF from HTML in Django. I went through a lot of solutions both on server side (xhtml2pdf, reportlab) and the client (jsPDF, etc.) All have one problem - the incorrect output of Cyrillic. Can someone advice the solution is relevant at the moment? Or give an example of how to make a picture from a template and then put in pdf? -
Django - NoReverseMatch Error when using named URL with parameter
I'm trying to build this link using a named URL with a parameter: http://127.0.0.1:8000/wakemeup/admin/list/colegio The parameter is the string after .../list/ (in this case "colegio"). I have a print() statement in the admin_list view, which shows the parameter is getting extracted correctly. However, when I try to build the URL: <a href="{% url 'wakemeup:admin_list' list_type=colegio %}">Colegios</a> I get this error: NoReverseMatch at /wakemeup/admin/list/colegio Reverse for 'admin_list' with keyword arguments '{'list_type': ''}' not found. 1 pattern(s) tried: ['wakemeup/admin/list/(?P<list_type>\\w+)$'] Request Method: GET Request URL: http://127.0.0.1:8000/wakemeup/admin/list/colegio Django Version: 2.0.1 Exception Type: NoReverseMatch Exception Value: Reverse for 'admin_list' with keyword arguments '{'list_type': ''}' not found. 1 pattern(s) tried: ['wakemeup/admin/list/(?P<list_type>\\w+)$'] views.py def admin_list(request, list_type): print(list_type) return index(request) urls.py url(r'^admin/list/(?P<list_type>\w+)$', views.admin_list, name="admin_list"), I also tried using an unnamed parameter, but no dice. Can someone please help me out? Thanks. -
bokeh plot graph horizontally
I'm plotting graph as script, div = components(p) return render(request, 'index.html', {"the_script": script, "the_div": div}) And in index.html I have <body> <div> {{the_script | safe}} {{the_div | safe}} </div> </body> Now I'm trying to plot 2 graphs horizontally I see option to use such as components(p1, p2) and I added another div tag underneath current one. But it plots graph vertically how can I plot them horizontally. -
can't import models from django custom seed command
I have a django 2.0.6 project running on python 3.6. I'd like to create a manage.py command that that seeds the project database with initial data using faker and factory_boy. I have the subcommand working. and printing to std. out. When I try to import the models I get the following error RuntimeError: Model class cb3p.events.model_utils.Link doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. The models are fine, however: python manage.py makemigrations works, the app works. Moving the models into the same app as the project doesn't help. Stripping the models down to the point where they only contain a single table with 1 field doesn't help. Moving the import inside the commands handle method doesn't help. -
I wanna add my save in django-moderation
im using django=1.11 and python 3.6 I have a model in models.py.(using django-moderation) I would like to add if it is authorized as a moderator. 2. the same situation with rejection. The second thing I would like to add to the person who was editing or adding got. Which moderating person automatically (automatic approval) class Book(ModeratedModel): title = models.CharField(max_length=191) type = models.CharField(max_length=30,choices=TYPE, blank=True, default='', null=True) status= models.CharField(max_length=30, choices=STATUS, blank=True, default='', null=True) date_start = models.DateField(blank=True, null=True) data_end = models.DateField(blank=True, null=True) age_restrictions = models.ForeignKey(OgraniczenieWiekowe, null=True, default='', blank=True) volumes = models.SmallIntegerField(null=True, blank=True, default=0) chapter = models.SmallIntegerField(null=True, blank=True, default=0) -
Django refuses to save the date shown on django-bootstrap-datepicker-plus?
In my Django (1.11.5) project I use django-bootstrap-datepicker-plus application for DateField in Profile model. When user submit form nothing happens and I don't understand why Django refuses to save the date shown on form. How to fix it? models.py: class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) birth_date = models.DateField(blank=False) forms.py: # "django-user-accounts" application from account.forms import SignupForm as BaseSignupForm # "django-bootstrap-datepicker-plus" application from bootstrap_datepicker_plus import DatePickerInput class SignupForm(BaseSignupForm): birth_date = forms.DateField(widget=DatePickerInput()) views.py: # django-user-accounts application from account.views import SignupView as BaseSignupView class SignupView(BaseSignupView): form_class = SignupForm def generate_username(self, form): pass def after_signup(self, form): self.create_profile(form) super(SignupView, self).after_signup(form) def create_profile(self, form): profile = self.created_user.profile profile.birth_date = form.cleaned_data["birth_date"] profile.save() -
Securely use Blockly generated code
i'm using Google Blockly plugin in order to make easy the building of some logical blocks, rules, etc... Blockly, has the capability to generate python code directly from the blocks positioned into the canvas: DEMO Now, i've integrated Blockly to my django web application, and i'm wondering if it's a good approach, that permits me to use the generated python code SAFELY into my web application, preventing malicious code injection directly to my webserver. Any suggestion? Thanks. -
bokeh pass slider layout to components
I'm using bokeh components to get script, div and pass to template script, div = components(p) return render(request, 'index.html', {"the_script": script, "the_div": div}) I'm trying to add date slider something like date_range_slider = DateRangeSlider(title="Date Range: ", start=date(2017, 1, 1), end=date.today(), value=(date(2017, 9, 7), date(2017, 10, 15)), step=1) layout = row(p, date_range_slider) But how do I pass layout to components or script or div -
Incorrect type. Expected pk value, received dict. - Django REST
I'm new with Django Rest, I'm having trouble saving my data, I get "Incorrect type. Expected pk value, received dict", do I have to convert the dictionary into a list? Company Profile Model: class CompanyProfile(models.Model): name = models.CharField(_('nombre'), max_length=255, db_index=True) email = models.EmailField(_('email de contacto'), max_length=255, blank=True) description = HTMLField(_('descripción'), blank=True) countries = models.ManyToManyField('countries.Country', blank=True, related_name='countries') Country Model: class Country(models.Model): name = models.CharField(_('nombre'), max_length=255) description = HTMLField(_('descripción'), blank=True) Serializers: class CompanyWriteSerializer(serializers.ModelSerializer): countries_id = serializers.PrimaryKeyRelatedField(queryset=Country.objects.all(), write_only=True, many=True) def create(self, validated_data): countries = validated_data.pop('countries_id') company = CompanyProfile.objects.register_company(**validated_data, country=self.context['request'].user.country.id) for c in countries: print(c) company.countries.add(c) return company def update(self, instance, validated_data): instance.countries = validated_data.get('countries_id', instance.countries) instance.save() return instance class Meta: model = CompanyProfile fields = ('countries_id', 'countries') -
Change default django error messages for AuthenticationForm
I currently use this alternative AuthenticationForm: class AuthenticationForm(AuthenticationForm): username = forms.CharField(widget=forms.HiddenInput(), initial="members") def confirm_login_allowed(self, user): pass def __init__(self, *args, **kwargs): super(AuthenticationForm, self).__init__(*args, **kwargs) self.fields['password'].error_messages = {'incomplete': 'Please enter a valid password.'} for field in self.fields.values(): field.error_messages = {'required':'T {fieldname} is required'.format( fieldname=field.label)} Some of this code is useless, but I'm trying to change the error message for when the user enters an incorrect password. Currently, django supplies the error message: Please enter a correct username and password. Note that both fields may be case-sensitive., though I would like it to be Please enter the correct password. This is an edge case, I suppose. Thanks for any help. -
is it possible to send a model or list using cookies in django?
I would like to know if it possible to send a model or a list using django. I know that doing this is certainly not the best way. But I need to now. I'm trying to do this def article(request): articles = Article.objects.all() response = render(request, 'someHtml.html',{'articles': articles}) if request.POST: response.set_cookie('articles', articles) return response but doing this way the model article turns string and I would like a django model, like a bellow. def another_fuction_view(request): if 'articles' in request.COOKIES['articles']: articles = request.COOKIES['articles'] else: articles = ['not exists'] return render(request, 'anotherview.html', {'articles': articles}) I hope my arm does not fall because of it heuheuhe -
How to have Nginx to proxy pass only on "/" location and serve index.html on the rest
I have a web app that uses Django for the backend and some frontend and ReactJS for stricly the frontend. I am setting up my Nginx configuration and I am trying to get Nginx to proxy_pass only on the "/" location and then on the rest of the locations I want it to serve the index.html file from React. Here is my current Nginx configuration under sites-available. So the only url that does not have the prefix "/home/" or "/app/" is the homepage. I want Django to serve the homepage and then ReactJS to serve the rest. server { listen 80; root /home/route/to/my/ReactJS/build; server_name www.mydomain.com; location = /favicon.ico { log_not_found off; } location / { include proxy_params; proxy_pass http://0.0.0.0:8000; } location /home/ { try_files $uri $uri/ /index.html; } location /app/ { try_files $uri $uri/ /index.html; } } Let me know if you need any more details or if I could clear things up. Thanks! -
Error POST request on Django Rest Framework (auth_user.username)
I try to create a new user (django user) via POST with serializers.py from rest_framework import serializers from .models import * from django.contrib.auth.models import User class UsuarioSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('email', 'password') views.py: class Registrar(mixins.CreateModelMixin, viewsets.GenericViewSet): serializer_class = UsuarioSerializer urls.py: from django.urls import path, include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register('usuarios', views.UsuarioViewSet) router.register('tecnicos', views.TecnicoViewSet) router.register('pedidos', views.PedidoViewSet) router.register('mispedidos', views.PedidoMiUsuarioSet) router.register('registrar', views.Registrar, base_name = 'registro') urlpatterns = [ path('', include(router.urls)) ] When i make a post i get this error: UNIQUE constraint failed: auth_user.username This works if i change the model User to Usuario... Models.py: class Usuario(models.Model): email = models.EmailField(max_length=70, blank=True, null=True, unique=True) password = models.TextField() def __str__(self): return self.email But i need to use the User model from django -
Django - preset foreign key value in form field
I'm struggling to figure this out and hoping someone here can help me. I have a model, called "Team", which has a ForeignKey field that corresponds to the page I'm showing the ModelForm on ("Department"). Since it's on the page I want to set the ForeignKey in the backend (View or Form) rather than have the user select it. Following others examples I set it up so the value would be added in the form portion, but when I submit the form I get the following error (followed by the request.POST print out) in the terminal: <ul class="errorlist"><li>Department<ul class="errorlist"><li>This field is required.</li></ul></li></ul> <QueryDict: {'csrfmiddlewaretoken': ['KeEJF7KFr6l9dbkmZWA7u4Qg3eKqqFGcB2qq2AIEmilLP87AySi60ig3hJl6TBS0'], 'title': ['test'], 'description': [''], 'events': [''], 'current_status': [''], 'notes': [''], 'impact': [''], 'timeliness': [''], 'likelihood': [''], 'risk': [''], 'summary': [''], 'documents': ['']}> FORM: class GroupFormCreate(forms.ModelForm): Department = forms.HiddenInput() title = forms.CharField(label="Team Title", required=True) description = forms.CharField(label="Description", widget=forms.Textarea, required=False) events = forms.CharField(label="Events", widget=forms.Textarea, required=False) current_status = forms.CharField(label="Current Status", widget=forms.Textarea, required=False) notes = forms.CharField(label="Notes", widget=forms.Textarea, required=False) RATING_CHOICES = [(x, x) for x in range(1, 6)] RATING_CHOICES_PLUS_BLANK = tuple(BLANK_CHOICE_DASH + list(RATING_CHOICES)) impact = forms.ChoiceField(choices=RATING_CHOICES_PLUS_BLANK, label="Impact", widget=forms.Select(), required=False) timeliness = forms.ChoiceField(choices=RATING_CHOICES_PLUS_BLANK, label="Timeliness", widget=forms.Select(), required=False) likelihood = forms.ChoiceField(choices=RATING_CHOICES_PLUS_BLANK, label="Likelihood", widget=forms.Select(), required=False) risk = forms.ChoiceField(choices=RATING_CHOICES_PLUS_BLANK, label="Risk", widget=forms.Select(), required=False) summary = forms.FileField(label="Summary … -
Update view uses methods from CreateView Django
thanks beforehand I have a problem where i have this code. view.py class CompetitionCreate(CreateView): model = Competitions form_class = CompeForm template_name = 'courses/addCompe.html' def get_success_url(self): return reverse('designCourses', kwargs={'id' : self.kwargs['id']}) def get_initial(self): return { 'Courses': self.kwargs['id']} class CompetitionUpdate(UpdateView): model = Competitions form_class = CompeUpdate template_name = 'Courses/addCompe.html' def get_success_url(self): return reverse('designCourses', kwargs={'id' : Competitions.objects.values_list('Courses_id', flat= True).get(pk= self.kwargs['id'])}) def get_initial(self): return {'Competition': str(Competitions.objects.values_list('Competition', flat= True).get(pk= self.kwargs['id'])), 'Courses': Competitions.objects.values_list('Courses_id', flat= True).get(pk= self.kwargs['id'])} each have a diferent form, but anyhow the CompetitionUpdate(UpdateView) always calls the get_inital y get_success_url from CompetitionCreate(CreateView). if a i remove the one in CreateView it doesn't even call it. forms.py class CompeForm(forms.ModelForm): class Meta: model = Competitions fields = ['Competition', 'Courses'] Competitions = forms.Field(widget=forms.Textarea(attrs={'class': 'form-control'}), label= 'Competition') Courses= forms.ModelChoiceField(Courses.objects.all()) class CompeUpdate(forms.ModelForm): class Meta: model = Competitions fields = ['Competition', 'Courses'] Competition = forms.Field(widget=forms.Textarea(attrs={'class': 'form-control'}), label='Competition') Courses= forms.ModelChoiceField(Courses.objects.all()) Courses is a foreingKey of Competition Thanks if you can help me -
Authentication login with legacy database in Django
I am creating a project in Django and I have a database that I would like to use in the project. In the database I have the log_user table where the logins information is stored, but I can not find a way to authenticate other than the Django default table. Can anybody help me ? -
GCP VM Django proyect with Docker, can't access
I'm running a Django proyect on a GCP VM instance, My Dockerfile is: FROM python:3.5 RUN apt-get update USER root WORKDIR /app ADD . /app RUN pip install -r requirements.txt WORKDIR /app/etalentNET EXPOSE 8000 CMD ["python", "manage.py", "makemigrations"] CMD ["python", "manage.py", "migrate"] CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] My doker-compose.yaml is: version: '3' services: db: image: sqlite3 web: build: image: demo:latest dockerfile: Dockerfile command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db When I run docker run -p 8000:8000 demo it doesn't shows anything but the containers its up. CONTAINER ID IMAGE COMMAND STATUS PORT ef4585c1e580 demo "python ma…" Up 12 hours 0.0.0.0:8000->8000/tcp I try to access it via <host_ip>:8000 but it doens't ERR_CONNECTION_TIMED_OUT I'm running in a GoogleCloud Machine with Ubuntu 16.04, and Django-2.0.6. -
Make a model field choose from a database of users
So, I'm making an item checkout app for our internal group. So, my django app has a model of an item, with one of the fields being "lonedTo". We have a database of users in the building, and I would like to set the choices field of this "loanedTo" field to take values from the db. So, when someone checks out an item, he can select from a list of users. I can't seem to find how to do this exactly? On here, https://docs.djangoproject.com/en/2.0/ref/models/fields/, the choices field can be set to an iterable list or tuple. -
Store image in server to imagefield django
I have an image in folder in server based on id of the django model object with image field. Now, when i want to copy the object i.e. create the object with same details, i need to copy the image also in new folder with new id. I can do copy folder in python, but what i wanna do is to create a new object with the same info, i have image field upload to function which takes care of path based on id. I just need the image to pass to the create function. How can i pass the image stored in server to imagefield. -
RuntimeError: There is no current event loop in thread 'Dummy-1'
Hello i am working on a web application with a backend in python and a Django server. I have a few raspberry pis which are sending datas to a server and then i am supposed to get those datas from my backend. So I succeeded to do it out of my project so i am pretty sure about the code. Now i wanna integrate this function to my project so here is the file : loop = asyncio.get_event_loop() class StartApp: def __init__(self, interval=1): self.interval = interval Mqtt = multiprocessing.Process(target = self.runMqtt) loop.run_until_complete(runCoap()) async def runCoap(): print('COUCOU C cOAP') protocol = await Context.create_client_context() requestTemp = Message(code=GET, uri='coap://129.6.60.38/other/sensors/temperature') requestHumidity = Message(code=GET, uri='coap://129.6.60.38/other/sensors/humidity') while True: time.sleep(1) try: responseTemp = await protocol.request(requestTemp).response responseHumidity = await protocol.request(requestHumidity).response except Exception as e: print('Failed to fetch resource:') print(e) else: print('Result: %s\n%r'%(responseTemp.code, responseTemp.payload)) print('Result: %s\n%r'%(responseHumidity.code, responseHumidity.payload)) and i get this error when running my app : Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f55cdc989d8> Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 147, in inner_run handler = self.get_handler(*args, **options) File "/usr/local/lib/python3.5/dist-packages/django/contrib/staticfiles/management/commands/runserver.py", line 28, in get_handler handler = super(Command, self).get_handler(*args, **options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 68, in get_handler return get_internal_wsgi_application() … -
Django Wagtail image not showing on post detail page
I'm trying to work my way through a wagtail tutorial and i'm facing an issue trying to implement images. The images i upload and add to the blog posts are displayed in the post list page but are not showing up in the post detail page. Could anyone let me know what i'm missing right now and if i need to share any additional info. Thanks! I'm using wagtail V2.1 and this is my current code: blog/models.py for the post detail page class: class PostPage(Page): body = RichTextField(blank=True) date = models.DateTimeField(verbose_name='Post date',default=datetime.datetime.today) categories = ParentalManyToManyField('blog.BlogCategory',blank=True) tags = ClusterTaggableManager(through='blog.BlogPageTag',blank=True) header_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) content_panels = Page.content_panels + [ ImageChooserPanel('header_image'), FieldPanel('body', classname="full"), FieldPanel('categories',widget=forms.CheckboxSelectMultiple), FieldPanel('tags'), ] settings_panels = Page.settings_panels + [ FieldPanel('date'), ] @property def blog_page(self): return self.get_parent().specific def get_context(self,request,*args,**kwargs): context = super(PostPage,self).get_context(request,*args,**kwargs) context['blog_page'] = self.blog_page return context blog/templates/blog/post_page.html for the post detail page: The image does not show here {% extends "blog/base.html" %} {% load wagtailcore_tags wagtailimages_tags wagtailroutablepage_tags %} {% block content %} <!-- Post Title --> <h1>{{ page.title }}</h1> <hr> <!-- Post Image --> {% if post.header_image %} {% image post.header_image original as header_image %} <img src="{{ header_image.url }}" class="img-responsive" ></img> {% endif %} <hr> <!-- … -
Float detected as DeferredAttribute
I get>=' not supported between instances of 'DeferredAttribute' and 'float error when using registered_model >= 0.5 or any of comparing symbols I registered model with FloatField(), but for some reason in MySQL it was registered as 'decimal' type, I thought it was the problem so I manually changed it to 'float' type but I still get same error. Django Version: 2.0.6 | Python Version: 3.6.5 -
Is it possible to set edit_handlers in wagtail dynamically?
In Wagtail (2.1), I'd like to show edit_handlers based on the instance of a Page object. Digging in Wagtail, I see that edit_handlers is a classbased function, hence no request or instance object is available. Is this even possible? As far as I know, I can only achieve this by overriding the function based view edit (https://github.com/wagtail/wagtail/blob/master/wagtail/admin/views/pages.py#L311) copying the whole function, and changing the edit_handler assignment here (https://github.com/wagtail/wagtail/blob/master/wagtail/admin/views/pages.py#L329) based on latest_revision. Then I'd have to create a new urls.py that picks up on this overridden edit view for that specific Page type. -
ImportError: cannot import name 'Comment'
Good afternoon. Good a such error today: ImportError: cannot import name 'Comment' The problem happend in my admin.py directory. Here is the full code from django.contrib import admin from .models import Post, Comment # Register your models here. admin.site.register(Post) admin.site.register(Comment) I try to fix the problem by myself or look at the documentation, but i can't find anything. Help please :C -
How to delete data in FlutterUI through JSON?
Basically what I want is to remove a specific data in my Django database. This is how I got the JSON in Flutter: Future<String> getData() async{ http.Response response= await http.get( Uri.encodeFull("192.168.2.107:8000/api/"), headers: { "Accept" : "application/JSON" } ); I just can't figure out how to delete an entry (e.g. "192.168.2.107:8000/api/16"). Something that I've found is this https://docs.flutter.io/flutter/dart-io/HttpClient/delete.html but I don't quite understand what I am supposed to insert. Just if needed my urls.py : url(r'^api/(?P<image_id>\d+)/$', views.get_rest_list,name='api'), url(r'^api/delete/(?P<image_id>\d+)/$', views.delete,name='apiDelete'), I hope I described the issue correctly.