Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Get for hidden field 2 values
My request.POST looks like 'hidden': ['testtest', ''],, but i want to get'hidden': ['jhjj,,,mh,jhj,h'],. What could be the reason for it? forms.py: hidden = forms.CharField(required=False, max_length=50, widget=forms.HiddenInput(attrs={'id': 'hidden'})) I use javascript to emit the hidden field a value. $('#id_field1').keyup(function() { var group_name = $("#id_field1").val(); $("#hidden").val(groupt_name); var x = $("#hidden").val(); }); -
Wagtail RichTextField toolbar customisaton
I am using RichTextField in a wagtail model. The wagtail version I am using is 1.9.1 along with Django 1.8.5. I have tried this to customise the toolbar. But when I tried to follow the steps in the link, I am getting the below given error, virtual/wagtail/local/lib/python2.7/site-packages/wagtail/wagtailcore/blocks/stream_block.py", line 211, in get_prep_value for child in value # child is a BoundBlock instance AttributeError: 'unicode' object has no attribute 'block'. I coudn't figure out why it is raising such an error response. I would be appreciated if someone give a helping hand to figure out the issue. -
Django migration error: has no field named u'DO_NOTHING'
I've been trying to add a foreign key to my models in Django 1.9 with the option on_delete='DO_NOTHING' per instructions on Django Docs, but for version 1.10. I ran python manage.py makemigrations without any problems but when I tried to run python manage.py migrate of course I got the error: django.core.exceptions.FieldDoesNotExist: Entrance has no field named u'DO_NOTHING' Realizing my mistake, I changed the option to on_delete=models.DO_NOTHING and ran makemigrations and migrate again but I'm still getting the same error: django.core.exceptions.FieldDoesNotExist: Entrance has no field named u'DO_NOTHING' Looks like something is wrong in migration files. Not too familiar with internal workings of Django so I don't know where to look to fix this. Any ideas? -
displaying different records depending on the parent tab clicked django
I have two tabs my parent tab contains a list of cars, my child tab contains car details, performance, offers, I am trying to display different data depending on which of the parent tabs is displayed. expected results parent tab car one | car two child tab car details | performance | offers results display here tabs.html parent tab <ul class="nav nav-tabs"> {% for car in cars %} {% if forloop.first %} <li class="active"><a href="#carDetails" data-toggle="tab">{{car.name}}</a></li> {%else%} <li><a href="#carDetails" data-toggle="tab">{{car.name}}</a></li> {%endif%} {%endfor%} </ul> child tab <ul class="nav nav-tabs"> <li class="active"><a href="#carDetails" data-toggle="tab">Car Details</a></li> <li><a href="#performance" data-toggle="tab">Performance</a></li> <li><a href="#offers" data-toggle="tab">Offers</a></li> </ul> for loop {% for car in cars.id %} <tr> <td class=" vertical-center"> <a href="">{{ car.name }}</a> </td> </tr> {% endfor %} -
django get existing objects and update m2m
models.py class PhoneNumber(models.Model): person = models.ManyToManyField(Person, related_name='phonenumbers', blank=True) employee = models.ManyToManyField(Employee, related_name='phonenumbers', blank=True) phone = models.CharField(max_length = 20) For check exist phone I tried create save() method for PhoneNumber model: def save(self, *args, **kwargs): #check if phone exists exist_phone = PhoneNumber.objects.filter(phone=self.phone).last() if exist_phone: new_people = self.person if new_people: for person in new_people: exist_phone.person.add(person) new_employees = self.employee if new_employees: for employee in new_employees: exist_phone.employee.add(employee) else: super(PhoneNumber, self).save(*args, **kwargs) It doesn't work because an error occurs: "<PhoneNumber: >" needs to have a value for field "phonenumber" before this many-to-many relationship can be used. But I want get existing object and add new value for m2m. How do i get values from posted m2m fields? Is there are possible to realize it in model? -
form wizard does not move to the next screen in a jquery dialog
I an using django-crispy forms and using that in a jquery dialog box to show a form wizard. the problem that I am facing is that when used in the dialog box the wizard never moves to the next screen. So, my wizard is defined as follows: class ContactWizard(SessionWizardView): def get_template_names(self): return "reviewdialog.html" def done(self, form_list, **kwargs): return HttpResponseRedirect('index') And the template is defined as: {% load crispy_forms_tags %} {% load i18n %} {% block content %} <form action="." method="post"> {% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {% crispy form %} {% endfor %} {% else %} {% crispy wizard.form %} {% endif %} {% if wizard.steps.prev %} <button name="wizard_goto_step" value="{{ wizard.steps.first }}">{% trans "first step" %}</button> <button name="wizard_goto_step" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button> {% endif %} </table> <input type="submit" class="btn btn-success" value = "NEXT"> </form> {% endblock %} Now, I show this in a jquery dialog where I have overridden the submit method to ensure that the dialog does not close on clicking the 'NEXT' button <script> function EditDialog(pk) { $.ajax({ url: "{% url 'populatereviewform' %}", method: 'GET', data: { pk: pk }, success: … -
Django admin list_display_links to foreign key
I am using Django 1.10. In the admin is there an option to set links on Foreign Keys such that when it gets clicked the page is redirected to the Foreign key object. -
Django - refresh database
This is part of my admin.py file: class InactiveSite(Site): class Meta: proxy = True verbose_name_plural = 'Inactive sites (' + str(Site.objects.filter(is_active=False).count()) + ')' class InactiveSiteAdmin(admin.ModelAdmin): list_display = ('is_active', 'name', 'description', 'keywords', 'date') fields = ('name', 'url', 'category', 'subcategory', 'category1', 'subcategory1', 'description', 'keywords', 'date', 'group', 'is_active') readonly_fields = ('date',) list_editable = ('is_active',) list_display_links = ('name',) list_filter = ('is_active',) def get_queryset(self, request): return Site.objects.filter(is_active=False) When I change site from inactive to active in my django admin it doesn't reload my database. There is still "Inactive sites (3)" for example. When I close my serwer and run it again everything is ok ("Inactive sites (2)" for example). How can I fix that? -
Django: Cannot assign object: "VoterCode.region" must be a "Region" instance
I am quite new at Django, and I am trying to make a form with a foreign key. I take only one foreign key from the form, and I assign the rest of the values. I understand I am trying to save an object, not an instance. I thought that a query is getting a collection of instances (a query set of instances), and even if it has only one element I have to always take the first. This is what I tried to do, but it did not work: return Region.objects.filter(name = region_name)[:1].get() Here is my form: class VoterCodeForm(forms.ModelForm): election = forms.ModelChoiceField(queryset=Election.objects.all(), empty_label="Select an election") class Meta: model = VoterCode fields = ('election',) Here is my view: def populate_voter_codes(request): if request.method == "POST": form = VoterCodeForm(request.POST) if form.is_valid(): election = form.instance.election form.save(commit=False) VoterCode.populate_voter_codes(election) return redirect('elections') else: form = VoterCodeForm() return render(request, 'admin_interface/populate_voter_codes.html', {'form': form}) Here is how I save the values: def postcode_to_region(postcode): ...some processing... return Region.objects.filter(name = region_name)[:1].get() def populate_voter_codes(the_election): data = requests.get(url = "http://t2a.co/rest/?output=json&method=person_search&api_key=test").json() data = data["person_list"] i = 1 for person in data: voter_code = VoterCode.generate_voter_code() #print(person["postcode"]) region = VoterCode.postcode_to_region(person["postcode"]); entry = VoterCode(id=i, code=voter_code, election = the_election, region = region) entry.save() i += 1 Thanks for … -
Django: Retrieve Celery taskresult.result saved as a list
I'm trying to access the results of my TaskResult object using django_celery_results. My results is a 2d list, wherein my goal is to save the logs of three (3) programs there, after running them in the tasks. I run it and had errors when trying to access the results contents. I saw posts about saving into fields containing lists as json, but I wasn't able to do that. When I looked up on the mysql table of it, result field was saved longtext and now, I don't know how to truly access it. in tasks.py: program1_process = subprocess.Popen((prog1_args), stdout=subprocess.PIPE, stderr=subprocess.PIPE) prog1_process.wait() prog1_out, prog1_err = prog1_process.communicate() prog1_dict = {'output_log': prog1_out, 'error_log': prog1_err} """ For the second and third subprocesses These are in a for loop so there are many times they will be run, that's why I used a list """ process_list = list() submit_p = subprocess.Popen((submission_args), stdout=subprocess.PIPE, stderr=subprocess.PIPE) process_p = subprocess.Popen((processing_args), stdout=subprocess.PIPE, stderr=subprocess.PIPE) submit_p.wait() process_p.wait() sub_out, sub_err = submit_p.communicate() process_out, process_err = process_p.communicate() process_dict = { 'name': name, 'submit_out_log': sub_out, 'submit_err_log': sub_err, 'process_out_log': process_out, 'process_err_log': process_err, } process_list.append(process_dict) combined_list = [[prog1_dict], []] combined_list[1].extend(process_list) return combined_list Testing in the shell: from django_celery_results.models import TaskResult result = TaskResult.objects.all() for res in result: … -
Dict: get() not returning 0 if dict value contains None
python dict if a key having value None and when called get() returns NoneType ex_dict = {"test" : None} ex_dict.get('test', 0) In above example it should return 0 but it wont. Can any explain why it behave like that. -
Record in the model field
I make an auction site. There is a model Lot class Lot(models.Model): class Meta: db_table = 'lot' lot_created_date = models.DateTimeField(default=timezone.now) lot_author = models.ForeignKey('auth.User', default='1') lot_name = models.CharField(max_length=100,) lot_description = models.TextField(default='',) lot_start_price = models.CharField(max_length=100, default=100) lot_last_bet = models.CharField(max_length=1000, default='', blank=True) def __unicode__(self): return self.lot_name When printed in a template, each lot has a button "bid". How to record in the field "lot_last_bet"(Login of the user who made the bet) when you click the "bid"? -
How can i get object_list in django middleware
I am writing one middleware class to handle pagination in django. I am getting issue when user delete entry in ListView and page number is lost. So, i have to check how many pages for that request and adjust page number to reduce issue 404 error. I can get ClassBase Name, model name but cant get object_list data. my code is: url = request.path resolver_match = resolve(url) func = resolver_match.func module = func.__module__ view_name = func.__name__ clss = get_class( '{0}.{1}'.format( module, view_name ) ) I want to count the current page of that request. Please suggest to get it. Thanks, ThanhTruong -
Returning filtered objects(list or queryset)
I need to filter some data in django rest framework filter. I have models: class A(models.Model): ... connections = models.ManyToManyField(classB) .... class B(models.Model): ... date_added=models.DateTimeField() .... I need to return classA objects with filtered connections. For example: classA objects has many connections with different date_added field. I need to return classA objects with connections, but connections should be only from specified date. (classA objects can contains different connections, but if it have connection from specified date, I need to return object from classA, containing connection which meet the condition, excluding connections which not meet that condition). Is there any way to do it? -
How to Initialize the value for the variable when runserver Django website thyon
I have a dictionary.txt file represented as {{key: value}}. I built a dictionary translation web so I wanted to initialize a variable whose data dictionary type is in python for storing. I use the django framework to process. Here is my dictionary reader. def read_dictionary(fileName): dict = {} my_dict = {} with open(fileName, 'r', encoding="utf8") as f: for line in f: items = line.split(':') key, values = items[0].replace('X', '*'), items[1].strip().replace('\n', '') dict[key] = values for k, v in dict.items(): my_dict.setdefault(v, []).append(k) return my_dict How can I initialize variable my_dict = value from dictionary file and I can it in myapp folder ? Thank you. Do I need to create a model object and save it under the database? -
Django: CSRF verification fails
I am using Django 1.8.6 and python 3.6 to create a blog. Encountered with csrf verification error. I have used the {% csrf_token %} in my html template. My view.py is def post_detail(request, year, month, day, post): post = get_object_or_404( Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) comments = post.comments.filter(active=True) if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() else: comment_form = CommentForm() return render(request, 'blog/post/detail.html', { 'post': post, 'comments': comments, 'comment_form': comment_form }) I am quite new to Django. I thank you in advance for the time and effort spent.It would of great help if you help me out. -
Path to remote storage in Django / Apache application
I'm trying to access to file / directories on a remote storage, in a Django Application. My webserver is Apache, and both virtual machine and storage are hosted by Windows Azure. I want to do it both from Python and encapsulated C++ code, by example creating an empty file in Python. open("\\\\samples.file.core.windows.net\\share\\file.ext","a").close() (see this link for the path : https://docs.microsoft.com/fr-fr/azure/storage/storage-python-how-to-use-file-storage). When using this path under Apache, it fails with IOError : invalid mode ('a') or filename: '\\\\\\\\digitalstructurestorage.file.core.windows.net/ Adding http and https as prefix does't help, when not escaping the slashes, it writes the file on the C: drive of the virtual machine. open("\\samples.file.core.windows.net\\share\\file.ext","a").close() However, when connecting in RDP to my virtual machine, I can successfully write the file. I believe there's something to add in Apache / MOD_Wsgi configuration to correct this behaviour, but I could not found documentation about it. I also precise that I've to provide path as input to some functions of 3rd party librairies, that's why I'd like to avoid Windows Azure API or any higher level API to manage the Input/Output. Thx in advance for your assistance. -
Django save multiple user types
I am new to Django and would like to do a registration page for my web application. Currently, I need two types of Users (Student and Instructor). I have a checkbox for the user to select if they are student or instructor in my RegistrationForm. I would like to know that under my RegistrationForm, how do I save them into Student or Instructor table respectively under the save() method? register.py class RegistrationForm(forms.ModelForm): email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder': 'Email'}), label='') password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'}), label='') password2 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password'}), label='') INSTRUCTOR = "INS" STUDENT = "STU" roles_choices = [(INSTRUCTOR, "Instructor"), (STUDENT, "Student")] role = forms.ChoiceField(choices=roles_choices, widget=forms.RadioSelect(), label='') class Meta: model = User fields = ['email', 'password1', 'password2'] def clean(self): """ Verifies that the values entered into the password fields match NOTE: Errors here will appear in ``non_field_errors()`` because it applies to more than one field. """ cleaned_data = super(RegistrationForm, self).clean() if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: if self.cleaned_data['password1'] != self.cleaned_data['password2']: raise forms.ValidationError("Passwords don't match. Please enter both fields again.") return self.cleaned_data def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.set_password(self.cleaned_data['password1']) user.set_role(self.cleaned_data['role']) if commit: user.save() return user models.py class User(AbstractBaseUser): role = models.CharField(max_length=3) email = models.EmailField(max_length=100, primary_key=True) first_name = models.CharField(max_length=30, null=False) last_name … -
How can I easily send a preview email for a Campaign Monitor template?
I already migrated some of our own email templates into Campaign Monitor's system. I'd like to write a routine to send a preview email for a selected template. I'm using Python (https://github.com/campaignmonitor/createsend-python). Looks like that I have to create a campaign which has a send_preview https://github.com/campaignmonitor/createsend-python/blob/master/createsend/campaign.py#L87 function. However I'd need to create a list also in order to have a campaign object only for this preview purpose. This feel like unnecessary / awkward. I feel like I'm tumbling down a rabbit hole. Is there a simpler way to send a preview email? -
Django admin, filter by timestamp range
I have a model with these attributes: class MyModel(models.Model): name = models.CharField(max_length=250, blank=False, null=False) timestamp = models.BigIntegerField(default=0) def save(self, *args, **kwargs): self.timestamp = get_timestamp_in_milli() super(MyModel, self).save(*args, **kwargs) In my admin.py I have declared AdminModel with this model: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): pass Is there any calendar like filter, where I can filter range of my timestamp? If yes how to include it? I know that there is also filter based on DateField, is it possible to make timestamp filterable as DateFiled? -
What type of DB should I use for a web based forum?
I'm developing a web based QnA forum in Django , which DB would be best for this , should I go for a NoSQL DB like MongoDB or should I stick with SQLite? -
Upload video to amazon s3 using django and python
All i am trying is to upload a video to amazon s3 instead of saving in media as django does regularly. So created a below model def upload_to_amazon_s3(instance, filename): aws_access_key_id = settings.AWS_ACCESS_KEY_ID aws_secret_access_key = settings.AWS_SECRET_ACCESS_KEY file_name = 'videos/{0}_{1}/{2}'.format(instance.user.id, instance.user.username, filename) conn = boto.connect_s3(aws_access_key_id, aws_secret_access_key) try: bucket = conn.get_bucket("ipitch_videos", validate=True) except S3ResponseError: bucket = conn.create_bucket('ipitch_videos') #Get the Key object of the bucket k = Key(bucket) #Crete a new key with id as the name of the file k.key=file_name #Upload the file result = k.set_contents_from_file(instance.video_file) # we need to make it public so it can be accessed publicly # using a URL like http://s3.amazonaws.com/bucket_name/key k.make_public() get_s3_obj = Key(bucket,file_name) endpoint_url = get_s3_obj.generate_url(expires_in=0, query_auth=False) return endpoint_url class Video(DateTimeModel): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255) video_file = models.FileField(upload_to=upload_to_amazon_s3) I am getting the endpoint_url value from amazon s3 Url for example as https://ipitch_videos.s3.amazonaws.com/videos/1_username/super.mpg So when i upload a video with from front end form or an API with all fields user, name, video_file, a record is being created in to the database successfully but the following three problems occur Video record instance is saving but splitting / after https:// from endpoint_url that comes from amazon and using only https:/ instead of https:// as below Along … -
Searching for files with common wor
In a Django project, I would like to highlight files with certain words. For instance, I'm looking for files having word1 and word2. I know I could use grep -ri --colour 'word1' Project/** to find all files with the word word1. After, we could use the same files to search for word2. The purpose is to obtain the files. Could anyone have an idea how I could do such thing? Thanks! -
Django middleware functioning
The middleware code below is not showing error but its not logging out after 5 minutes.How will this code in middleware continously check if inactive time is greater than 5 minutes..The middleware gets executed only before and after the request is called right?? settings.py SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' The above sample of serializer is for Django 1.6. Kindly search for other version. Thanks... Create middleware.py from datetime import datetime, timedelta from django.conf import settings from django.contrib import auth class AutoLogout: def process_request(self, request): if not request.user.is_authenticated() : #Can't log out if not logged in return try: if datetime.now() - request.session['last_touch'] > timedelta( 0, settings.AUTO_LOGOUT_DELAY * 60, 0): auth.logout(request) del request.session['last_touch'] return except KeyError: pass request.session['last_touch'] = datetime.now() Update your settings.py: MIDDLEWARE_CLASSES = [ ......................... 'app_name.middleware.AutoLogout', ] Auto logout delay in minutes AUTO_LOGOUT_DELAY = 5 #equivalent to 5 minutes -
django - count() if not find result it returns Nonetype
I trying to get count of record from xyz table but it returns NoneType. IF there is no record found it should return 0 lets say, ABC.objects.filter(abc.name="test").count() Can anyone help me to get out of Nonetype.