Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-rest-framework Create object with relationship many-to many
I need to create object "Tag" with relationship many-to-many attached to object "Task".I have this code and don't understand why it doesn't work. P.S. I relied on this post manyToMany with django rest framework .models class Tag(models.Model): name = models.CharField(max_length=200) def __str__(self): return "{}".format(self.name) class Task(models.Model): name = models.CharField(max_length=200, blank=True) tags = models.ManyToManyField(Tag) def __str__(self): return "{}".format(self.name) .views class TagCreateView(generics.ListCreateAPIView): serializer_class = TagSerializer def get_queryset(self): queryset = Tag.objects.all() task_id = self.kwargs.get('task_id', None) if task_id is not None: queryset = queryset.filter(task=task_id) return queryset def perform_create(self, serializer): task_id = self.kwargs.get('task_id', None) try: tasks = Task.objects.get(task__id__exact=task_id) except Task.DoesNotExist: raise NotFound() serializer.save(tag=tasks) .serielizers class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('id', 'name','') class TaskSerializer(serializers.ModelSerializer): tag = TagSerializer(many=True, read_only=True) class Meta: model = Task fields = ('id', 'name', 'tags') read_only_fields = ('tags') .urls urlpatterns = { url(r'^todolists/(?P<task_id>[0-9]+)/tags', TagCreateView.as_view(), name="tags")} -
How to show icons and text in dropdown menu for userprofile in djangoadmin?
I'm trying to put icons and text in a dropdown menu for admins so that they can assign a military rank to each user for a game. Later I want to show this rank icon beside their profile image, and under it show the rank in text. Also I'm trying to do this as simple as possible, so my code so far is this:(I'm not trying to get text yet here..) RANK_CHOICE = ( (1, mark_safe('<img src="/media/rank/private.png" alt="private" title="Private">')), (2, mark_safe('<img src="/media/rank/sergeant.png" alt="sergeant" title="Sergeant">')), ) rank = models.CharField(max_length=1, choices=RANK_CHOICE, blank=True) The dropdown list is now empty? EDIT: BTW when I view the source code in browser I can view the images from those links. What have I missed? Appreciate any kind of help, thanks for your time. -
same form on different apps django
Hello I would like to implement the same form on every page in my django project. I know this question has been asked like 15 times but sorry I still don't get it. When I try to copy the code from those Questions I always get some Error. I have a context_processor like this in my settings: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] there are some solutions from 2011 which suggest doing it like so: TEMPLATE_CONTEXT_PROCESSORS = ( "myapp.context_processors.global_login_form", ) but this does not work. What is also quite often suggested is 'django.core.context_processors.request' but yeah still does not work. When I try to do one of these I get "model not installed" or other Errors. What is also recommended is to make a "context_prossecor.py" file and implement some functions. Does not work. something like: <form action="{% url login_view_name %}" method="POST"> {{global_login_form.as_p}} </form> does not work as well. I tried to implement the form into my base/navigation.html file but the form never shows up only when im on the base.html itself. To write some view Function or implement a class LoginFormMiddleware(object) in the View.py and … -
In a Django serializer, how to set foreign key field based on view argument?
Using the Django REST Framework, I would like to allow users to create and save instances of a Django model through a ListCreateAPIView (via POST). One of the fields (a foreign-key field called domain) shall be determined from a view parameter as defined in urls.py. Furthermore, the user can modify the model instance later using PUT or PATCH requests to a RetrieveUpdateDestroyAPIView endpoint (using the same serializer). I don't want the user to be able to modify the domain field at this point. While I have the code for the model and the view / serializer structure ready, I'm not sure how to tell the serializer to determine the value of the domain field based on the view parameter. Here's what I got: class RRset(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(null=True) domain = models.ForeignKey(Domain, on_delete=models.CASCADE, related_name='rrsets') subname = models.CharField(max_length=255, blank=True) type = models.CharField(max_length=10) ... and a straight-forward ListCreateAPIView: class RRsetsDetail(generics.ListCreateAPIView): serializer_class = RRsetSerializer permission_classes = (permissions.IsAuthenticated,) def get_queryset(self): name = self.kwargs['name'] return RRset.objects.filter(domain__name=name, domain__owner=self.request.user.pk) urls.py contains the following line: url(r'^domains/(?P<name>[a-zA-Z\.\-_0-9]+)/rrsets/$', RRsetsDetail.as_view(), name='rrsets') This allows the user to list and create RRset objects using the RRsetsSerializer serializer (the name field is listed for completeness only, but I do not believe it … -
Django weird behavior on cyrillics input in form
I have contact form with 3 inputs: subject, email and message. When entering subject in Latin, for example 'Documentation' - I can see it normally in console. But when typing subject field in Cyrillic, for example 'Документація' - Im recieving something weird, for example 'Subject: =?utf-8?b?0KLQtdC30Lg=?'. How could this be solved? Thanks in advance for any hint! forms.py class FeedbackForm(forms.Form): subject = forms.CharField(required=True) from_email = forms.EmailField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) views.py def feedback(request): if request.method == 'GET': form = FeedbackForm() else: form = FeedbackForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "catalogue/feedback.html", {'form': form}) def feedback_success(request): return HttpResponse('Success! Thank you for your message.') feedback.html {% extends 'catalogue/base.html' %} {% block title %}Feedback{% endblock %} {% load staticfiles widget_tweaks%} {% block content %} <div class="row"> <br> <div class="col-lg-4" style="margin-top: 5%; text-align: right"> <p style="font-size: 18px">Have a question?</p> <p style="font-size: 18px">Found a bag?</p> <p style="font-size: 18px">Have any ideas?</p> <p style="font-size: 42px">Please tell us about this!</p> </div> <div style="text-align: right; margin-top: 1%; " class="col-lg-3"> <img src="{% static 'catalogue/img/hrn.jpg' %}" alt="" style="border-radius: 50%"> </div> <div class="col-lg-5"> <form method="post"> {% csrf_token %} {% render_field form.subject placeholder="Subject" … -
Offering choices that depend on other fields in Django Admin
I'm new about programming so my code could seems dumb sometimes. I'm stuck on this problem since 2 days and I looked for on the web but didn't find what I wanted. I saw related questions on stackoverflow but it seems it?s only for forms and I would like to implement that in the Admin interface. I would like to display choices in a dropdown menu depending on the choices the user make in an other dropdown menu. For these 2 dropdown menu I have 2 lists: COUNTRY = ( (1, 'United States'), (2, 'Canada'), (3, 'France'), (4, 'Italy'), (5, 'Mexico'), (6, 'Norway') ) STATES = ( (1, 'Alabama AL'), (2, 'Alaska AK'), (3, 'Arizona AZ'), (4, 'Arkansas AR'), (5, 'California CA'), (6, 'Colorado CO'), (7, 'Connecticut CT'), (8, 'Delaware DE'), (9, 'Florida FL'), etc... ) Here my model: class Airport(BaseModel): airport_code = models.CharField(max_length=50, verbose_name="Airport Code (ICAO)") airport_name = models.CharField(max_length=50, verbose_name="Airport Name") city = models.CharField(max_length=50, verbose_name="City") country = models.IntegerField(default=1, choices=COUNTRY, verbose_name="Country") state = models.IntegerField(default=1, choices=STATES, verbose_name="State") def get_state(): if self.country == 1: return self.state == 1 & 2 I just put 1 and 2 in this line for the example and to not write to much on the post: return … -
I have two dictionaries within one dictionary and cannot figure out how to access a specific value
I tried looking at other examples but none of them helped me, My problem is somewhere in either constant or views, I cannot seem to grab the value of header from landing page from CONSTANTS.PY. Please help me figure out how what i'm calling in VIEWS.PY is wrong. CONSTANTS.PY videos = {'landing_page': { 'header': 'What\'s it like to take a class at ?', 'subheader': ' \"There are students who keep in touch for years after they\'ve taken a language class here.\" Learn more about the experience and what it means to learn a language with us in the video below. You\'re not just taking a class; you\'re getting an immersive experience and joining a growing community', 'url': 'https://www.youtube.com/'}, 'private_lesson': { 'header': 'SEE WHAT A CLASS LOOKS LIKE AND MEET OUR TEACHERS', 'subheader': ' \"There are students who keep in touch for years after they\'ve taken a language class here.\" Learn more about the experience and what it means to learn a language with us in the video below. You\'re not just taking a class; you\'re getting an immersive experience and joining a growing community', 'url': 'https://www.youtube.com/'}} VIEWS.PY @render_to('video-section.html') def video_section(request): context = {} context['headerLP'] = c.videos['landing_page']['header'] context['subheaderLP'] = c.videos['landing_page'].get([{'subheader'}]) return … -
How to Consume Yahoo Finance API in Django
I'm trying to learn Django and built a small app that contains a list of companies with some general info for each of them. The home page shows a list of all companies and then a user can click on the company name to see more info. I'm now trying figure out how APIs are consumed in Django by using Yahoo Finance to get some stock data about the company and display it on the page. (I've used the yahoo-finance package multiple times in Python and it's pretty straight forward, which is why I've stared with this). I don't need to save the data to a database (unless that's the only way), I simply want to display it. I've pip installed the packaged and added it to the APPS in the settings.py file. Then in my views.py I've added the yahoo-finance dependencies and tried to work in the API in the code below. Then in the template I'm trying to use {{ mkt_cap }}. Doing it this way I'm getting a YQLResponseMalformedError. I realize this may not be the correct way to go about it, but I'm having a hard time figuring it out. from django.views import generic from .models … -
Django run two views at the same time
So as the title says, im trying to run two views at the same time. Or at least, that is what i think i have to do. I have system that lets user like the model and if model like count is bigger than 3, the view should be redirected to a view that sends email message to client. I dont want to put email message code in the same view as "like" view, as the like works same as like button on facebook: it has to respond fast back to the user. Also i want the like_exam view to be finished in any case, if counter < 3 or not. SO what i have now is: def like_exam(request, letnik_id, classes_id, subject_id): exam_id = request.GET.get('exam') exam = get_object_or_404(Exam, id=exam_id) counter = exam.exam_likes.count() user = request.user if user in exam.exam_likes.all(): exam.exam_likes.remove(user) return JsonResponse({"like": "unliked"}) else: exam.exam_likes.add(user) if counter < 3: html = likes_email(exam) return HttpResponse(html) # i want the json to be posted in any case: return JsonResponse({"like": "liked"}) def likes_email(exam): ....sends email... -
Django ManifestStaticFilesStorage not loading the correct static files
I am using a combination of django-storages and ManifestStaticFilesStorage to server static files and media from S3. class StaticStorage(ManifestFilesMixin, S3BotoStorage): location = settings.STATICFILES_LOCATION When I run collectstatic I can see the newest version of my JS file on S3 with the correct timestamp. I can also see that file being referenced in the staticfiles.json manifest. However looking at the site in the browser I am still seeing the old JS being pulled down, not the one in the manifest What could be going wrong? -
Django Rest Framework how to deal with api versions and model changes
This is not a question for a particular use case, but for something I noticed in my experience doing APIs, specifically with using Django and Django Rest Framework. Months ago I had a problem with the API I maintain for a client's project. Let's say we have the following model: class Person: first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) Then, the corresponding serializer: class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = '__all__' Of course, its corresponding ViewSet and route pointing to it: http://localhost:8000/api/v1/persons/ Note this is the 1st version of my API. Everything OK at this point, right? Now, my client asked that we need to receive person's fullname instead of first and last name separately... As supposed, I'll have to change my model to be: class Person: full_name = models.CharField(max_length=200) There are 3 different clients (mobile apps) using this version of the API. Obviously I don't want to change my API, instead I will want to put the new approach in a new version. BUT the 1st version's Serializer is coupled with the Model, so at this point the 1st version of the API already changed What I expect to read in answers below is how you guys deal … -
django modelform validation at the form level
I can have custom validators for my django models and what I would like to do is perform validation at the form level where the form elements have dependencies with each other. To illustrate, say I have the following model: class MyModel(models.Model): num_average = models.IntegerField(verbose_name='Number of averages', default=1) num_values = models.IntegerField(verbose_name='Number of values', default=3) The dependency is that num_values = num_average * 3. I know I can set this automatically but for this purposes let us assume we want the user input. I have a form as: class MyForm(ModelForm): class Meta: model = MyModel fields = ['num_average', 'num_values'] def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) Is there a way to validate the form as a whole before the submit gets triggered? -
Django RF: Fill ManyToManyField
I have model with posts: class Post(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) photo1 = models.ImageField(upload_to=get_image_path) photo2 = models.ImageField(upload_to=get_image_path) result1 = models.IntegerField(default=0) result2 = models.IntegerField(default=0) User = settings.AUTH_USER_MODEL author = models.ForeignKey(User, default=settings.AUTH_USER_MODEL) created = models.DateTimeField(auto_now_add=True, blank=True) description = models.CharField(max_length=500) I add this model to model with custom user profile: class Profile(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to=get_image_path, blank=True) location = models.CharField(max_length=30, blank=True) birthdate = models.DateField(null=True, blank=True) post_count = models.IntegerField(default=0) points = models.IntegerField(default=0) posts = models.ManyToManyField(posts.models.Post) Post model contained in posts = models.ManyToManyField(posts.models.Post). I need output posts many2many in Profile, but belong author's posts (author = models.ForeignKey(User, default=settings.AUTH_USER_MODEL) from Posts model). -
Django yamlfield is not converted from unicode during Model.__init__
I am updating Django, as well as the django-yamlfield package. The package has to be updated as 'SubfieldBase' has been deprecated, and yamlfield is not longer inheriting from it. In the old implementation, while passing a unicode YamlField to Model.init kwargs, the unicode value got converted to the actual python object. Now, as far as I understand, this value should be passed to YamlField 'from_db_value' new method. This isn't working for me, and the 'init' function which uses 'setattr', just set the unicode value to the field. I searched the docs without any luck, and I'm pretty much out of ideas by now. Anyone came across this? -
Request failure with django API and Alamofire
Requests with Alamofire 4 in Swift 3 always fails with 500 status code. I tryed in Postman and works! Look at my code: func newUser(user: User) { var urlRequest = URLRequest(url: URL(string: url + "/register")!) urlRequest.httpMethod = "POST" let parameters: Parameters = [ "username": "\(user.name!)", "email": "\(user.email!)", "password": "(Kh=CE)4r)PC4}f?", "profile": [ "status": 0, "level": 0, "facebook_id": "\(user.fbId!)", "facebook_token": "000", "push_device_token": "000", "photo": "\(user.photoUrl!)" ] ] let headers: HTTPHeaders = ["Content-Type": "application/json"] Alamofire.request(url+"/register", method: .post, parameters: parameters, encoding: JSONEncoding(options: []), headers: headers).response { response in debugPrint(response) print(response) } } Anyone can help me? -
Validating multiple files before uploading in Django
I am currently trying to create a Django app that allows a user to upload multiple .gpx files at once. I would like that when the files are validated the user is provided with a list of files and the reason they weren't uploaded. The file is validated by the following: File size File type Has this file been uploaded before (based on hash of file) If the user uploads a single file that fails any of the above they get the correct error message. If they upload 2 or more files which have an error they only get the message for the first error that occurs. here is my form.py: from django import forms from .validators import validate_file class UploadGpxForm(forms.Form): gpx_file = forms.FileField(widget=forms.ClearableFileInput( attrs={'multiple': True}), validators=[validate_file] ) here is my validators.py: from hashlib import md5 from .models import gpxTrack from django.conf import settings from django.template.defaultfilters import filesizeformat from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ def validate_file(value): if len(value.name.split('.')) != 2: raise ValidationError( _('%(file_name)s has not been uploaded: File type is not supported') , params = { 'file_name': value.name } , code = 'file_type' ) if value.content_type in settings.DASHBOARD_UPLOAD_FILE_TYPES: if value._size > settings.DASHBOARD_UPLOAD_FILE_MAX_SIZE: raise ValidationError( _('%(file_name)s has … -
ORM query for django
I am pretty new to ORM query in django. I have the below sql to get the data from the database. Select * from subnets_subnet as sb left join subnets_subnetoption as sbo on sb.id = sbo.subnet_id left join options_value as ov on ov.id=sbo.value_id left join options_option as oo on oo.id = ov.option_id where oo.name='Customer' How can I join three multiple table even one is from another django app? ie options_value and options_option is from another app. class Subnet(models.Model): parent = models.ForeignKey('self', blank=True, null=True, editable=False) base_address = MyGenericIPAddressField(protocol='IPv4', db_index=True) creation_date = models.DateTimeField(auto_now_add=True, editable=False) modification_date = models.DateTimeField(auto_now=True, editable=False) zone = models.ForeignKey('zones.SecurityZone') dns_authority = models.ForeignKey('dns.DnsAuthority') class SubnetOption(models.Model): subnet = models.ForeignKey('Subnet') value = models.ForeignKey('options.Value') class Option(models.Model): name = models.CharField(max_length=40) required = models.BooleanField(default=False) scope = models.ForeignKey('Scope') class Value(models.Model): content = models.CharField(max_length=60) comment = models.CharField(max_length=80, blank=True, null=True) option = models.ForeignKey('Option') -
S3 based database for Django
I am looking for database engine or documentation how to create such that could - to some extent - remove usage of SQL based database in Django. What I mean by this: in settings.py database engine will be "....FileBasedEngine" having model defined would create the folder "ModelName" in the desired location (content will represent collection) adding record will create a file (name represent primary key) in the folder (content will be a JSON representation of the record) reading the record would return file from the desired folder based on the primary key name, as well as updating or removing record/file reading collection (SELECT *) will read each file in the folder and return list of records etc. This solution does not look as most effective one and would deliver a fraction of database functionality, however, it could be a databaseless Django solution. S3 is final files sources for this solution. Is anybody heard about such solution and can point me how to start? -
filter against search parameters django rest framework
How can I check in the get queryset if the search param is empty or not, so I can further customize my search, I want it not to filter queryset for "today", if the search is not empty, can someone explain me how to do this? ModelViewSet: from rest_framework import viewsets, permissions, filters from cms.restapi.pagination import StandardResultsOffsetPagination from cms_sales.models import LeadContact from cms_sales.restapi.permissions.lead_contact_permissions import LeadContactPermissions from cms_sales.restapi.serializers.lead_contact_serializer import LeadContactSerializer class LeadContactViewSet(viewsets.ModelViewSet): def get_queryset(self): queryset = LeadContact.objects.none() user = self.request.user if user.has_perm('vinclucms_sales.can_view_full_lead_contact_list'): queryset = LeadContact.objects.all() elif user.has_perm('vinclucms_sales.can_view_lead_contact'): queryset = LeadContact.objects.filter(account_handler=user) filter_date = self.request.query_params.get('filter_date', None) if filter_date is not None: queryset = queryset.filter(next_action_date=filter_date) return queryset serializer_class = LeadContactSerializer filter_backends = (filters.DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter) filter_fields = ('account_handler',) ordering_fields = ( 'first_name', 'last_name', 'account_handler__first_name', 'account_handler__last_name', 'sub_organization_name', 'organization_name', 'next_action_date', 'serial_number', 'status_text') search_fields = ( 'first_name', 'last_name', 'account_handler__first_name', 'account_handler__last_name', 'sub_organization_name', 'organization_name', 'next_action_date', 'serial_number', 'status_text') pagination_class = StandardResultsOffsetPagination permission_classes = [permissions.IsAuthenticated, LeadContactPermissions] -
Could not parse the remainder: || django template
I trying to make or condition in django template and getting this error: Could not parse the remainder: ' || 'default_avatar.png'' from 'userprofile.avatar || 'default_avatar.png'' code src="/media/{{userprofile.avatar || 'default_avatar.png'}}" -
how to send parameters to change rest view via angularjs
So I have a button in Angular is which has a function this function is a django rest view . So this view is a parameter based view . Now I want to pass the parameter via the angularjs to the django view . I tried using http.get with params but no use the parameters are not sent. hope some one can help me out here -
Updating a project from 1.4 to 1.11
I have an old project which was made in Django 1.4. I am looking to update to 1.11. Is there a generic guide that I should follow to do the migration? If not, what are the major changes I should worry about when migrating to 1.11? -
Group by and join in django models
I have the following models: class Post(models.Model): description = models.TextField(max_length=500) title = models.CharField(max_length=500) created_at = models.DateTimeField(auto_now_add=True, blank=False) creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') topic = models.ForeignKey(Topic, on_delete=models.CASCADE, related_name='posts') image = models.ForeignKey(Image, on_delete=models.CASCADE, related_name='posts') tags = models.ManyToManyField(Tag, related_name='posts') ratings = GenericRelation(Rating) class Rating(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='ratings') value = models.SmallIntegerField(default=None, validators=[ MinValueValidator(DISLIKE_VALUE), MaxValueValidator(LIKE_VALUE) ]) I want to execute the following SQL statement as Django query: SELECT p.id, p.title, p.topic_id, SUM(r.value) FROM api_post p JOIN api_rating r ON p.id=r.object_id WHERE r.content_type_id=18 GROUP BY p.id LIMIT 5; I read through the documentation and the closest I get is this: Post.objects.annotate(rating=Sum('ratings__value')).order_by('ratings').values('id', 'title', 'description', 'rating') Also I don't really want only these fields from the model because it returns them in a dictionary and I would like it to be in a object. -
Setting Up Django and React
I am using WebPack to setup Django and React. So far, I have generated a bundle and I am trying to reference it in my template: {% extends "main/base.html" %} {% load render_bundle from webpack_loader %} {% block main %} <div id="App1"></div> {% render_bundle 'vendors' %} {% render_bundle 'App1' %} {% endblock %} However, Django can't seem to find the correct bundle files and I get a 404 error shown in the diagram below. Did I initialize everything correctly in the settings.py? -
Django using old version of static file with DjangoManifest
I'm using Django Manifest to manage my static files version. When I'm updating a static file (CSS or JS), the staticfiles.json is being updated but Django keeps using the old version. I'm working with Amazon S3 and Cloudfront CDN. Something I noticed is that it always uses the last version before the latest one. Therefore, I can change just a bit in the file and collect static files again in order to update it, but that's annoying... This is my custom storage class: class StaticStorage(ManifestFilesMixin, S3BotoStorage): """uploads to 'mybucket/static/', serves from 'cloudfront.net/static/'""" location = settings.STATICFILES_LOCATION def __init__(self, *args, **kwargs): kwargs['custom_domain'] = settings.AWS_CLOUDFRONT_DOMAIN super(StaticStorage, self).__init__(*args, **kwargs) Thanks! Rani