Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Initialize form with request.user in a ModelForm django
I have this ModelForm class ScheduleForm(forms.ModelForm): class Meta: model = Schedule fields = ['name', 'involved_people',] def __init__(self, user, *args, **kwargs): super(ScheduleForm, self).__init__(*args, **kwargs) self.fields['involved_people'].queryset = Profile.objects.exclude(user=user) This is my view def create_schedule(request): form = ScheduleForm(request.POST or None) schedules = Schedule.objects.all().order_by('deadline_date') if form.is_valid(): schedule = form.save(commit=False) schedule.save() messages.success(request, "Schedule added successfully!") return render(request, 'schedule/index.html', {'schedules': schedules}) context = {'form': form} return render(request, 'schedule/create_schedule.html', context) How do you pass request.user in the view? How do you initialize the form with request.user in it? -
wave.Error: file does not start with RIFF id Is there mistake in my code?
I got an error,wave.Error: file does not start with RIFF id . I wrote in views.py if __name__ == "__main__": train_label = np.array([]) test_label = np.array([]) nfft = 2048 nceps = 12 train_data = np.empty((0, 12), float) test_data = np.empty((0, 12), float) directory = os.listdir('/sound_app/sounds') for file_name in directory: feature = get_feature(file_name, nfft, nceps) if len(train_data) == 0: train_data = feature else: train_data = np.vstack((train_data, feature)) train_label = np.append(train_label) test_label = np.append(test_label,file_name) in mfcc.py def get_feature(wavfile,nfft,nceps): wav,fs = wavread(wavfile) t = np.arange(0.0,len(wav)/fs,1/fs) center =len(wav)/2 cuttime = 0.8 global wavdata wavdata = wav[int(center-cuttime/2*fs):int(center+cuttime/2*fs)] global time time = t[int(center-cuttime/2*fs):int(center+cuttime/2*fs)] ceps = mfcc(wavdata,nfft,fs,nceps) return ceps.tolist() /sound_app/sounds's file has many wav file.I doubt these wav file are really wav file,so I run command /sound_app/sounds/0517.wav & /sound_app/sounds/0518.wav etc ,so it is returned RIFF (little-endian) data, WAVE audio, Microsoft PCM, 16 bit, stereo 44100 Hz .So I think these are really wav file.Therefore I cannot understand why this error happens.Do i make a mistake in my code?How should I fix this? -
Django static file loading error on centos
I have static file loading issue and when I run collectstaic command, it throws error 'Found another file with the destination path 'admin/js/vendor/xregexp/xregexp.min.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path'. Following is my settings for static files in centos server. STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_URL = '/static/' STATIC_ROOT = '/root/www/static-root/' MEDIA_URL = '/media/' MEDIA_ROOT = '/root/www/media-root/' I couldn't find another place where static files get stored. How I can solve the issue, thank you. -
Django - get linked models in many to many
I have two different models: A group model class Group(models.Model): (...) users=models.ManyToManyField(users.User, related_name='trainings') And a very standard user model. I'm trying to write a function where it returns all of the linked groups for a given User object. What would solve my problem is something like this: def get_groups(user): connected_groups = Group.objects.filter(user in users) But that throws an error. It the thing that I am trying possible? Or should I instead create a 'linked_groups' variable within the User model? -
'P' for what in url(r'^(?P<slug>[\w-]+)/$' [duplicate]
This question already has an answer here: what does this django regex mean? `?P` 3 answers In Django's urls.py: url(r'^(?P<slug>[\w-]+)/$', I understand 'slug' is variable,'[\w-]+' is value. What's 'P' stand for? -
Django Rest Framework: How to set a field to null via PATCH request?
I have a Model and a ModelSerializer with this field: models.py: leftovers_from = models.ForeignKey('DayPlanning', null=True, blank=True, related_name='extra_for', on_delete=models.CASCADE) serializers.py: leftovers_from_id = serializers.PrimaryKeyRelatedField(queryset=DayPlanning.objects.all(), source='leftovers_from', write_only=True, required=False) Now I can perfectly fine create a new object for this model using a POST request (both with or without this field being null/None/empty.) However when I try to update the field using PATCH I can only update it with a different value (a PK of the Foreign model). I've tried passing null, '', 0 and -1 to leftovers_from_id, however the result is either This field cannot be empty or PK 0 not found. How do I clear this field using a PATCH request? Thanks! -
How correctly show ValidationError in Django and AJAX?
In my Django project I have modal with form where superuser can create new user. I want to show ValidationError which I set in forms.py file when superuser by mistake write existing email or passwords are not similar. Right not when superuser submit form which has mistakes as I described above browser raise error: SyntaxError: JSON.parse: unexpected character at line 3 column 1 of the JSON data Uncaught TypeError: a.replace is not a function at Function.htmlPrefilter (jquery.min.js:3) at qa (jquery.min.js:3) at Ja (jquery.min.js:3) at r.fn.init.append (jquery.min.js:3) at r.fn.init.<anonymous> (jquery.min.js:3) at T (jquery.min.js:3) at r.fn.init.html (jquery.min.js:3) at Object.error (crud.js:45) at i (jquery.min.js:2) at Object.fireWith [as rejectWith] (jquery.min.js:2) QUESTION: How to show error messages correctly when data is not valid? forms.py: class UserCreateForm(UserCreationForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'is_active', 'is_superuser', 'password1', 'password2') def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email=email).exists(): raise ValidationError(_("Email already exists.")) return email def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError(_("Enter the same password as above, for verification.")) return password2 views.py: class UserCreateView(CreateView): template_name = 'users/create_user.html' form_class = UserCreateForm def get(self, request, *args, **kwargs): data = dict() user_create_form = UserCreateForm() context = {'user_create_form': user_create_form} … -
Django - Filter select choices based on another selected element
I have two models that are related class Filial(models.Model): descricao = models.CharField(max_length=255) empresa = models.ForeignKey( 'BOXCFG.Empresa', related_name="filiais", on_delete=models.CASCADE) class Empresa(models.Model): razao_social = models.CharField(max_length=255) logo = models.ImageField( upload_to=logo_directory_path, default='images/totvs.jpg') I want to create a form that only shows Filial options that are related to the selected Empresa in a previous form field on the same page. Is there an easy way to do this with Django? -
Need Help in a django empty popup
I want to create a popup in a django template but the popup appears empty This is my code so far: <input type="button" value="{{ account.account_id }}" class="btn btn-primary" data-toggle="modal" data-target="#myModal" id="myid"/> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="myModalLabel">Modal title</h4> </div> <div class="modal-body"> <iframe src="{% url 'Trinity:accountinfo'%}?id={{account.account_id}}" width="300" height="380" frameborder="0" allowtransparency="true"></iframe> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> <!-- /.modal --> but if I do the iframe like this : <iframe src="{% url 'Trinity:accountinfo'%}?id=123509817994125" width="300" height="380" frameborder="0" allowtransparency="true"></iframe> It works! But I want that the id to take dinamically not hardcoded. Any idea would appreciate! Thanks! -
Unable to python manage.py migrate successfully
This is the crux of the error: django.db.utils.OperationalError: (1553, "Cannot drop index 'user_id': needed in a foreign key constraint") -
Django displayig logged in user's info doesn't work
I'm using django-registration auth_login to logs in on my website. When user login, he redirects to custom profile page. On this custom profile page I need to display his username,last_name and etc. The question is that, {{user.username}}, {{user.get_username}}, {{request.get_username}}, {{request.user}}, {{request.user.username}} doesn't work(It displays nothing) I really have no idea why this is happening. Every information will be usefull. Thx. -
run celery task only once on button click
I created a django app with a celery task that organises database tables. The celery task takes about 8 seconds to do the job ( quite heavy table moves and lookups in over 1 million lines ) This celery starts through a button click by a registered user. I created a task-view in views.py and a separate task-url in urls.py. When navigating to this task-url, the task starts. My Problem: When you refresh the task-url while the task is not finished, you fire up a new task. With this set-up, you navigate to another page or reload the view How do I prevent the task from firing up each time on refresh and prevent navigating to another page. Ideally, a user can only run one task of this particular type. Might this be doable with JQuery/Ajax? Could some hero point me out in the right direction as I am not an expert an have no experience with JQuery/Ajax. Thanks -
How to make a 3 levels filter menu in Django
I have the following models in django: Category, Sub Category and Product. I am trying to understand how could I make a website, with a form in Django that by Selecting the Category it will only shows the SubCategory under that Category, and by Selecting the SubCategory ony shows the Product in that SubCategory, all in drop-down menus. Any suggestions? I am not really finding anything that tells me how to do it. Thanks -
not navigate to line_chart.html page in django using chart.js?
I am new in django, i need to develop chart based application i am creating line chart using chart.js library i have install pip install django-chartjs INSTALLED_APPS settings: INSTALLED_APPS = ('chartjs',) Create the HTML file Create the view with labels and data definition and also add urls.py file and static files. when i run this application it returns only json data but i want to display chart if any mistake my code.its not navigate to html page. reference link http://django-chartjs.readthedocs.io/en/latest/ -
Django - How to properly send a request to server and ask to run a matlab program?
I have a django web project on a server. I want it to run a matlab code to produce some text file(which will be used later). Here is my code: if(request.method == "POST"): run_octave(Dataset,is_multiclass,require_mapper,mapper,require_aspect_ratio,aspect_ratio) return redirect('meta2db.views.meta2db') def run_octave(dataset,is_multiclass,require_mapper,mapper,require_aspect_ratio,aspect_ratio): origWD = os.getcwd() args = ["octave", "dbEval.m",dataset,is_multiclass,require_mapper,\ mapper,require_aspect_ratio,aspect_ratio] os.chdir(os.path.join(os.path.abspath(sys.path[0]), "../scripts/")) process = subprocess.Popen(args, stdout=subprocess.PIPE) #print(os.listdir("../scripts/results/chruch_street/")) time.sleep(5) for line in process.stdout: time.sleep(0.5) Group("eval_status").send({"text": line.decode('utf-8')},immediately=True) if process.poll() is None: process.kill() else: print(process.communicate()) os.chdir(origWD) I ues a post request to run the octave code with subprocess call. However the matlab code take awhile to be finished and always make the client timeout which is not acceptable. My question is how to solve this kind of problem in another way. A post request seems not a good solution. -
CSV Import Challenges
My CSV file have data field with the following record examples: ColumnA C,17.87491.0E , H,09.9745.9B After data import into SQL Management Studio, each record will split creating multiple column: ColumnA (C ,H) ColumbB (17.87491.0E ,09.9745.9B) Please how can I resolve this ? Can anyone help? -
Upgrade Django installation on AWS elasticbeanstalk
I have a Django 1.9.12 project running on EBS. I'd like to upgrade to Django 1.11 which I've done in the dev environment. How can I force EBS to update to 1.11? I hoped it might be a simple case of updating the requirements.txt but that hasn't worked with eb deploy Would it be easier just to create a new EBS project? -
pass ApiKeyAuthentication in tastype
I am new to tastypie and I am receiving 401 unauthorized error. I thought the headers are automatically pass because of the inclusion of the middleware or am I incorrect? My user is logged in via views.py and a key is generated and stored via tastypie's helper function. Once the user logs in, it gets directed to some page. I go check the api page and it shows unauthorized but if I remove ApiKeyAuthentication I can see my user. In my url it shows localhost:8000/api/user_details there's no user and key info. I've tried including this models.signals.post_save.connect(create_api_key, sender=User) in models.py and in api.py. Same error. api.py class MyResource(ModelResource): user = fields.ForeignKey(UserResource, 'user') class Meta: queryset = MyTable.objects.all() resource_name = 'user_details' authorization = DjangoAuthorization() authentication = ApiKeyAuthentication() list_allowed_methods = ['get', 'post'] def authorized_read_list(self, object_list, bundle): return object_list.filter(user=bundle.request.user) -
How to dynamically filter ModelChoice's queryset in a Inlineformset?
I just want to filter select field in a inlineformset. Scenario: Every task has own report.Each task has a booking .Booking has several booked items.I want to display only related bookeditems based on booking in report form.Report form is generated using signals and while editing i'm using inlineformset to populate form with instances. Here is my code : Models.py class Task(models.Model): booking = models.ForeignKey( Booking, blank=False, null=True, related_name='booking_id',) ...... class Report(models.Model): task = models.ForeignKey( Task, blank=True, null=True, related_name='task',) hoarding = models.OneToOneField( BookedItem, blank=True, null=True, related_name='+') status = models.CharField( max_length=32, choices=ReportStatus.CHOICES, blank=True, null=True, default=ReportStatus.INCOMPLETE) views.py def report(request, pk): task_instance = get_object_or_404(Task, pk=pk) booking = task_instance.booking_id #all bookeditems here bookeditems = BookedItem.objects.filter(Booking_id=bookeditem) # inline formsetfactory ReportFormset = inlineformset_factory(Task,Report,form=TaskReportForm,fields=('hoarding','status',), extra=0,can_delete=False,) data = request.POST or None formset = ReportFormset(instance=task_instance) for form in formset: form.fields['hoarding'].queryset = bookeditems.all() if request.method == 'POST': formset = ReportFormset(request.POST,instance=task_instance) if formset.is_valid(): formset.save return redirect('taskreport') else: formset = ReportFormset(instance=task_instance) else: formset = ReportFormset(instance=task_instance) return render(request, 'report.html', {'formset': formset, 'bookeditems': bookeditems, 'task_instance': task_instance}) forms.py class TaskReportForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(TaskReportForm, self).__init__(*args, **kwargs) class Meta: model = PrinterReport fields = ['hoarding','status',] exclude = ['printer_task',] report.html: <form action="." method="POST">{% csrf_token %} {{ formset.management_form }} <section id="account" class="nice-padding active"> <div class="link-formset"> <table class="listing listing-page"> … -
Controlling PolymorphicModel classed object as model in Generic view
I have a PolymorphicModel class named Vehicle, and I derived two class from this: Car and Truck. I use UpdateView to update but it's getting vehicle_id from vehicle_list randomly. And I have to control which type of vehicle is this model. But I couldn't. My classes: class Vehicle(PolymorphicModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, verbose_name="ID") class Car(Vehicle): car_license = models.CharField(max_length=32) class Truck(Vehicle): truck_license = models.CharField(max_length=32) In view: class VehicleUpdate(UpdateView): car = object if car.car_license is not None: model = Car else: model = Truck fields = '__all__' def get_success_url(self, **kwargs): return reverse_lazy('person-list') But it's giving this error: AttributeError: type object 'object' has no attribute 'tr_id' By the way, I tried to use "isinstance()" but it didn't work. Maybe it's about being PolymorphicModel, I don't know. class VehicleUpdate(UpdateView): if isinstance(object, Car): model = Car else: model = Truck fields = '__all__' def get_success_url(self, **kwargs): return reverse_lazy('person-list') -
Django: UnicodeEncodeError at /admin/structure/type/add/
I have issues when I enter a string with these french characters: é, è, à, etc... I tried two things: The first thing is adding this at the very top of my views.py file: # -*- coding: utf-8 -*- The second thing is adding this to my settings.py file: DEFAULT_CHARSET = 'utf-8' And I still get this error message whenever I enter a string with a special character: Environment: Request Method: POST Request URL: http://10.0.0.238:8000/admin/structure/type/add/?_to_field=id&_popup=1 Django Version: 1.8 Python Version: 2.7.13 Installed Applications: ('apps.structure', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "/home/kaiss/.local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/kaiss/.local/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper 616. return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/kaiss/.local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view 110. response = view_func(request, *args, **kwargs) File "/home/kaiss/.local/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/home/kaiss/.local/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner 233. return view(request, *args, **kwargs) File "/home/kaiss/.local/lib/python2.7/site-packages/django/contrib/admin/options.py" in add_view 1516. return self.changeform_view(request, None, form_url, extra_context) File "/home/kaiss/.local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper 34. return bound_func(*args, **kwargs) File "/home/kaiss/.local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view 110. response = view_func(request, *args, **kwargs) File "/home/kaiss/.local/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func 30. return func.__get__(self, type(self))(*args2, **kwargs2) File "/home/kaiss/.local/lib/python2.7/site-packages/django/utils/decorators.py" in inner 145. return func(*args, **kwargs) File "/home/kaiss/.local/lib/python2.7/site-packages/django/contrib/admin/options.py" in changeform_view 1470. self.log_addition(request, new_object) … -
Function Call in another function not working in django shell
I have a file : def fetchArticles(topic): testing() def testing(): print("testing") print("starting") fetchArticles("World") It is present in a app in django and when i run it as a standalone file using python3 xyz.py it runs perfectly fine but when i run it in django shell using python3 manage.py shell < xyz.py it is not able to locate the testing function. It shows this error : starting Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/shell.py", line 101, in handle exec(sys.stdin.read()) File "<string>", line 12, in <module> File "<string>", line 4, in fetchArticles NameError: name 'testing' is not defined Can anyone help me to resolve this issue ? -
"detail : Invalid signature ." in JWT
I have created login/register API using DRF and JWT token. The api works fine, it generates the token. Now I have another app that provides a capability to add notices to authenticated users only. When I try to test, I supply the header as Authorization JWT <token> in postman, but I get the following as the error: "detail : Invalid signature ." I even checked the token here https://jwt.io/, it shows signature verified. Now I am unable to detect the problem. I surfed all through the internet but no luck. Please anyone can help me out with this. For full api you can see it in github here, and suggest me if I am wrong anywhere. views.py class AddNotice(APIView): permission_class = (AllowAny,) serializer_class = AddNoticeSerializer def post(self, request, format=None): data = request.data serializer = AddNoticeSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data return Response(new_data) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) serializers.py class AddNoticeSerializer(serializers.ModelSerializer): class Meta: model = Api fields = ('id', 'notice_name', 'notice_desc', 'notice_author', 'notice_valid_till', 'notice_publish_date') def create(self, validated_data): return Api.objects.create(**validated_data) def update(self, instance, validated_data): instance.notice_name = validated_data.get('name', instance.notice_name) instance.notice_desc = validated_data.get('category', instance.notice_desc) instance.notice_author = validated_data.get('subcategory', instance.notice_author) instance.notice_valid_till = validated_data.get('subcategory', instance.notice_valid_till) instance.notice_publish_date = validated_data.get('subcategory', instance.notice_publish_date) instance.save() return instance -
how to generate pdf for business card using python?
i enter image description herewant to generate pdf for business ID card using django -
File Uploading Using Alfresco and Django Python
We are developing an application using Django1.11 (Python 3.6) and Angular 4. We want to develop our system in such a way that all types of files, documents etc. will be saved to Alfresco using Alfresco API. We do not have so much knowledge in integrating the alfresco API system. How the API authentication process works etc. And We are little bit confused how to call the API and about the integration process. If anyone can guide us to a proper way, the help will be appreciated. Thank you so much.