Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django wont start with Docker, new to Docker
Docker starts my django server and says its up at 0.0.0.0:8000, but i cant reach it in my browser, neither 0.0.0.0:8000 nor 127.0.0.1:8000 work web_1 | You have unapplied migrations; your app may not work properly until they are applied. web_1 | Run 'python manage.py migrate' to apply them. web_1 | April 30, 2017 - 03:36:35 web_1 | Django version 1.8.5, using settings 'my_project.settings' web_1 | Starting development server at http://0.0.0.0:8000/ web_1 | Quit the server with CONTROL-C. -
How to add the high cahrt function in my function in view.py?
I have follow this tutorial How to pass all the data in dataframe that extract from excel sheet to highchart? and now I need to build high chart function in another function, which mean in my interface I have my dataframe now I need to add the high chart under the dataframe but not able. This is my code for datafarme def read_raw_data(request): Wb = pd.read_exce(r"C:/Users/S/Desktop/excel/okAhead.xlsm") Step1_Result = Wb.replace(np.nan, 0, regex=True) drop_column = Step1_Result.drop(['facility','diecodename','rev','step], 1) uniquevaluesproduct = np.unique(drop_column[['Product']].values) total_count=drop_column['Product'].nunique row_array=[] for name, group in drop_column.groupby('Product'): # print the name of the regiment print(name) # print the data of that regiment group=group.values.tolist() row_array.append(group) print(group) i=1 temp=row_array[0] while i<total_count: newb = temp + row_array[i] temp=newb i = i + 1 print(newb) print(temp) b = ['indicator', 'month', 'ww', 'test_time', 'phi', 'Product'] #dataframe = pd.DataFrame.from_records(newb, columns=b) superstupidkia=temp test=pd.DataFrame.from_records(superstupidkia, columns=b) table = test.style.set_table_attributes('border="" class = "dataframe table table-hover table-bordered"').set_precision(10).render() context = { "result": table } return render(request, 'result.html', context) I wish to add this code in above function but not able: class BarView(HighChartsBarView): categories = ['Orange', 'Bananas', 'Apples'] @property def series(self): result = [] for name in ('Joe', 'Jack', 'William', 'Averell'): data = [] for x in range(len(self.categories)): data.append(random.randint(0, 10)) result.append({'name': name, "data": data}) return … -
confusion on which serializer to use to update user profile
I have a profile model for user to update. I want to have a rest api for that. I have a profile model which is too big than usual. I am working to update the user profile but I am having confusion on which serializer should i use to update the profile. Here is what i have done till now I created the serializer for user and user profile. class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('token', 'user','current_location', 'permanent_location', 'dob', 'about_me', 'gender_status', 'create_profile_for', 'marital_status', 'height', 'weight', 'body_type', 'complexion',) # # def update(self, instance, validated_data): # # instance = super(ProfileSerializer, self).create(validated_data) # profile = Profile.objects.update(user=instance.user, **validated_data) # return profile class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer(required=True) class Meta: model = User fields = ('id', 'profile', 'username', 'first_name', 'last_name',) def update(self, instance, validated_data): profile = validated_data.pop('profile') Profile.objects.update(**profile) This is my view class UserProfile(APIView): serializer_class = UserSerializer def get(self, request, token=None, format=None): """ Returns a list of profile of user """ reply={} try: profile_instance = Profile.objects.filter(user=self.request.user) if token: profile = profile_instance.get(token=token) reply['data'] = self.serializer_class(profile).data else: reply['data'] = self.serializer_class(profile_instance, many=True).data except: reply['data']=[] return Response(reply, status.HTTP_200_OK) def post(self, request, token=None, format=None): """ update a profile """ profile=None if not token is None: try: profile = … -
Force Remove Phpmyadmin and PHP7.0 Sub-process Error
I'm just tired of PHP7.0 forcing itself on me! I've deleted all files relating to php7.0 on my vps and I've tried uninstalling it with different command lines yet it will bring up the below error..even after I deleted it folders. I wanted to install supervisor but I couldn't because of the below error that PHP is still giving. I Don't want to use phpmyadmin and PHP7 anymore.! I'm on Ubuntu 16.04. What am I missing to clear this? Reading package lists... Done Building dependency tree Reading state information... Done supervisor is already the newest version (3.2.0-2ubuntu0.1). 0 upgraded, 0 newly installed, 0 to remove and 54 not upgraded. 2 not fully installed or removed. After this operation, 0 B of additional disk space will be used. Do you want to continue? [Y/n] y Setting up php7.0-fpm (7.0.18-1+deb.sury.org~xenial+1) ... Not replacing deleted config file /etc/php/7.0/fpm/php.ini Job for php7.0-fpm.service failed because the control process exited with error code. See "systemctl status php7.0-fpm.service" and "journalctl -xe" for details . invoke-rc.d: initscript php7.0-fpm, action "start" failed. dpkg: error processing package php7.0-fpm (--configure): subprocess installed post-installation script returned error exit status 1 dpkg: dependency problems prevent configuration of phpmyadmin: phpmyadmin depends on libapache2-mod-php | … -
Pytest uploaded files being placed in MEDIA_ROOT folder even though @override_settings(MEDIA_ROOT) has a different directory
I overrode my save() method on my model for profile image resizing after being uploaded. However, when I run my test using pytest, the files are placed directly into my media directory instead of the @override_settings test directory. What am I doing wrong? Below is my code: MODEL: def user_directory_path(instance, filename): ext = filename.split('.')[-1] new_name = '{0}_{1}.{2}'.format('profile', instance.profile.user.username, ext) return 'user_{1}_{0}/avatar/{2}'.format(instance.profile.user.id, instance.profile.user.username, new_name) class ProfileAvatar(models.Model): profile = models.OneToOneField(Profile, on_delete=models.CASCADE, primary_key=True) avatar = models.ImageField(upload_to=user_directory_path, default='generic/default.jpg') def save(self, *args, **kwargs): ext = self.avatar.name.split('.')[-1] image = Image.open(self.avatar) image_resize = ImageOps.fit(image, (300, 300), Image.LANCZOS) image_resize_io = BytesIO() if ext in ['jpg', 'jpeg']: image_resize.save(image_resize_io, format='JPEG') elif ext in ['png']: image_resize.save(image_resize_io, format='PNG') temp_name = self.avatar.name self.avatar.save(temp_name, content=ContentFile(image_resize_io.getvalue()), save=False) super(ProfileAvatar, self).save(*args, **kwargs) TEST: @override_settings(MEDIA_ROOT='/tmp/django_test') def test_avatar_upload_image_saves(self, client): image = SimpleUploadedFile(name='test.jpg', content=open( 'profiles/tests/test_images/test.jpg', 'rb').read()) response = client.post(reverse('profiles:av-upload', kwargs={ 'pk': self.user.id, 'username': self.user.username}), {'avatar': image}, follow=True) avatar = ProfileAvatar.objects.select_related( 'profile').get(profile_id=self.user.id) assert avatar.avatar.name == 'user_Testy2McT_3/avatar/profile_Testy2McT.jpg', 'Should return new filename and path.' -
Django migration and MariaDB: SQL Error (1005): Can't create table
MariaDB: 10.2.22, Django: 1.10.6, HeidiSQL: 9.4.0.5125 What can be the cause of the following error and how could it be prevented? SQL Error (1005): Can't create table databasename.#sql-a71_1824 (errno: -1 "Internal error < 0 (Not system error)") I'm using Django and MariaDB. In a Django model, I've chaned the field lenght of a CharField. While 'makemigrations' runs fine, 'migrate' aborts with above error. Afterwards, I tried to modify the field size directly (I'm using HeidiSQL),but got the same error msg. -
How to upload a file in django and run a python script on it?
I have worked on a project on python that takes input as an Excel file and returns its output as an Excel file in the same folder.I am a rookie in Django and want to make a website so that a user can upload his file and get the output file downloaded when the python script has finished working. Kindly help me with, 1. How to pass uploaded file to a python script ? 2. How to run the python script in django ? 3. How to get the file downloaded once processing has been done? -
Django error: multiple default values for specified column "id"
I'm working with a project with docker-compose, where I have a postgre container. When I run: docker-compose -f dev.yml run django python manage.py migrate I get the error: django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "scrapy_scrapy" That is happening before I made some changes to my models.py file. But now the file is correct and should be working. This is the content of the models.py file: from django.db import models import django # Create your models here. class Scrapy(models.Model): user = models.CharField(max_length=50,blank=True) password = models.CharField(max_length=50,blank=True) projecte = models.CharField(max_length=100) estat_last_check = models.CharField(max_length=700, default="", blank=True) date = models.DateTimeField(default=django.utils.timezone.now, blank=True) app_label = '' def __str__(self): # __unicode__ on Python 2 return self.projecte + " - " + self.user class Meta: app_label = 'scrapy' As you can see, no id filed is defined anymore, so, why is complaining about that field? I've done my research and tried some possible solutions, but no luck. I've already tried deleting the full Docker container and creating it again, or trying to delete the database. Any ideas? -
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.