Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to multiply model with different app in django?
to count about multiply model with another model in foreignkey but in different app, here the penjualan app and detail_penjualan_obat model : class detail_penjualan_obat(models.Model): kd_penjualan_detail = models.ForeignKey(penjualan_obat) kd_obat_detail = models.ForeignKey(obat) jumlah_jual = models.IntegerField() total_harga_perobat = MoneyField(max_digits=10, decimal_places=2, default_currency='IDR') def __unicode__(self): return self.total_harga_perobat and the obat app model : class obat(models.Model): jenis_obat = { ('obat bebas','Obat Bebas'), ('obat bebas terbatas','Obat Bebas Terbatas'), ('obat keras dan psikotropika','Obat Keras dan Psikotropika') } kd_obat = models.CharField(primary_key = True, default = '', max_length = 10, validators=[RegexValidator(r'^\d{1,10}$')]) nama_obat = models.CharField(max_length = 15) tipe_obat = models.CharField(max_length = 35, choices = jenis_obat) harga_jual = MoneyField(max_digits=10, decimal_places=2, default_currency='IDR') def __unicode__(self): return self.kd_obat and the view.py : def data_penjualan_obat_detail(request): if request.method == 'POST': form_data = request.POST form = penjualan_detail_form(form_data) if form.is_valid(): input_detail_penjualan = detail_penjualan_obat( kd_penjualan_detail = form.cleaned_data.get('kd_penjualan_detail'), kd_obat_detail = form.cleaned_data.get('kd_obat_detail'), jumlah_jual = request.POST['jumlah_jual'], total_harga_perobat = form.cleaned_data.get('total_harga_perobat') ) input_detail_penjualan.save() return redirect('/') else: form = penjualan_detail_form() return render(request, 'penjualan_detail.html',{'form':form}) here the function : total_harga_perobat = harga_jual * jumlah_jual and that function how to be 'place and work' in the view ? Sorry I have bad english but I hope you will understand what about my question, and solve my problem -
Django: python manage.py runserver Error
As I am applying "python manage.py runserver" in power shell it gives a pop up with "Python is not working " as I have completed all the procedure as from the very beginning of the tutorials but still it was repeating the same crap again and again is this is some kind of a port error or something or the procedure doesn't work with the window 10? -
Validation Exclude Self From QuerySet
Originally I had this in my models.py def validate_project_name(value,self): project_name = Team.objects.filter(Project_name=value) if self.pk: project_name = project_name.exclude(pk=self.pk) if project_name: raise ValidationError('This already exists.') class Team(models.Model): Project_name = models.CharField(max_length=250, validators=[validate_project_name]) Project_number = models.IntegerField() This worked in the sense that it will not allow users to input an already existing Project_name. However, now I have incorporated an edit/update functionality. So if a user wants to update his/her own Team, it will raise the ValidationError since it exists in the database. So for example, if the User wants to keep the same Project_name but update the Project_number the error will raise. So I want to exclude self from the queryset. I looked at this example: django exclude self from queryset for validation So I simply added the following code within my class Team. def clean_name(self): project_name = self.cleaned_data['Project_name'].title() qs = Team.objects.filter(Project_name=project_name) if self.instance.pk is not None: qs = qs.exclude(pk=self.instance.pk) if qs.exists(): raise ValidationError("This already exists") But it is not working as in the validation error is not being raised...Any ideas? -
Cast Django's intcomma string to Decimal
I'm trying to export some records from database with Django but when exported the type of amount field is represented as string and not decimal. My code from django.contrib.humanize.templatetags.humanize import intcomma import django_excel as excel def download(request): records = [] now = datetime.datetime.now() for reservation in Reservation.objects.sifted(request): record['Amount (EUR)'] = intcomma(reservation.amount) records.append(record) return excel.make_response_from_records( records, 'xls', file_name="export_reservations_{}".format(now.strftime('%d_%m_%Y').replace(".",",")) ) Model amount = DecimalField(max_digits=6, decimal_places=2, null=True, default="0.00", verbose_name='Amount') This produces something like 12.12 which is the correct format but it's string. If i do Decimal(intcomma(reservation.amount)), I get decimal type, but the format is 12 with floating points. How can I get decimal with correct format(xx.xx) in the export? -
Creating Views like Django Admin Panel
is there any way to create views like the ones shown on Admin Panel without any effort, I mean, generic views that display all the fields and have the ability to add foreign key items and such, just like admin panel? I've tried using django.views.generic.edit.FormView django.views.generic.edit.CreateView django.views.generic.edit.UpdateView django.views.generic.edit.DeleteView But I am forced to specify fields, and I have quite a lot. It also doesn't allow me to create objects for the foreignkey fields if there's any. Thanks in advance. -
Display of multiple related formset fields in Django
I have a formset that is a simple many-to-many relationship between task and owner where tasks are created and then on the owner page they are assigned using an inline formset. #model.py class Owner(models.Model): name = models.CharField(max_length=30) role = models.CharField(max_length=30) def __str__(self): return self.name class Task(models.Model): name = models.CharField(max_length=40) description = models.CharField(max_length=30) created = models.DateTimeField() owner = models.ManyToManyField(Owner, through='OwnerTask') def __str__(self): return self.name class OwnerTask(models.Model): # table to store which node has which point owner=models.ForeignKey(Owner) task=models.ForeignKey(Task) def __str__(self): return self.owner #form.py OwnerTaskFormSet = inlineformset_factory(Owner, Task.owner.through, fields=('task',), extra=1) Pushing this through the view and template works fine and I get the formset I want. Is there a way to create more fields to this formset that aren't data entry but related display fields. For example {{OwnerTaskFormSet.task}} is the input but {{OwnerTaskFormSet.task.description}} is just a paragraph tag. I'm assuming this needs to be done as a widget in the form but I can't piece it together. Something like OwnerTaskFormSet = inlineformset_factory(Owner, Task.owner.through, form=OwnerTaskForm, extra=1) class OwnerTaskForm(ModelForm): class Meta: model = OwnerTask fields = ( 'task.name', 'task.description') widgets = ........ render task.description as <p>...... I am aware I could do this with the model return so when you select the task you get … -
Delete time from datetime format in django
I need to send an email with a date, and the date should be "mm/dd/yyyy". From the database i get the date in this format: 2017-02-26T23:00:00Z So I added from django.utils import formats along with all the imports and then I also added in my function final_date = formats.date_format(input_date, "SHORT_DATETIME_FORMAT") The thing is that i get exactly what i want with the date, but also the time. Is there any way to get rid of the time within my formatting?? I know i can use the function split(), but that seems an ugly way to achieve this. TL;DR What I have --> 02/20/2017 4:40 p.m. What I want --> 02/20/2017 -
How to format OneToOne Relationship in Django Admin?
I have 2 models that are connected via a OneToOneField Relationship. This is what they look like: class UserText(models.Model): user_input = models.CharField(max_length=2000) class Question(models.Model): user_text = models.OneToOneField( UserText, on_delete=models.CASCADE, blank=True, null=True, ) user_questions = models.CharField(max_length=2000) I would like each UserText to have the Questions model connected to it within the database. This is why I used a OneToOne relationship. From here, I do not know how to represent this relationship within my admin.py so that when I look in my database through the admin I see each UserText model with its connected Question. This is what my admin.py look as of now: from django.contrib import admin from v2.models import UserText from v2.models import Question @admin.register(UserText) class UserTextAdmin(admin.ModelAdmin): model = UserText display = ('user_input') @admin.register(Question) class QuestionAdmin(admin.ModelAdmin): model = Question display = ('user_questions') What do I need to add or change in my admin.py so that every Question model is connected to it's parent UserText model through the OneToOne relationship? -
Translate built-in Django Validation error
How would I go about translating a validation error that is automatically generated by Django? I'm seeing that when a user attempts to add an invalid username, the Validation error is not translated. Is there a way to mark the built-in validation error for translation? My error is currently generated by validating a Form that is generated using the built-in User model. class UserForm(ModelForm): email = forms.CharField(max_length=75, required=True, label=_('Email')) password = forms.CharField( widget=forms.PasswordInput(), label=_('Password')) class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'password', ) -
how to write view with multi relationships model in Django
to make it simple lets assume we have a employer,employee and job relationship. employer request a job and employees bid their request and finally employer accept one my problem is how to write view to interact with employee and employer and how to save model from django.contrib.auth.models import User class Employer(models.Model): user = models.ForeignKey(User) *some other fields* class Employee(models.Model): user = models.ForeignKey(User) *some other fields* class Job(models.Model): employer = models.ForeignKey(Employer) employer = models.ForeignKey(Employee) *some other fields* serializers are (no foreign key included in serializer field) class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('somefields...') class EmployerSerializer(serializers.ModelSerializer): class Meta: model = Employer fields = ('somefields...') class JobSerializer(serializers.ModelSerializer): class Meta: model = Job fields = ('somefields...') -
While running my Django file I am getting this error. Can you please help me in this regard, how can I able to solve this issue?
Traceback (most recent call last): File "manage.py", line 8, in execute_from_command_line(sys.argv) File "/home/srk/Envs/project1/local/lib/python2.7/site-packages/django/core/management/init.py", line 367, in execute_from_command_line utility.execute() File "/home/srk/Envs/project1/local/lib/python2.7/site-packages/django/core/management/init.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/srk/Envs/project1/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) File "/home/srk/Envs/project1/local/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/srk/Envs/project1/local/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/srk/Envs/project1/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 72, in handle failures = test_runner.run_tests(test_labels) File "/home/srk/Envs/project1/local/lib/python2.7/site-packages/django/test/runner.py", line 548, in run_tests suite = self.build_suite(test_labels, extra_tests) File "/home/srk/Envs/project1/local/lib/python2.7/site-packages/django/test/runner.py", line 437, in build_suite tests = self.test_loader.loadTestsFromName(label) File "/usr/lib/python2.7/unittest/loader.py", line 100, in loadTestsFromName parent, obj = obj, getattr(obj, part) AttributeError: 'module' object has no attribute 'reset_password' -
How to pass argument to HyperLinkedIdentityField's view_name
I am using django rest framework and have created a serializer class as class ForumTopicListSerializer(ModelSerializer): threadUrl = HyperlinkedIdentityField( view_name = 'forum-api:thread_list_forum_topic' ) class Meta: model = ForumTopic fields =[ 'id', 'title', 'threadUrl' ] I Have a HyperLinkedIDentityField and the view there is forum-api:thread_list_forum_topic but the problem is that this view requires an argument to be passed. Its url is as url(r'thread/topic/(?P<forumTopic>[0-9]+)/$', ThreadListForumTopicAPIView.as_view(), name = 'thread_list_forum_topic'), So how do i pass the argument of the forumTopic is the HyperLinkedIdentityField? -
PyCharm don't start up
I'm new to python community and intends to use PyCharm for django framework. However, after installing PyCharm (32 bit launcher same as my OS), the software can't be launched. After double-click the pycharm icon nothing happens, also tried on pycharm.exe, pycharm.bat, and pycharm64.exe, they all failed to start. Have tried to search about the system requirement and I believe everything fits. My OS is 32x bit, 4gb RAM and 100+gb storage available. Hope anyone could give me hints about this issue. Thank you! -
Start over with django migrations
I have 2 related questions. I have deleted all my migrations, including the migrations directory, from all the apps in my project. I've started with a clean database. But still, when I run ./manage.py makemigrations, django says there are no changes to be made. How do I completely start over with migrations? No squashing, just starting over. It seems that when I call makemigrations, django consults the database. I'd like my codebase to be the only source of truth for my migrations. Is there a way to do this? -
Inline models with images in admin model
I have two models products and products images now I want to add product and images from the admin using one single form Product Model class Products(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=250) description = models.TextField(null=True) category = models.ForeignKey(ProductCategory, null=True, blank=True) business = models.ForeignKey(BpBasic, default=BpBasic.get_admin_business().bp_id) created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(default=None, null=True) created_by = models.ForeignKey(User, null=False, blank=False, related_name='product_created_by') updated_by = models.ForeignKey(User, null=True, blank=False, related_name='product_updated_by') Product Images Models class ProductImage(models.Model): product = models.ForeignKey(Products, null=False, on_delete=models.CASCADE, related_name='product') image = models.ImageField(upload_to='media/products/') primary = models.BooleanField(default=False) created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(default=None, null=True) created_by = models.ForeignKey(User, null=False, blank=False, related_name='prod_image_created_by') updated_by = models.ForeignKey(User, null=True, blank=False, related_name='prod_image_updated_by') Product Image Inline Model class ProductImageInline(admin.StackedInline): model = ProductImage exclude = ('created_at', 'updated_at', 'created_by', 'updated_by') extra = 1 Product Admin Model class ProductAdmin(admin.ModelAdmin): model = Products list_display = ('name', 'description', 'category') fieldsets = [ ('Product Details', {'fields': ['name', 'description']}), ('Product Category', {'fields': ['category']}) ] inlines = [ProductImageInline] def save_formset(self, request, form, formset, change): def set_user(instance): if not change: instance.created_by = request.user else: instance.updated_by = request.user instance.save() print formset instances = formset.save(commit=False) print list(instances) map(set_user, instances) instances.save() return instances def save_model(self, request, obj, form, change): if not change: obj.created_by = request.user obj.business = request.user.profile.business else: obj.updated_by = request.user obj.save() return obj … -
django rest framework attribute error
I made two simple examples to illustrate what got me confused. In the first example accessing the class & instance variables works as expected. However in the 2nd example, accessing the variables from within the Serializer class fails. Can you explain me why is that? Example #1: class A(): x = 10 # accessing class variable works as expected A.x > 10 a = A() # accessing instance variable works as expected a.x > 10 Example #2: from rest_framework import serializers class EmailFieldSerializer(serializers.Serializer): email = serializers.EmailField() # why does this fail? EmailFieldSerializer.email > AttributeError: type object 'EmailFieldSerializer' has no attribute 'email' serializer = EmailFieldSerializer() # why does this fail too? serializer.email > AttributeError: type object 'EmailFieldSerializer' has no attribute 'email' -
Django: error: invalid command 'bdist_wheel'
I have installed the packages but met the traceback,which shows error: invalid command 'bdist_wheel'. I referenced Why can I not create a wheel in python? wheel ,setuptools --force, --upgrade pip was all updated and installed. So I am confused why it still error. [192.168.15.xxx] out: Running setup.py bdist_wheel for bokeh ... [?25lerror [192.168.15.xxx] out: Complete output from command /home/user/project/weather_station/venv/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-25c2v483/bokeh/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /tmp/tmpn5f73qcnpip-wheel- --python-tag cp35: [192.168.15.xxx] out: [192.168.15.xxx] out: [192.168.15.xxx] out: usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] [192.168.15.xxx] out: or: -c --help [cmd1 cmd2 ...] [192.168.15.xxx] out: or: -c --help-commands [192.168.15.xxx] out: or: -c cmd --help [192.168.15.xxx] out: [192.168.15.] out: error: invalid command 'bdist_wheel' -
return default value form model field
In my calculation I have this start = Project.objects.all().order_by('created').first().created, I'm ordering my projects by created date so I can do something with them, now what is the best way to return default value from status, I need this value so I can calculate projects on the date when they are accepted. status = models.CharField(max_length=15, choices=ProjectChoices.PROJECT_STATUSES, default=ProjectChoices.STATUS_STARTED) -
How I could create a theme selector for Django (ideas, advices, ...)
I'm developping and improving my Django website and I would like to get advices about graphic charts and what I can do with Django. When I'm developping my software, I adopted a graphic chart according to my compagny's colors (blue and white) in order to display a good trial version. But, if I have to develope my project for another compagny, let suppose with "green and red" graphic chart, I have to modify all my CSS files and replace original white & blue colors by green & red. My question is : How I could write a script which will be located in a tools menu in my Django website with a theme selector ? For example, I had to create some CSS file and choose the good one by checking a case ? Then, the website will adopt colors from this theme. Something like this in Dolibarr Software : For the moment, I'm just getting some ideas / processes and if someone had already made this kind of things ? Thank you -
invalid literal for int() with base 10 while using session
I'm trying to send data from one view to another. I want to access the email throughout my application so, I'm setting email to session. Now, I want to get object passing email as pk. View where I set the session def login(request): if request.method == 'POST': user = get_object_or_404(UserDetails, pk=request.POST['email']) if(user.password==request.POST['password']): request.session['email']=user.email return redirect('/users/dashboard/') else: return render(request, 'accounts/login.html') else: return render(request, 'accounts/login.html') View where I want to access the session value and use it to get the object def profile(request): if(request.session['email'] is not None): user = get_object_or_404(UserDetails, pk=request.session['email']) userprofile = get_object_or_404(UserProfile, pk=request.session['email']) return render(request, 'users/profile.html', {'user':user, 'profile':userprofile}) Model class UserDetails(models.Model): email = models.EmailField(max_length=200, primary_key=True, blank=False) name = models.CharField(max_length=200, blank=False) password = models.CharField(max_length=100) city = models.CharField(max_length=200) mobile_num = models.IntegerField() I am getting this invalid literal for int() with base 10 error at my email value.This might be a question asked many times but, I did not find any solution to it.Any help will be appreciated. Thanks! -
Why I am Getting '_SIGCHLDWaker' object has no attribute 'doWrite' in Scrapy?
I am using Scrapy spiders inside Celery and I am getting this kind of errors randomly Unhandled Error Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/twisted/python/log.py", line 103, in callWithLogger return callWithContext({"system": lp}, func, *args, **kw) File "/usr/lib/python2.7/site-packages/twisted/python/log.py", line 86, in callWithContext return context.call({ILogContext: newCtx}, func, *args, **kw) File "/usr/lib/python2.7/site-packages/twisted/python/context.py", line 122, in callWithContext return self.currentContext().callWithContext(ctx, func, *args, **kw) File "/usr/lib/python2.7/site-packages/twisted/python/context.py", line 85, in callWithContext return func(*args,**kw) --- <exception caught here> --- File "/usr/lib/python2.7/site-packages/twisted/internet/posixbase.py", line 602, in _doReadOrWrite why = selectable.doWrite() exceptions.AttributeError: '_SIGCHLDWaker' object has no attribute 'doWrite' I am using: celery==3.1.19 Django==1.9.4 Scrapy==1.3.0 This is how I run Scrapy inside Celery: from billiard import Process from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings class MyCrawlerScript(Process): def __init__(self, **kwargs): Process.__init__(self) settings = get_project_settings('my_scraper') self.crawler = CrawlerProcess(settings) self.spider_name = kwargs.get('spider_name') self.kwargs = kwargs def run(self): self.crawler.crawl(self.spider_name, qwargs=self.kwargs) self.crawler.start() def my_crawl_manager(**kwargs): crawler = MyCrawlerScript(**kwargs) crawler.start() crawler.join() Inside a celery task, I am calling: my_crawl_manager(spider_name='my_spider', url='www.google.com/any-url-here') Please any idea why this is happening? P.S: I have asked another question Why I am Getting KeyError in Scrapy? I don't know if they are somehow similar -
Django 1.10 ManyToMany get all objects
I have this model for apps: class App(models.Model): app_name = models.CharField(max_length=50,blank=True,null=True) app_type = models.CharField(max_length=12,blank=True,null=True,choices=APPTYPE) and I have this intermediate model: class AppPivot(models.Model): host = models.ForeignKey(Hosts, models.DO_NOTHING, blank=True,null=True) app = models.ForeignKey(App, models.DO_NOTHING,blank=True,null=True) owner = models.ForeignKey(AppOwner, models.DO_NOTHING,blank=True,null=True) I'm trying to query the below model and get all related entries: class Hosts(models.Model): host_name = models.CharField(max_length=200, unique=True) host_group = models.ForeignKey(Groupvars,models.DO_NOTHING,default='30') host_project = models.ForeignKey(Project,models.DO_NOTHING,blank=True,null=True) host_env = models.ForeignKey(Env, models.DO_NOTHING,blank=True,null=True) os = models.CharField(max_length=25,blank=True,null=True) ticket = models.CharField(max_length=50,blank=True,null=True,default='-') app = models.ManyToManyField(App,through='AppPivot') I tried the below and got empty results for the app fields: hosts = Hosts.objects.filter(is_enabled='Y').prefetch_related('app').select_related('host_group').select_related('host_env').select_related('host_project').all() What am I missing? -
Django show image/video which is outside of static folder
I want to make web site which show file tree in web and print image/video on web. I'm planning to print it with html tag img and video. However there are some problems with path. Most of my static files( like video or img) outside of django project folder. For example django template source and view source is at /Users/Knight/My-site/Damotorie_cafe/views.py and image is at /Applications/MAMP/practice I tried to get relative path with python code and use it for src attribute. Same path works well when I don't use django and just open it with local web browser, however when I open it with django then error occur. I'm starter in django. Can any one help me? (I searched it before asking, but most of question is about upload not show image.) -
django rest add data to serializer when saving
I want to do the following: models.py class MyModel(TimeStampedModel, models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey(settings.AUTH_USER_MODEL) serializers.py class MyModelSerializerCreate(serializers.ModelSerializer): class Meta: model = MyModel fields = ( 'name', ) And I would like to add as owner the current user in request.user. Currently I am adding this in my view directly by uptading request.data with user and then pass the updated data to my serializer. data = request.data # Add owner to data data["owner"] = request.user.pk serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) I would like to do this in my serializer directly but can't find a way to properly do it because it looks like data validation to me. Is this a good idea ? Should I keep this logic in my views or move it to my serializer ? -
Celery Results Backend HTML & JSON
The application I am working on requests content from static HTML pages and API endpoints and needs to support both content types in a result backend. Is there a way to work with both HTML and JSON in a Celery Results Backend? I have tried to use pickle, text/plain and application/json as the CELERY_ACCEPT_CONTENT settings variable without any luck.