Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Object of type JSON non serializable django REST Framwork
Hi guys I am having the error Object of type 'MyUser' is not JSON serializable, I checke on many post that has the same issue but nothing seems to make my code work Could someone help me please ? in my views: class TeamChartData(APIView): queryset = MyUser.objects.all() serializer_class = MyUserSerializer permission_classes = [] http_method_names = ['get',] def get_serializer_class(self): return self.serializer_class def get(self, request, format=None, *args, **kwargs): chunk_team = get_chunk_team(self) data = { "chunk_team":chunk_team } return Response(data) serializer.py : from rest_framework.serializers import ModelSerializer from rest_framework import serializers from registration.models import MyUser from website.models import Team,Project from survey.models import Response class MyUserSerializer(ModelSerializer): team = serializers.SerializerMethodField() class Meta: model = MyUser fields = ( 'email', 'first_name', 'last_name', 'team', ) def get_team(self, obj): #print(obj) # for you to understand what's happening teams = Team.objects.filter(members=obj) serialized_teams = TeamSerializer(teams,many=True) return serialized_teams.data class TeamSerializer(ModelSerializer): class Meta: model = Team fields = ( 'team_name', 'team_hr_admin', 'members', ) -
django 1.11 raise forms.validationError not showing the error in html
I've tried looking around for solutions on how to check if a form's name is already existing in the database. I used this link to figure out how, and it is indeed not allowing duplicate names to be entered. But where I expected one, I did not get an error message. I'm not sure what I'm doing wrong here, so if anyone can tell me what I should do, that would be really useful! addgame.html: <form method="POST" class="post-form" enctype="multipart/form-data"> {% csrf_token %} {% if form.non_field_errors %} {% for error in form.non_field_errors %} {{ error }} {% endfor %} {% endif %} <div class="form-group"> {{ form.name.label_tag }} {% render_field form.name class="form-control" %} <br> {{ form.genre.label_tag }} {% render_field form.genre class="form-control" %} <br> {{ form.image.label_tag }} {{ form.image }} </div> <hr> <button type="submit" class="save btn btn-primary">Save</button> </form> views.py: def addgame(request): if request.method == "POST": form = InfoForm(request.POST, request.FILES) if form.is_valid(): infolist = form.save(commit=False) infolist.created_date = timezone.now() infolist.save() return redirect('index') else: form = InfoForm() return render(request, 'ranking/addgame.html', {'form': form}) forms.py: class InfoForm(forms.ModelForm): class Meta: model = GameInfo fields = ('name', 'image', 'genre') def clean_name(self): name = self.cleaned_data['name'] try: match = GameInfo.objects.get(name=name) except GameInfo.DoesNotExist: return name raise forms.ValidationError('This game has already been added to … -
How to redirect url with added url parameters
I have a workout calendar app where if a user goes to /workoutcal/, I want them to be redirected to workoutcal/<today's year>/<today's month> so that this route will send their request to the correct view: url(r'^(?P<year>[0-9]+)/(?P<month>[1-9]|1[0-2])$', views.calendar, name='calendar'), So how can I write a new url pattern in urls.py that does something like: url(r'^$', RedirectView().as_view(url=reverse_lazy(),todays_year, todays_month)), -
How to get the type of a class property in python
I have a Python class with different attributes but I do not seem to find how to get the type of each of them. I want to check whether if a given attribute has an specific type. Be aware that I am talking about the class and not an instance. Let's say that I have this class: class SvnProject(models.Model): ''' SVN Projects model ''' shortname = models.CharField( verbose_name='Repository name', help_text='An unique ID for the SVN repository.', max_length=256, primary_key=True, error_messages={'unique':'Repository with this name already exists.'}, ) How can I check whether shortname is a model.CharField or a model.Whatever? -
Django admin disable foreign key drop down but keep add button next to it
I want the dropdown for particluar foreign key to be disabled,but want the "plus" button intact.so that in admin a user can only add the value but cannot edit or select from the list. -
Celery Database Backend Missing connection string! Do you have the database_url setting set to a real value?
After upgrading to Celery 4.1.0 I got this error. While running my Django app. Missing connection string! Do you have the database_url setting set to a real value? -
Python Dictionary Update method not doing as I expect
I bumped into this method while trying to see how django BaseContext works. def flatten(self): """ Return self.dicts as one dictionary. """ flat = {} for d in self.dicts: flat.update(d) return flat When I try to recreate the method on my own like this A = { 'c':1,'d':2,'a':3,'b':4 } B = { 'b':2,'a':1,'d':4,'c':3 } flat = {} for x in A: flat.update(x) print(flat) I am getting a ValueError: dictionary update sequence element #0 has length 1; 2 is required From the dictionary update documentation it says the method accepts either another dictionary object or an iterable of key/value pairs. What am I not getting right since I think I am passing in a dictionary to the method?? -
PDFkit - different page size on production machine
I have a Django project in which I generate PDF from HTML with PDFkit. On my local machine I see the pdf just fine but on production machine the generated pdf page is a little bigger. The html is correct and identical on both machines. The OSes are the same (ubuntu 14.04). Checked all the packages versions and they are the same. My pdf generating code is: options = {'page-size': 'A2', 'margin-top': '0in', 'margin-right': '0in', 'margin-bottom': '0in', 'margin-left': '0in'} pdf_location = '/...../executive_summary.pdf' pdfkit.from_string(my_template.render(context_dict), pdf_location, options=options, css='/....../executive_summary.css') wkhtmltopdf is the latest pdfkit==0.6.1 The screenshots are attached. Where else can be the problem? -
virtualenvwrapper - environment variables are not saving
I have a problem with virtualenvwrapper on ubuntu. I'm working on simple Django project foo. I've decided to move SECRET_KEY from settings.py and save it as environment variable. Everything went well: In bash I've entered export SECRET_KET=['...'] In settings.py I've entered: SECRET_KEY = os.environ['SECRET_KEY'] Also I tested that app is working and everything was ok. BUT After I've started working on project once again using workon foo command in bash and I've tried to simply run server with python manage.py runserver and the SECRET_KEY is not working. The error I get is: ... SECRET_KEY = os.environ['SECRET_KEY'] File "/home/user/.virtualenvs/foo/lib/python3.6/os.py", line 669, in __getitem__ raise KeyError(key) from None KeyError: 'SECRET_KEY' I've read that this variable should be set in postactivate file in .virtualenvs/foo/bin/, but there is nothing there. Fortunately it was just simple test project, but how can I be sure that environment variable will be saved in my next virtualenv when using virtualenvwrapper? -
Django custom manager`s method that changes data works incorrectly with other maager`s methods (filter, get, etc.)
I have created a custom Manager, but in my case its method adds some string to the end of particular field in a model instead of just filtering queryset as in usual cases. My goal is to return already changed objects when calling SomeModel.objects. Django`s documentation says: You can override a Manager’s base QuerySet by overriding the Manager.get_queryset() method. get_queryset() should return a QuerySet with the properties you require. My approach works, when I call SomeModel.objects.all(), but if I apply some filter for objects or just after .all() I can see that data become just regular. models.py: class BaseModelQuerySet(models.QuerySet): def edit_desc(self, string): if self.exists(): for obj in self: if 'description' in obj.__dict__: obj.__dict__['description'] += string return self class BaseModelManager(models.Manager): def get_queryset(self): return BaseModelQuerySet(self.model, using=self._db).edit_desc('...extra text') class BaseModel(models.Model): objects = BaseModelManager() class Meta: abstract = True Shell output: >>> Macro.objects.all()[0].description 'Test text...extra text' >>> Macro.objects.all().filter(id=1)[0].description 'Test text' That makes me confused. Such impression that other methods calling regular queryset instead of one returned with custom objects. I`m looking forward for any help and thanks in advance! -
Python:django: TypeError: __init__() missing 1 required positional argument: 'on_delete'
from django.db import models class Topic(models.Model): text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def _str_(self): return self.text class Entry(models.Model): topic = models.ForeignKey(Topic) text = models.TextField date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural= 'entries' def _str_(self): return self.text[:50]+"..." This is my code,When i run: python3 manage.py makemigrations learning_logs The answer is : TypeError: __init__() missing 1 required positional argument: 'on_delete' WHY THIS WARNING ? I read the documentation. But this problem doesn't sovled . -
Cannot assign "(<VlanedIPv4Network: 103.35.203.6/31>,)": "IPv4Manage.vlanedipv4network" must be a "VlanedIPv4Network" instance
I have a IPv4Manage model: class IPv4Manage(models.Model): ... vlanedipv4network = models.ForeignKey( to=VlanedIPv4Network, related_name="ipv4s", on_delete=models.DO_NOTHING, null=True) And when I update the ipv4 instance: vlaned_ipv4_network = VlanedIPv4Network.objects.create( network_ip = ip_network_divided_obj.network_address.exploded, prefix = ip_network_divided_obj.prefixlen, gateway_ip = gateway_ip.exploded, broadcast_ip = ip_network_divided_obj.broadcast_address.exploded, ipv4networkmanage = vlanable_ipv4network.ipv4networkmanage, ) ... ipv4 = IPv4Manage.objects.get(ip=ip) ipv4.netmask = bits_to_mask(ip_network_divided_obj.prefixlen) if ipv4.ip == gateway_ip: ipv4.is_gateway = True else: ipv4.is_gateway = False ipv4.ip_status = IPV4_STATUS.已Vlan化未配置服务器 ipv4.vlanedipv4network = vlaned_ipv4_network, # there comes the issue ipv4.save() Cannot assign "(<VlanedIPv4Network: 103.35.203.6/31>,)": "IPv4Manage.vlanedipv4network" must be a "VlanedIPv4Network" instance. But my vlaned_ipv4_network exactly is VlanedIPv4Network instance. -
Django regex in url patterns
Is there any difference to use [0-9]+ vs d+ in django url patterns? Any security difference? -
Django/Python register page
I'm making a register page for my django website, but it pretty messy to me, I'm pretty sure the bullet points and the additional information is not supposed to show up right away. How can I make this register page look cleaner? Ie. just the username, password, and confirmation textbox, rather than all the messages. Thanks! Register.html <h2>Sign up</h2> <br> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign up</button> </form> Register view def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('index') else: form = UserCreationForm() return render(request, 'todo/register.html', {'form': form}) -
Build m2m relationship for parents to children and siblings
To describe my problem let's assume there is a model class Person: class Person(models.Model): name = models.CharField(max_length=100, unique=True) sex = models.CharField( max_length=1, choices=( ('F', 'female'), ('M', 'male') ) ) relatives = models.ManyToManyField('self', blank=True) def __str__(self): return self.name A person can have many (or none) relatives of these types: parents children siblings halfsiblings (maternal or paternal) In order to describe the relationship type we need another model class and the option through, which in this case will require also the option symmetrical=False. The relation parent-child is indeed asymmetrical, however the siblings relation is symmetrical. I'm looking for an elegant and clear solution to overcome the dilemma between the true symmetrical relation of siblings and the asymmetrical relation of parents and children. Adapting the field relatives and adding additional model class results in: class Person(models.Model): # ... relatives = models.ManyToManyField( 'self', through='Relatedness', symmetrical=False, blank=True ) class Relatedness(models.Model): RELATIONSHIPS = ( ('PA', 'parent'), ('SI', 'sibling'), ('MH', 'maternal halfsibling'), ('PH', 'paternal halfsibling'), ) source = models.ForeignKey('Person', related_name='source') target = models.ForeignKey('Person', related_name='target') relationship = models.CharField(max_length=2, choices=RELATIONSHIPS) class Meta: unique_together = ('source', 'target') What I need is: to show all relatives for a person to implement constraints that there are no weird combinations like if A … -
How to verify auth key of another API in my Api?
I have made an Django API(1), which calls another API(2) for data. Problem I am facing is that other API(2) use HMAC auth, so when logged in that API(2), I am getting the result but using the same app(1) in other browser { "message": "Unauthorized", "success": false } this message is coming. I know I need to put the auth key of API(2) somewhere in my views.py(1) file and currently I am doing this, def search(request): auth = HmacAuth('Username', 'mySEcretKey') response = requests.get('https://api(2).com/api/get_nearest', auth=auth, params=dict(token='imatinib')) print json.dumps(response.json(), indent=4) which is obviously not working. -
Django and multiple joins
I'm trying to do a quite long join, but it seems like django can't handle the last layer. Am I getting it wrong or is there any way around this? Models.py class A(models.Model): object_id = models.IntegerField(primary_key=True) name = models.CharField(max_length=50) class B(models.Model): class_A_object = models.ForeignKey(A, on_delete=models.PROTECT) value = models.CharField(max_length=50) class C(models.Model): class_B_object = models.ForeignKey(B, on_delete=models.PROTECT) class D(models.Model): value= models.IntegerField(primary_key=True) class_C_object = models.ForeignKey(C, on_delete=models.PROTECT) I'm then trying to select the value in class D when the related class A object name = ABC. D.objects.filter(class_C_object__class_B_object__class_A_object__name='ABC') This fails, to begin with pycharm refuses the autocomplete it and if I run it i get a name not defined error. However, if i drop one layer it works. D.objects.filter(class_C_object__class_B_object__value='ABC') I haven't found any documentation mentioning a maximum number of joins, but it feels like there is a limitation here. Does anyone know if that's the case, and if so, what the best way would be to work around this? The database is external to me and can not be modified. The only working decent workaround i have at the moment is to use the cursor directly and write the sql by hand. However, this is not ideal for a lot of reasons. Any help would be … -
In Reportlab Using SimpleDocTemplate how to add image on top
How to use SimpleDocTemplate for add image on top in pdf. Becuase i try some solutions but not effect on pdf from PIL import Image from reportlab.pdfgen import canvas from reportlab.lib import colors from reportlab.lib.pagesizes import letter, A4, inch,landscape from reportlab.platypus import Image, Paragraph, SimpleDocTemplate, Table, TableStyle from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes import A4 response = HttpResponse(content_type='"application/pdf"') response['Content-Disposition'] = 'attachment; filename=users.pdf' doc = SimpleDocTemplate(response, pagesize=(1600, 500),rightMargin=72,leftMargin=72, topMargin=72,bottomMargin=18) self.canv.drawImage(self.img, 0, 0, height = -2*inch, width=4*inch) # http://www.reportlab.com/apis/reportlab/2.4/pdfgen.html doc = SimpleDocTemplate(("report.pdf"),pagesize=letter, rightMargin=72,leftMargin=72, topMargin=72,bottomMargin=18) all_data = [] record_for_frontEnd = BillManagement.objects.filter(**kwargs) pdf_data = [['Creation Date', 'Bill Number', 'Name', 'Quantity', 'Product/Service Name', "Ref No", "Cost", "discounted Price", "Net Amount", "Costomer Name", "Commission Staff", "Commission Amount", "Patyment Type"]] -
Python/Django: How to display error messages on invalid login?
I'm trying to do the Login for my Django (2.0) website, so far I've got the login working for existing accounts. I'm using the built-in login function. Now I want to display an error message when you enter an invalid account, for example "Invalid username or password!". But I have no idea how to go about this. Right now it just refreshes the login page when your enter an invalid account. Any help is appreciated! Login.html {% block title %}Login{% endblock %} {% block content %} <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> {% endblock %} Login view def login(request): if request.method == 'POST': form = AuthenticationForm(request.POST) username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: auth_login(request, user) return redirect('index') else: form = AuthenticationForm() return render(request, 'todo/login.html', {'form': form}) -
How do I download a file from a FIleField in Django?
Using Django, I have uploaded files to a FileField. Is there a way to retrieve the file from this field, and download it in the original form back to my PC using a Python Script. This is the model for the item: class CatalogueItemData(VendorCustomerRestrictedPermissionMixin, OrnamentationBase, SoftDeleteObject): """ Represents Data belonging to an Item (CatalogueItem). """ url = models.FileField(upload_to=get_item_data_file_path, null=True, blank=True, validators=[validate_is_not_jpeg_extension], help_text='Disallowed format: .jpg') name = models.CharField(max_length=60) class Meta: verbose_name = 'Catalogue Item Data' verbose_name_plural = 'Catalogue Item Data' def __str__(self): return self.name def get_file_name(self): """ Returns the name of the uploaded file. """ name = self.raw.name return name.strip('category/item-data') I have the ID for the data, I want to download the file stored in the file field. I do not want to modify the model. -
djang - 404 error for only one css file
I have this in my base.html template: {%load staticfiles%} <link rel="stylesheet" type="text/css" href="{% static 'css/bulma.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/app.css' %}"> And this is what I get in console when navigating on the page. [21/Dec/2017 12:52:04] "GET / HTTP/1.1" 200 1134 [21/Dec/2017 12:52:04] "GET /static/css/bulma.css HTTP/1.1" 304 0 [21/Dec/2017 12:52:04] "GET /static/css/app.css HTTP/1.1" 404 1758 So the app.css doesn't load and I don't understand why because it is in the same folder ar bulma.css which as I see loads fine. urls.py from django.contrib import admin from django.urls import include, path from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf import settings urlpatterns = [ path('', include('homepage.urls')), path(r'hap/', admin.site.urls), path(r'martor/', include('martor.urls')), ] urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns += staticfiles_urlpatterns() settings.py STATIC_URL = '/static/' STATIC_ROOT = './static/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django.contrib.staticfiles.finders.FileSystemFinder', ) -
Apache Django app: ImportError: No module named django.core.wsgi
I installed mod_wsgi, and loaded it in apache. This is my apache virtual host: <VirtualHost *:80> ServerName mysite.localhost ServerAlias mysite.localhost Alias /static /var/www/mysite/static <Directory /var/www/mysite/static> Require all granted </Directory> <Directory /var/www/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mysite WSGIProcessGroup mysite WSGIScriptAlias / /var/www/mysite/mysite/wsgi.py </VirtualHost> When I go to mysite.localhost I get: ImportError: No module named django.core.wsgi I try to run it from python shell and everything goes well. I have django installed globally, not just in the virtualenv. Thanks. -
django-celery-beat not sending tasks to celery worker
I was using celery only in django first. This was my config, from __future__ import absolute_import import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'inventory.settings') app = Celery('inventory') app.config_from_object('django.conf:settings', namespace='CELERY') #app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.autodiscover_tasks() app.conf.beat_schedule = { 'send-report-every-single-minute': { 'task': 'db.tasks.send_daily_report', 'schedule': crontab(minute='*/1'), }, } And I ran celery worker and beat and the task worked. celery -A inventory worker -l info celery -A inventory beat -l info But now, I am using the package, django-celery-beat. I added the schedule in the django admin panel, and enabled the same task. But it does not send the task to the celery worker. The worker keeps on waiting. It is stuck on starting, Neither does it show the task scheduled when I run the beat manually, $ celery -A inventory beat -l debug [2017-12-21 16:10:48,471: INFO/MainProcess] beat: Starting... [2017-12-21 16:10:48,527: DEBUG/MainProcess] Current schedule: [2017-12-21 16:10:48,527: DEBUG/MainProcess] beat: Ticking with max interval->5.00 minutes [2017-12-21 16:10:48,528: DEBUG/MainProcess] beat: Waking up in 5.00 minutes. See, below Current Schedule line, it shows nothing but an empty line. It happens only when I add task schedule through django admin panel. -
About django rest framework document, how custom the description of request params and add the field to post params?
In the auto-generate view by rest_framework.documentation,when I take the post test, there is no field to fill my params, and how to add the description of request params like the api of "delete>list"? I can not get the ideas from the document:Documenting your API Should I write some code at here? @api_view(['POST']) def Login(request): try: username=request.data['username'] password=request.data['password'] except Exception as error: return Response(str(error), status=status.HTTP_400_BAD_REQUEST) user = authenticate(username=username, password=password) if user is None: or : from django.conf.urls import url, include from django.contrib import admin from . import views from rest_framework.documentation import include_docs_urls urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^media/(?P<file_path>.*)', views.GetMediaFiles), url(r'^api/',include('api.urls')), url(r'^docs/', include_docs_urls(title='CLTools API Docs')), ] Thanks! -
Django Crispy Form doesn't render hidden fields in formsets
I'm using django crispy forms to create inline formsets using a model form and a helper class. In my template, If I do {% crispy entrance_formset entrance_helper %} everything works fine when I submit. But if I try to manually render each form in the entrance_formset like this: {{ entrance_formset.management_form|crispy }} {% for entrance_form in entrance_formset %} {% crispy entrance_form entrance_helper %} {% endfor %} I get the following error when submitting. django.utils.datastructures.MultiValueDictKeyError: "'entrances-0-id'" When I look at the html, I see that the hidden fields entrances-0-idand entrances-1-id are indeed missing. What am I doing wrong? form class: class EntranceForm(ModelForm): latitude = FloatField( min_value=-90, max_value=90, required=False, ) longitude = FloatField( min_value=-180, max_value=180, required=False, ) class Meta: fields = ['name', 'location', 'latitude', 'longitude', 'directions'] widgets = { 'location': HiddenInput, 'directions': Textarea(attrs={'rows': 5}) } def __init__(self, *args, **kwargs): super(EntranceForm, self).__init__(*args, **kwargs) coordinates = self.initial.get('location', None) if isinstance(coordinates, Point): self.initial['latitude'], self.initial['longitude'] = coordinates.tuple def clean(self): data = super(EntranceForm, self).clean() latitude = data.get('latitude') longitude = data.get('longitude') point = data.get('location') if latitude and longitude: data['location'] = Point(latitude, longitude) helper class: class EntranceFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super(EntranceFormSetHelper, self).__init__(*args, **kwargs) self.layout = Layout( 'name', 'latitude', 'longitude', 'directions', ) self.form_class = 'form-horizontal' self.label_class = 'col-xs-4' self.field_class = …