Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I translate django admin form labels?
I have a django project using django modeltranslation to do translation for my models' names. In this case, I have name_en and name_zh_hans. As shown, I am able to translate the word 'name' into chinese but not the auto generated '[en]' and '[zh-hans]' part of the label. I've look through the django's and modeltranslation's documentation but still couldn't figure it out. Have anyone met with the same problem and manage to resolve it? -
Django List View is not giving any value in Debian Apache Server with get_queryset
I have deployed a django app in Debian/Appache server. List cbv is not showing the out put, but working locally, if I remove the get_queryset method it is working, so how I can put a filter with request.user element. Thank you. List View is as follows class MeetingList(LoginRequiredMixin, ListView): model = Meeting queryset= Meeting.objects.all() paginate_by = 5 def get_queryset(self): return self.model.objects.filter(user=self.request.user).order_by('-id') -
Data migration of image model
Hi this is mostly a copy paste of a question asked in Google groups: Thanks to Wagtail docs, I was able to understand how to build a custom image model, BUT, as I have a website with more than 500 contents, I don't want to mess the whole thing up with a bad data migration. In fact, I am not sure of which migration operation I should use here. I think that I should this one: https://docs.djangoproject.com/en/1.8/ref/migration-operations/#altermodeltable Can someone confirm this ? Thanks a lot Regards -
Is it possible for a template argument to equal the value of another element?
<h1 class="profile_username"></h1> <a href="{% url 'profile' user= %}"></a> h1 will be dynamically populated with a value, so is it possible for the user argument to equal the value of the h1 class? -
always serializer is invalid
models.py class Profile(models.Model): firstname = models.CharField(max_length=100,null=True,blank=True) lastname = models.CharField(max_length=100,null=True,blank=True) city = models.CharField(max_length=100,null=True,blank=True) state = models.CharField(max_length=100,null=True,blank=True) # . . . other fields views.py profile = Profile.objects.get(id=1) serializer = LenderProfileSerializer(profile,data=request.data) if serializer.is_valid(): serializer.save() serializers.py class LenderProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = [ 'firstname', 'lastname', 'city', 'state' ] this is my code for example ,i am trying to fill only some fields and so i gave serializer = LenderProfileSerializer(profile,data=request.data) still it is giving invalid -
Django precise_bbcode not properly parsing contents of [code] tags?
I just installed precise_bbcode in my Django application. When I provide the string: >>> s = """ [code] for i in var: print(var[i]) [/code] """ the output is just plain text: for i in var: print(var[i]) However if I change the [i] to [i2] it works fine and formats the text as expected. I am guessing that precise_bbcode thinks [i] has something to do with italic text (even though it is surrounded by [code] tags and the [i] has no associated closing tag). This behavior is also present for [b] and probably any other recognized tag I then I tried setting the option render_embedded = False but I still get the same behavior. I then tried making my own "code" tag: from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import HtmlFormatter class PygmentsBBCodeTag(BBCodeTag): name = 'code' class Options: strip = False replace_links = False render_embedded = False transform_newlines = False escape_html = False def render(self, value, option=None, parent=None): print(value) return highlight(value, PythonLexer(), HtmlFormatter()) tag_pool.register_tag(PygmentsBBCodeTag) And got the same result. Stranger still, in my PygmentsBBCodeTag class whenever the [i] exists I notice that it is never called (as the value is not printed). Is there any way to tell … -
Override a validation check in Django Rest with ModelSerializer
I went to through related questions and didn't find any solution. View class TestList(viewsets.ModelViewSet): serializer_class = TestSerializer queryset = Test.objects.all() Model class Location(models.Model): latitude = models.CharField(max_length=100) longitude = models.CharField(max_length=100) class Test(models.Model): video_id = models.CharField(max_length=100) location = models.ForeignKey(Location) Serializer class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = ('latitude', 'longitude') class TestSerializer(serializers.ModelSerializer): def validate_location(self, data): if type(data['location']) == dict: if not (type(data["location"]["latitude"]) == str and len(data["location"]["latitude"]) < 100): raise serializers.ValidationError("Latitude field error") if not (type(data["location"]["longitude"]) == str and len(data["location"]["longitude"]) < 100): raise serializers.ValidationError("Longitude field error") else: raise serializers.ValidationError("Wrong type") return data def create(self, validated_data): print validated_data loc_details = validated_data.pop('location') location = Location.objects.create(**loc_details) return Test.objects.create(location=location, **validated_data) class Meta: model = Test fields = ('video_id', 'emotions', 'location') The ModelSerializer of Test expects location field as pk. But i want to recieve a latitude longitude fields and create a Location object before saving Test model. Post request format { "video_id": "sdasd", "location": {"latitude":"52.345","longitude":"56.756"} } I want to take the location details, create location object and then pass that to Test model. I wrote custom validation and tried to override the "Expected pk value error". But its not working. How to override the validation error ? -
Does Django (w/ MySQL) do only 1 table lookup or multiple when counting with CASE
Lets say we have a model of the form class Person(models.Model): is_gay = models.BooleanField() is_tall = models.BooleanField() is_nice = models.BooleanField() ... Now lets say we want to know how many people we have meeting different criteria. We can achieve this by counting them num_gays = models.Person.objects.filter(is_gay=True).count() num_tall_and_nice = models.Person.objects.filter(is_tall=True, is_nice=True).count() Unfortunately, this would need 2 database queries. As you can imagine, as the number of types of people grows large, (e.g. an enumeration of 25/30) this can slow down quite a lot. So now we can optimize by instead using aggregations aggregations = {} when = models.When(is_gay=True, then=1) case = models.Case(when, output_fields=models.IntegerField()) sum = models.Sum(case) aggregations['num_gays'] = sum when = models.When(is_tall=True, is_nice=Ttrue, then=1) case = models.Case(when, output_fields=models.IntegerField()) sum = models.Sum(case) aggregations['num_tall_and_nice'] = sum result = models.Person.objects.aggregate(**aggregations) However, I am curious as to how Django (using MySQL) processes this query. Does it look at the table only once, and each time it looks at a row, it adds 1 to every single CASE statement that applies. Or does it look at the table N times where N is the number of CASE statements? -
multiple file in django - in single input field - dropzone js
I am using dropzone js to upload multiple file at a time. In the following code I am using session to store the file. if request.FILES: if 'tracks' not in request.session['multitrack']: request.session['multitrack']['tracks'] = {} request.session['multitrack']['tracks']['track_count'] = 1 request.session['multitrack']['tracks']['track_count'] = request.session['multitrack']['tracks']['track_count'] + 1 filetrack = request.FILES.get('file', None) fs = FileSystemStorage() multitrack_name = fs.save(filetrack.name, filetrack) multitrack_url = fs.url(multitrack_name) request.session['multitrack']['tracks'][track_count] = {} request.session['multitrack']['tracks'][track_count]['file_url'] = multitrack_url multitrack_filename_split = multitrack_url.split('/') multitrack_filename = urllib.unquote(multitrack_filename_split[-1]) request.session['multitrack']['tracks'][track_count]['file_name'] = multitrack_filename request.session['multitrack']['tracks'][track_count]['file_size'] = filesizeformat(filetrack.size) return HttpResponse(track_count) I am using track_count as a key to store the track details. When i upload two or more files at a time the count is not incremented. The multiple files are stored in FileSystemStorage but the count has not incremented as per the uploaded files. Please help me to find out the bug. else please tell me do i need to change the logic or any mistake in it. Please ask me if you have any doubts in my question i posted if anyone not able to understand. -
rewriting part of urls using django
I have a url like www.example.com/events/A/ www.example.com/events/B/ etc I would like to change that to www.example.com/portal/A/ and likewise. This can be achieved at Apache level, but can I do it in django using some middleware or something. I have tried using RedirectView like this url(r'events/', RedirectView.as_view(url='/portal/')), But that just stops at /portal and anything after the events/ is ignored. Is there a way to do this in django -
The meaning of that loop
{% if request.GET.next %} <input type="hidden" name="next" value="{{ request.GET.next }}"> {% endif %} In the following code, I don't understand what is the meaning of request.GET. Could anyone have time to explain to me the meaning of that? In fact, if anyone could explain to me the whole loop, it should be appreciate. -
Django MySQL on a different database
So for example, here are the databases that are set in my settings.py file. DATABASES = { 'default': { 'NAME': 'app_data', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'postgres_user', 'PASSWORD': 's3krit' }, 'my_blog': { 'NAME': 'my_blog', 'ENGINE': 'django.db.backends.mysql', 'HOST': '192.168.1.40', 'USER': 'mysql_user', 'PASSWORD': 'priv4te' } } I need to get some information from my_blog database. I do not have write permissions to this database, I only need to perform simple select queries. How do you suggest I do it? -
Which design pattern Django follows and which design pattern we should follow while development using Django?
I eager to know that which design pattern Django follows and if Django is not using any design pattern then which one we should use? I searched it thoroughly and didn't get any suitable answer for same so can anyone please clear it? Thanks in advance. -
ElementTree CDATA is not showinig
I am new in XML and Python. I am using a VAST XML and i want the Text in CDATA only but when i am taking the text values through ElementTree it remove the CDATA from it. import xml.etree.ElementTree as ET import urllib xml_tree1 = ET.ElementTree(file=urllib.urlopen('https://pubads.g.doubleclick.net/gampad/ads?sz=640x480&iu=/124319096/external/single_ad_samples&ciu_szs=300x250&impl=s&gdfp_req=1&env=vp&output=vast&unviewed_position_start=1&cust_params=deployment%3Ddevsite%26sample_ct%3Dskippablelinear&correlator=')) vast = xml_tree1.getroot() ad=vast.find('Ad') impression=inline.find('Impression') impression.text it shows: https://securepubads.g.doubleclick.net/pcs/view?xai=AKAOjsvgy0lSG91sfq6V74Ggq2Z62Crvop2FqEF7KV5JNYSIthyZcloXkw_oETJoQXvd5d0bnACmvRfWVBIhr40FLGT1umFX1-G6M5Wigd-vKELUANHVHg5GKZ4wxPbGgaMIWjbNpwTd4PcNHCxGAYSmEuDdMf2EPwV63VdCMirwZ1wBjE9tYMweV-Xydomz1owiwv0xrs8iTY8dCJSZSVW8yVbID7FltN7PgfLqWkmcl7roTw&sig=Cg0ArKJSzKSde3F8SSDAEAE&adurl= CDATA has been removed from this URL, I don't want to parse the whole XML and append CDATA one by one in all the text. I want to return response in XML. Thanks in advance. -
Interfacing arduino and web application using python
I am doing a project which requires interfacing a html/css based interface to Arduino board, The Arduino will be connected to the computer via USB provided and it will also have some sensors like accelerometers etc. As I am familiar with Python, I was planning on using it for the same(for the interfacing). I don't have any knowledge regarding Arduino or what interfacing framework can be used, so, it will be really helpful if you guys provided some suggestions regarding the same and some sources for learning about Arduino and frameworks will also be greatly appreciated. -
how to update OneToOneField / ForeignKey using ViewSet? Django
I am currently using restful and serializers to create and update my user. Somehow I am not able to update some of the fields if the field has to do with OneToOneField / ForeignKey. in my models.py, my Student is actually connected to the django build in user model which includes the user's email and connected to the school model which has the name of the school class Student(Model): user = OneToOneField(settings.AUTH_USER_MODEL, on_delete=CASCADE) date_of_birth = DateField(blank=True, null=True) student_name = CharField(max_length=256) school = ForeignKey(School, on_delete=CASCADE, related_name="%(class)ss", related_query_name="%(class)s", blank=True, null=True) in serializer.py I have class StudentSerializer(ModelSerializer): user_email = SerializerMethodField() school_name = SerializerMethodField() class Meta: model = Student fields = ( 'user_email', 'student_name', 'phone', 'school_name') def get_user_email(self, obj): return obj.user.email def get_school_name(self, obj): return obj.school.school_name def create(self, validated_data): return Student.objects.create(**validated_data) def update(self, instance, validated_data): instance.user.email = validated_data.get('user_email', instance.user.email) instance.student_name = validated_data.get('student_name', instance.student_name) instance.phone = validated_data.get('phone', instance.phone) instance..school.school_name = validated_data.get('school_name', instance..school.school_name) instance.save() return instance in my view.py update function class UserViewSet(ViewSet): queryset = Student.objects.all() def update(self, request, pk=None): student = get_object_or_404(self.queryset, pk=pk) serializer = StudentSerializer(student, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response({'status': True}) return Response({'status': False, 'message': serializer.errors}) I am able to use the API view to pass in json and update the student_name … -
Splinter with Django client won't parse requested webpage
all! Im having a little trouble setting up Django properly with Splinter. Here's the code: from splinter import Browser import django django.setup() browser = Browser('django') browser.visit('http://google.com') browser.html What the following code should yield is the source for google.com. However, it returns the source for Django's 'Welcome to Django' test page. How do i get django to properly connect to google.com and return the source? I'm running this on Mac OS X 10.1, Django 1.10.1, & Python 3.6 -
Django doesn't pass correct template field when it's nested inside a position: fixed div
When I use the code below: <p class="new_profile"><a href="{% url 'profile' u=i.user %}">{{i.user}}</a></p> i.user works fine. But when I wrap it around a position: fixed div: <div class="profileWrapper"> <p class="profile_posts"><a href="{% url 'profile' u=i.user %}">{{i.user}}</a></p> </div> It's incorrect. The div is initially display: none then display block via JS. Both of these are inside a profile.html template that is included to another comments.html template: {% for i in comment_list %} <div class='comment_div'> <div class="left_comment_div"> <h3><a class='username_foreign'>{{ i.user }}</a></h3> {% include 'profile.html' %} <br> <p>{{ i.comment_text }}</p> </div> </div> {% endfor %} I need to use position: fixed here, so is there any other way I can achieve it? -
Fetching profile picture info
while i am trying put login with google in my django web framework , the username in the gmail fetched using "Hello {{ user.get_full_name|default:user.username }}!" in my home.html file and my question is to how can i get the profile picture of my gmail account in the same html? -
NameError at /accounts/regist_save/
I got a error, NameError at /accounts/regist_save/ global name 'Token' is not defined. I think my app do not have necessary things,so I add from rest_framework.authtoken.models import Token into models.py and rest_framework.authtoken into settings.py. But in that time,there are many error in my console,so I deleted them. So,what should I do to fix this error? I wrote in views.py, @login_required def profile(request): context = { 'user': request.user, } return render(request, 'registration/accounts/profile.html', context) def regist(request): form = RegisterForm(request.POST or None) context = { 'form': form, } return render(request, 'registration/accounts/regist.html', context) @require_POST def regist_save(request): form = RegisterForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('registration/accounts/profile.html', context) context = { 'form': form, } return render(request, 'registration/accounts/regist.html', context) in models.py from django.db import models from django.dispatch import receiver from django.db.models.signals import post_save from django.conf import settings # from rest_framework.authtoken.models import Token # Create your models here. @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) in urls.py from django.conf.urls import url from . import views from django.contrib.auth.views import login, logout urlpatterns = [ url(r'^login/$', login, {'template_name': 'registration/accounts/login.html'}, name='login'), url(r'^logout/$', logout, name='logout'), url(r'^regist/$', views.regist,name='regist' ), url(r'^regist_save/$', views.regist_save, name='regist_save'), ] -
How should I write tests for my Forms in Django?
Have anyone idea how should I write unit test for this form : class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField( choices=PRODUCT_QUANTITY_CHOICES, coerce=int) update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) -
Book Structure in Django
I am currently trying to implement a book structure in Django in the model. The structure is as follows Book Class: title pages (this is an array of page objects) bibliography (a dictionary of titles and links) Page Class: title sections (an array of section objects) images (array of image urls) Section Class: title: text: images (array of image urls) videos (array of video urls) I am pretty new to Django and SQL structuring. What my question specifically is, what would be the best method in order to make a db with books where each entry has the components listed above? I understand that the best method would be to have a table of books where each entry has a one to many relationship to pages which in turn has a one to many relationship with sections. But I am unclear on connecting Django models together and how I can enable lists of objects (importantly these lists have to be dynamic). -
Error while importing function from a module in django webapp
I am new to python and django and was trying to make a basic webapp and while doing that, i wanted to add some helper functions in a separate folder inside my app folder. The structure is : app utils testFile.py migrations static urls.py views.py .... .... My testFile.py has one function for now def testFunc(): print("IT WORKS") I am calling it my views.py from testFile import testFunc and tried the following too from utils.testFile import testFunc but none of them worked. After that I checked for directories in which python is looking into using sys.path, and utils wasn't there, so I added it using sys.path.insert(), but that doesn't work too. It keeps giving the no module named testFile error I tried creating two simple python files and calling function of one from the other, it works there. So only while I am using in my django webapp, the error is coming. What am I doing wrong here? -
ChoiceField doesnt get initial value when submitting a form using post
for a week I m trying to find a solution but all I tried didnt work. I have this form: class QuestionForm(forms.Form): def __init__(self, question, default ,*args, **kwargs): super(QuestionForm, self).__init__(*args, **kwargs) choice_list = tuple([tuple([x.id,x.content]) for x in question.get_answers_list()]) user_answer = None if default: for id,desc in choice_list: if id == int(default): user_answer = id break; self.fields["answers"] = forms.ChoiceField( widget=forms.RadioSelect(), choices=choice_list, required=False, initial=user_answer) And this form: <form action="" method="POST"> {% csrf_token %} <input type=hidden name="question_id" value="{{ question.id }}"> <ul class="list-group"> {% for answer in form.answers %} <li class="list-group-item">{{ answer }}</li> {% endfor %} </ul> <input type="submit" name="question_btn" value={% trans "Check" %} class="btn btn-lg center-block btn-outline btn-success"> <input type="submit" name="back_btn" value={% trans "Back" %} class§="btn btn-lg center-block btn-outline btn-success"> <input type="button" VALUE="Go to tests menu" onClick="history.go(-1);return true;"> </form> This is my FormView: class QuizTake(FormView): form_class = QuestionForm template_name = 'question.html' def __init__(self, *args, **kwargs): super(QuizTake, self).__init__(*args, **kwargs) self.next_button_clicked= True @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): print("dispatch ") # Try to dispatch to the right method; if a method doesn't exist, # defer to the error handler. Also defer to the error handler if the # request method isn't on the approved list. self.quiz = get_object_or_404(Quiz, url=kwargs['quiz_name']) if self.quiz.draft and not request.user.has_perm('quiz.change_quiz'): raise … -
Django - How to redirect differently using LoginRequired and PermissionRequired?
I would like to create a Mixin which will: First - Check if a user is authenticated, if not, redirect to login url. If yes... Second - Check if user has a defined Profile (a user), if not, redirect to Profile creation, else, allow user to access the View. I was planning to do sometinhg like: class ProfileRequiredMixin(LoginRequiredMixin,PermissionRequiredMixin): #TODO check how multiple inheritance works treating conflicting methods '''This Mixin should first check if user is autheticated, if not, redirect to login. If it is, check if it has a profile. If it does not, redirect to profile creation url. If it has, allow access to view.''' pass But I am confused as how to overwrite the handle_no_permission() and dispatch() methods.