Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
For schemaless db like mongodb How can I skip MODEL part for MVC or MVT.
Mongodb is a schemaless concept. So for django or any other framework, can i skip design MODEL part(MVC or MVT) in advanced. advice me -
Django Form (Checkbox) - unable to save data
I am trying to display a form (with multiple select checkbox) and save the data in database. But having some problem. Here is My Model:- class Preference(models.Model): CLASS_CHOICES = [('1', '1'), ('2', '2'), ('3', '3')] BOARD_CHOICES = [('C', 'CBSE'), ('I', 'ICSE'), ('S', 'State Board')] SUBJECT_CHOICES = [('H', 'HINDI'), ('M', 'MATH'), ('E', 'ENGLISH')] class = models.CharField(max_length=2, choices=CLASS_CHOICES, default='1', blank=False) board = models.CharField(max_length=2, choices=BOARD_CHOICES, default='C', blank=False) subject = models.CharField(max_length=2, choices=SUBJECT_CHOICES, default='M', blank=False) My form:- class PreferenceForm(forms.ModelForm): class Meta: model = Preference fields = ['class', 'board', 'subject'] widgets = { 'board': forms.RadioSelect(), 'subject': forms.CheckboxSelectMultiple() } My View:- def pref(request): form = PreferenceForm(request.POST or None) if form.is_valid(): form.save() return render(request, 'website/thanks.html') else: print(form.errors) return render(request, 'website/pref.html', {'form': form}) It displays the form with checkbox but I am unable to save that data to database even when I select a single choice. Error Displayed:- ` <li>Subject<ul class="errorlist"><li>Select a valid choice. [&#39;H&#39;, &#39;M&#39;] is not one of the available choices.</li></ul></li> All help/suggestions are appreciated, thanks. -
CONFLICT (content): Merge conflict in migrations/0001_initial.py
CONFLICT (rename/delete): migrations/0003_auto_20170419_2013.py deleted in HEAD and renamed in 2bb95952ff3911ed6cdb3fce0a83ea5f6ac88558. Version 2bb95952ff3911ed6cdb3fce0a83ea5f6ac88558 of migrations/0003_auto_20170419_2013.py left in tree. CONFLICT (rename/delete): migrations/0002_auto_20170419_1648.py deleted in HEAD and renamed in 2bb95952ff3911ed6cdb3fce0a83ea5f6ac88558. Version 2bb95952ff3911ed6cdb3fce0a83ea5f6ac88558 of migrations/0002_auto_20170419_1648.py left in tree. Auto-merging migrations/0001_initial.py CONFLICT (content): Merge conflict in migrations/0001_initial.py Automatic merge failed; fix conflicts and then commit the result. Pulled code from github to production, what is the best way of resolving such conflicts in order not to get problems now and later? What happened is that I had problems with database localy and changed it, so migrations are totally different. Possibly faked migrations localy. And second point, as far as it's pulling application folder, would it be helpful just to add migrations to gitignore file ? -
How in DJANGO create editable Select field?
How in DJANGO create editable select field as in the picture below? I used before django-floppyforms app in my project. It use datalist which is unflexibility in css styling. So is it possible replace detalist to ul, li elements? forms.py: CharacteristicForm(forms.ModelForm): user_class = floppyforms.CharField( widget=floppyforms.TextInput( datalist=['A', 'B', 'C'], attrs={'autocomplete': 'off',} ) ) class Meta: model = Characteristic fields = ('user_class') -
Django App Deploy on AWS Elastic Beanstalk Error: relation "django_site" does not exist
I am using this popular tutorial to deploy a django app on AWS EB. https://realpython.com/blog/python/deploying-a-django-app-to-aws-elastic-beanstalk/ After deploying I am getting the following error: ProgrammingError at /accounts/login/ relation "django_site" does not exist LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... Fixes others have suggested that I have done: I have 'django.contrib.sites' in my installed apps (settings.py) I have SITE_ID = 1 in settings Some are suggesting that you run manage.py migrate sites before migrating the rest of the tables. Does anyone know how to do that on an AWS instance? I SSH'd in and that command won't run. Any help would be very much appreciated. I've been battling AWS Elastic Beanstalk for a week now. -
Can't seem to setup my Django project properly
I was trying the official tutorial of Django because I want to learn it. I run Archlinux 4.10.11-1 64 bits. First, I created a folder named djangoapp where I set my virtual environment: $ virtualenv djangoapp I set my current directory to this folder, and then I activated it: $ source bin/activate And I installed Django after: $ pip install django Following the tutorial, I ran: $ django-admin startproject djangoapp And set my current directory to djangoapp, and ran: $ python manage.py runserver But I'm getting the following error: django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Indeed, running env | grep DJANGO_SETTINGS_MODULE gets me the following result: DJANGO_SETTINGS_MODULE= So I tried to set it manually: $ export DJANGO_SETTINGS_MODULE='djangoapp.settings' Running $ python manage.py runserver now works, but $ django-admin help now gets me the following error: ModuleNotFoundError: No module named 'djangoapp' What did I do wrong? Thanks for your help! PS: $ python --version gets me Python 3.6.1. -
Django Archive class-based-view efficiency
I'm having performance issues using django's date archive cbv's and I'm looking for help to get some gains. I've been reading about prefetch_related and I'm convinced this method would help, but I'm not sure how to implement it. My code: #models.py class Job(models.Model): class Meta: ordering = ['-date'] get_latest_by = 'date' number = models.CharField(max_length=15, default='0') date = models.DateField() customer = models.ForeignKey(Customer) --snip-- def value(self): total = 0 for ticket in self.tickets.all(): total += ticket.value() return total class Ticket(models.Model): job = models.ForeignKey(Job, related_name='tickets') amount = models.FloatField() rate = models.FloatField() --snip-- def value(self): return self.amount * self.rate In views: #views.py class JobListYearly(YearArchiveView): template_name = 'ledger/job_list_yearly.html' model = Job date_field = 'date' make_object_list = True queryset = Job.objects.all().prefetch_related('tickets') def get_context_data(self, **kwargs): context = super(JobListYearly, self).get_context_data(**kwargs) job_list = context['job_list'] context['job_list'].prefetch_related('tickets') total = 0 for job in job_list: total += job.value() context['sum'] = total return context I can tell from lack of performance gains that the way I implemented prefetch_related did not work, and I have some sense that this is due to using the cbv. Any recommendations on how to implement this with efficiency in mind? It's even slower on the template as I'm also displaying all of the tickets. Any help would be … -
Django and microsecond discrepancy in DateTimeField
I have a code that calculates a given datetime as follows time = datetime.datetime.now() - datetime.timedelta(minutes=60) I then use time to set a field in an offer object to be saved in the database. The offer.time is a Offer model instance; it is configured to be: time = models.DateTimeField(blank=True, null=True) It happens, however, that offer.time is updated when calling offer.save(). When setting offer.time = time, I get 2017-04-29 09:36:14.895581. After calling offer.save, offer.time is 2017-04-29 09:36:14.895000. Why isn't save() preserving the original time? Any ideas? Thanks in advance. -
Django left join models
I want to left join the below tables and add a filter condition on approved_coupon field. My models class Voucher(models.Model): voucher_id = models.UUIDField(default=uuid.uuid4, editable=False) voucher_code = models.CharField() class ApprovedCouponLine(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) approved_coupon = models.ForeignKey(ApprovedCoupon, on_delete=models.CASCADE, related_name='approved_coupon_lines') coupon_code = models.ForeignKey(Voucher, on_delete=models.CASCADE, related_name='approved_coupon_lines_coupons') I tried this, but it shows the inner join. queryset = Voucher.objects.filter(approved_coupon_lines_coupons__approved_coupon_id='CD5FC4FE').values_list('code', flat=True) Current Query: SELECT "voucher_voucher"."code", "voucher_approvedcouponline"."id" FROM "voucher_voucher" INNER JOIN "voucher_approvedcouponline" ON ("voucher_voucher"."id" = "voucher_approvedcouponline"."coupon_code_id") WHERE "voucher_approvedcouponline"."approved_coupon_id" = 'CD5FC4FE' Expected Query: SELECT "voucher_voucher"."code", "voucher_approvedcouponline"."id" FROM "voucher_voucher" LEFT JOIN "voucher_approvedcouponline" ON ("voucher_voucher"."id" = "voucher_approvedcouponline"."coupon_code_id" AND "voucher_approvedcouponline"."approved_coupon_id" = 'CD5FC4FE' ) What I missed in the above example? -
Not able to access foreign key in the view function
The function is not accepting the foreign key. It is getting a syntax error. This is the code of the function. views.py def projectoraccept(request, eventprojector_id): eventprojector = get_object_or_404(Eventprojector, pk=eventprojector_id) if request.method == 'POST': eventprojector.is_accept = eventprojector.is_accept+1 eventprojector.save(update_fields=['is_accept']) if eventprojector.projector.sec.sec_name == 'CS_dept' eventprojector.projector.cs_no = eventprojector.projector.cs_no-1 eventprojector.projector.save(update_fields=['sec']) elif eventprojector.projector.sec.sec_name is EC dept eventprojector.projector.ec_no = eventprojector.projector.ec_no-1 eventprojector.projector.save(update_fields=['sec']) elif eventprojector.projector.sec.sec_name is EEE dept eventprojector.projector.eee_no = eventprojector.projector.eee_no-1 eventprojector.projector.save(update_fields=['sec']) elif eventprojector.projector.sec.sec_name is IEEE eventprojector.projector.ieee_no = eventprojector.projector.ieee_no-1 eventprojector.projector.save(update_fields=['sec']) elif eventprojector.projector.sec.sec_name is TCP dept eventprojector.projector.tcp_no = eventprojector.projector.tcp_no-1 eventprojector.projector.save(update_fields=['sec']) return render(request, 'event/projectordetails.html' , {'eventprojector' : eventprojector }) -
Upload multiple files at once, with different sets of categories - Django forms
I have a form which has to do multiple file uploads at once, through Django ModelForm. The scenario is like, I have a form in which different categories of documents has to be attached. For example, there maybe Medical records, Physician referrals, Diagnostic reports, etc. Each of these categories are stored in the DB. I have to upload all these documents according to their respective categories, through a single form submission. Here are my Django models. class Patient(models.Model): first_name = models.CharField(_("First Name"), max_length=30) last_name = models.CharField(_("Last Name"), max_length=30) email = models.EmailField(max_length=255) class DocumentType(models.Model): """ Type of document to be attached alongside a Patient. """ name = models.CharField(max_length=255) class DocumentFile(BaseModel): """ Documents to be attached alongside each document type within a Patient Case. Multiple documents to be attached. """ type = models.ForeignKey(DocumentType) attachment = models.FileField(upload_to=get_new_documents_path, blank=True) patient = models.ForeignKey(Patient, related_name="get_applicable_documents") Please tell me which is the best method to process the form submission. Any help would be much appreciated. -
Creat a unique name for the group when its created by a user in django
I'm trying to create an app that allows my user to create a House and then be able to add Occupants. However my issue is that name of the house needs to be unique, for example if i could automatically set the default name as "Username House". Dynamically inserting the user name of the person who is creating the house. this is what i have so far User = settings.AUTH_USER_MODEL class House(models.Model): owner = models.ForeignKey(User, null=True, blank=True) name = models.CharField(max_length=50) def __unicode__(self): return self.name class Occupant(models.Model): house = models.ForeignKey(House) occupants = models.ForeignKey(User) currently they can add any title they want -
How to fill out a list from the database?
I need to bind to each alias its rating, which would then display in the template, and order products by decreasing. How can I do that? class Items(models.Model): name = models.CharField(max_length=15, verbose_name='Название товара', default='') price = models.IntegerField(default=0, verbose_name='Цена') # image = models.CharField(max_length=255, verbose_name='Картинка', default='') image = models.ImageField(null=True, blank=True, upload_to='image/', verbose_name='Изображение') alias = models.SlugField(verbose_name='Alias товара', default='') rating = models.FloatField(default=0, verbose_name='Рейтинг') def popular(request): title = 'Популярные' products = Items.objects.all() category = Category.objects.all() context = { 'products': products, 'category': category, 'title': title, } return render(request, 'popular/main.html', context) -
Regex to match combination of letter and numbers to be used in URL pattarns in Django Project?
I need to pass username in my URL. username can be any combination of letter, numbers and special characters like @,_. also, username starts with a letter. username examples: test@1, test_1,test2_1990, -
Django Split a charfield output which is seperated by ','(comma) into an array of strings.?
template.html {{ model.tag }} gives output as "tag1,tag2,tag3" is there ant way to do it in django itself? i want output as shown below -
Linux - Generate a video from pictures and text
I'm developing a server with AWS Elastic Beanstalk. I have a project that is programmed in Django (Python) and I have to generate a video from an array of user images. If possible, I have to append text on the images too. I took a look at ffmpeg and using lambda functions from AWS, but I can't see if I can paint text on the images. It seems like there's a library that lets lambda execute ffmpeg: https://github.com/binoculars/aws-lambda-ffmpeg/ -
Passing url parameters in form widget django
Im trying to implement auocomplete in my django project. I want to pass a parameter through the url in the form. This is my Form class SongForm(forms.ModelForm): song_title = forms.ModelChoiceField( queryset=Snr.objects.all(), widget=autocomplete.ModelSelect2(url='login:song-autocomplete',attrs={'data-placeholder': 'Autocomplete ...', 'data-minimum-input-length': 3,},) ) class Meta: model = Song fields = ['song_title'] my url pattern is url(r'^(?P<playlist_id>[0-9]+)/create_song/song-autocomplete/$', views.SongAutocomplete.as_view(), name='song-autocomplete', ), so while calling the url song-autocomplete it needs a parameter playist_id. How do I send it using the url='login:song-autocomplete'? Thank you. -
Django - Get values from ManyToManyField which is foreing key
please help to understand. I have the next models : class TagsList(models.Model): tags_list = models.CharField(max_length=30) def __str__(self): return self.tags_list class Blog(models.Model): title = models.CharField(max_length=200) content = models.TextField() pub_date = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(TagsList) how i can get related tags by object (in my case object with post_id)? It's my view file : def single(request, post_id): object_post = Blog.objects.get(id=post_id) tags = TagsList.objects.all() content = { 'object_post': object_post, 'tags': tags, } return render(request, 'single.html', content) I tried all cases, but how to include to content exactly tags which are related to this object, don't know. Thanks all, for the help. P.S. Using django 1.11 -
Which file format django imagefield(filefield) requires?
I'm trying to send file as JSON field to server for creating a new instance. This file has being saved in models.ImageField. However, I don't know which format this field requires for incoming file. I tried to send it in base64, but it isn't suitable. -
Django - Can't do a POST request, receiving 405 "Method not allowed"
i'm trying to do a simple POST request to my endpoint, but i'm getting a 405 "Method not Allowed", here's my code: urlpatterns = [ url(r'^api/exemplo/post/$', ExempleView.as_view(), name='post'), ] Post method: class ExempleView(APIView): def post(self, request, *args, **kwargs): print(request.data) Server logs: Method Not Allowed (POST): /api/exemplos/post/ [29/Apr/2017 14:30:20] "POST /api/exemplos/post/ HTTP/1.1" 405 0 I'm using Postman to do the post request and rest_framework to create my API, any suggestion? -
Why two almost identically querysets work differently?
I have comment and rate model. class Rate(models.Model): game = models.ForeignKey(Games) user = models.ForeignKey(User) rate = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(10)]) class Meta: unique_together = ['game', 'user'] class Comment(models.Model): game = models.ForeignKey(Games) author = models.ForeignKey(User) content = models.TextField(max_length = 2500) date_of_published = models.DateTimeField() For comments I have queryset in game view : comments = Comment.objects.filter(user=request.user) and in templates: {% for x in comments %} {{ x.content}} {% endfor %} And it works very well. I can display comments from only loggedin user. but I have too queryset for rate. user_rate = Rate.objects.filter(user=request.user) It doesn't work properly. In templates: {% if user_rate %} <h2><a href="">Edit rate</a></h2> {% else %} <h2><a href=">Add rate</a></h2> {% endif %} It doesn't work. I should display Add if user don't have rate, and Edit if user have rate. BUT, If user have rate for only game1, he see in game2, game3, and others Edit ( he should see Add, because he doesn't have rate for this game...) and {% for user_rate in user_rate %} <p> Your score : {{ user_rate.rate }} <p> {% endfor %} User should be see Your score : (rate for this game) But in this case, user see his score from all games... How to … -
Unresolved reference 'models'
I am writing custom template tag, and the error occurs that "Unresolved reference 'models'" the following is my blog_tags.py. from django import template from .models import Post register = template.Library() @register.simple_tag def total_posts(): return Post.published.count() And my directory tree is as followed blog/ __init__.py models.py ... templatetags/ __init__.py blog_tags.py And i do have a Post class in my Models. And when i click the prompt by pycharm "install package Post", after finishing installed it, the error disappear. I wonder do i have to do the same, which is install the package by the IDE, every time when i want to write a custom tag evolved with class in my Models? -
how to get specific value in python dictionary?
I call an api via python and return this code as response: { "cast": [ { "character": "Power", "name": "George" }, { "character": "Max", "job": "Sound", "name": "Jash" }, { "character": "Miranda North", "job": "Writer", "name": "Rebecca" } ] } I am trying to get the value of Rebecca because i need to get the Writer. So i wrote: for person in cast # cast is the variable keeps whole code above NOT inside the dict: if person["job"] == "Writer": writer = person["name"] but it gives me: KeyError at search/15 u'job' how can i get the value? -
Django ChoiceField, ModelChoiceField validation
I see that forms.ChoiceField is using this code to validate the value: def validate(self, value): """ Validates that the input is in self.choices. """ super(ChoiceField, self).validate(value) if value and not self.valid_value(value): raise ValidationError( self.error_messages['invalid_choice'], code='invalid_choice', params={'value': value}, ) def valid_value(self, value): "Check to see if the provided value is a valid choice" text_value = force_text(value) for k, v in self.choices: if isinstance(v, (list, tuple)): # This is an optgroup, so look inside the group for options for k2, v2 in v: if value == k2 or text_value == force_text(k2): return True else: if value == k or text_value == force_text(k): return True return False and forms.models.ModelChoiceField this code: def validate(self, value): return Field.validate(self, value) Q1. Why Django uses validation to check if the selected value (from dropdown) is indeed in the choice list for forms.ChoiceField? Q2. When Django uses the validation from Q1, to check if the value is indeed in the choice list, why does not also check if the selected value is in the model records for forms.models.ModelChoiceField? -
Django - delete particular cron job (django-crontab)
I am trying to use cron in my django app. I use django-crontab package. This is part of my setings.py: cron1_time = '* * * * *' cron2_time = '*/2 * * * *' CRONJOBS = [ (cron1_time, 'mainapp.cron.print_inactive', '>> /home/user/Desktop/file.log'), (cron2_time, 'mainapp.cron.print_inactive1', '>> /home/user/Desktop/file.log') ] I would like to add an option to disable/enable particular cron jobs from my django admin panel. Is it possible to stop only one job? Crontab add adds every job which exists in CRONJOBS. I think I can use: call_command('crontab', 'remove') command but I don't know how can I delete/add particular cron job.