Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Selecting a particular object from a set of objects
I have the following models in my Django app: class Review(models.Model): ID = models.AutoField(primary_key=True) text = models.CharField(max_length=1000) review_user = models.ForeignKey("User", on_delete=models.CASCADE) review_book = models.ForeignKey("Book", on_delete=models.CASCADE) class Review_is_helpful(models.Model): ID = models.AutoField(primary_key=True) is_helpful = models.BooleanField() # associated user who gave the review, and the review itself review_user = models.ForeignKey('User', on_delete=models.CASCADE) on_review = models.ForeignKey('Review', on_delete=models.CASCADE) class Book(models.Model): ID = models.AutoField(primary_key=True) name = models.CharField(max_length=50) description = models.CharField(max_length=1000) class User(models.Model): ID = models.AutoField(primary_key=True) For every book, we will have any number of reviews, and for each review, users can tag the review as Helpful/Not helpful (or not tag at all). Now, if I have a Review QuerySet reviews, and a User object user inside a view function, I want to additionally have the following for each review in the QuerySet: 1. If the review has been tagged by the user as Helpful/Not helpful (the corresponding Review_is_helpful object exists), then the corresponding Review_is_helpful object should be there along with the review object. 2. If the user hasn't tagged the review as Helpful/Not helpful (the corresponding Review_is_helpful object does not exist), then any suitable false value, like None will be okay. I was looking for something along the lines of using reviews.annotate(...), but I'm not sure what … -
importing arbitrary fields of a model from excel by django-import-export
I am using Django I have a model like this class DialogText(models.Model): id = models.AutoField(primary_key=True) dialogId = models.ForeignKey(Dialog, on_delete=models.CASCADE, verbose_name="Dialog") whoSay = models.CharField(blank=True, max_length=255) text = models.TextField(blank=True, verbose_name="Dialog Text") image = models.ImageField(upload_to=textDirectory, blank=True, verbose_name="Picture") createdTime = models.DateTimeField(auto_now_add=True) state = models.CharField(blank=True, max_length=255) sayTime = models.CharField(blank=True, max_length=255) text_type = models.CharField(blank=True, max_length=255) I am using django-import-export to import my data from excel. But I don't want all fields of my model to be imported from excel. For example, I haven't any column named 'id' in excel or I should set 'createdTime' the current time of the server and don't import from excel. I have tried this but it didn't work: class DialogTextResource(resources.ModelResource): fields = ('whoSay', 'text', 'text_type', 'sayTime', 'state', 'image', 'dialogId') class Meta: model = DialogText class DialogTextAdmin1(ImportExportModelAdmin): resource_class = DialogTextResource Thank's for any help. -
Object not found, but does exist
I have an existing working site, that takes advantage of Adobe Lightroom's catalog being an sqlite3 db. The model is auto-generated. Whilst updating the code for the site (to TemplateView and streamlining), I thought I'd get adventurous and pull on one of the class models to get the information about how many times a face (person) appears in the photos. The model: class Aglibrarykeywordpopularity(models.Model): id_local = models.IntegerField(primary_key=True, blank=True, null=False) occurrences = models.TextField() # This field type is a guess. popularity = models.TextField() # This field type is a guess. tag = models.TextField(unique=True) # This field type is a guess. class Meta: managed = False db_table = 'AgLibraryKeywordPopularity' The 'tag' value is obtainable from another model, where it's called 'id_local': face_id = list(Aglibrarykeyword.objects.values_list('id_local', flat=True)) The values for the 'face_id' are all present in the previous 'tag' field when you view the db. However, when using: for a in face_id: face_pop.append(Aglibrarykeywordpopularity.objects.get(tag=a).occurrences) .. it complains that there are no matches. I've substituted 'a' for a number, or string of the number, even adding '.0' to the representation, and it still complains no matches. I've tried .filter...first() etc. slides.models.DoesNotExist: Aglibrarykeywordpopularity matching query does not exist My current work-around is going to output All() of … -
Django model accessed globally
I want to have a model accessed throughout the whole project in the templates, not to declare it on every view. Is this possible? What is the best way to do this? Something like User is accessed through request.user. -
Django: Working With Messages
I'm trying to create a messaging app similar to what we see on social networks. Here's my model, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") ... timestamp = models.DateTimeField(auto_now_add=True) Everything is fine I can filter out the messages for request.user, but couldn't order the users. I wants to order the Users based upon to whom request.user sent a message & who sent a message to request.user most Recently, as we see on social networks. How can I do that? -
How to handle AuthAlreadyAssociated at Python-auth/Django-Social?
I use this python-social-auth/social-app-django to connect my web with social media I want to ask how to handle errors when the same account is used to sign up? For example, I signed up using facebook and I signed up again using twitter. both successfully registered into two separate accounts, when I logged in using my facebook and then on my account settings page, I want to connect my twitter that has been registered before it will display an error message "AuthAlreadyAssociated at / oauth / complete / twitter /" AuthAlreadyAssociated This message appears after I authorize on the twitter redirect page when it gets redirected back to my web. In short, how to deal with accounts that have been registered in other accounts? This is my views.py: @login_required def settings(request): user = request.user try: github_login = user.social_auth.get(provider='github') except UserSocialAuth.DoesNotExist: github_login = None try: twitter_login = user.social_auth.get(provider='twitter') except UserSocialAuth.DoesNotExist: twitter_login = None try: facebook_login = user.social_auth.get(provider='facebook') except UserSocialAuth.DoesNotExist: facebook_login = None can_disconnect = (user.social_auth.count() > 1 or user.has_usable_password()) return render(request, 'profile/settings.html', { 'github_login': github_login, 'twitter_login': twitter_login, 'facebook_login': facebook_login, 'can_disconnect': can_disconnect }) And this is my settings.html template: {% extends "base.html" %} {% load crispy_forms_tags %} {% block title %}Navhi Microblog - … -
Django aggregation and filtering
I am working with a model having a date, a group, and an identifier. I want to retrieve for each group the id of the minimum date value. My model: class MyModel(models.Model): group = models.ForeignKey('myapp.Group') date = models.DateTimeField(blank=True, null=True) The goal is to retrieve this: [ (u'group1', datetime.date(2016, 1, 23), 15 <- Id of the minimum date for group1), (u'group2', datetime.date(2015, 6, 25), 314 <- Id of the minimum date for group2), ... ] I tried the following: MyModel.objects.values_list('group').annotate(Min('date')).order_by('group') This works fine but gives me the date: [ (u'group1', datetime.date(2016, 1, 23)), (u'group2', datetime.date(2015, 6, 25)), (u'group3', datetime.date(2015, 6, 26)) ... ] I cannot find a way to add the id to those tuples without breaking the grouping clause in SQL. I tried to do a where date = min(date), but aggregation is forbidden in where clause. -
DjangoCMS render_model with HTML
I'm using Django CMS and the Aldryn News Blog app on a client site to display a blog listing. The default template code uses {% render_model article "lead_in" %} to display the "Lead in" excerpt text. However it is displaying p tags for me and I actually need them to render. https://pasteboard.co/GSq8XObQ.png https://pasteboard.co/GSq8ONF.png I have tried both: {% autoescape off %} {% render_model article "lead_in" %} {% endautoescape %} {% render_model article "lead_in" |safe %} The first does nothing and the second errors out. How can I get it to render the html tags? -
Hidden fields, auto assign values in django
I am still a newbie on django and Python. This is also my first question. I am trying to create a hidden field and auto assign a value to the hidden field. It can be either in the views or in the templates. I have a field "kind" that needs to be hidden. Also I need to assign a value to it depending on different views/templates so it populates the database. This is my class view: class Monthlypage(CreateView): template_name = 'monthly.html' model = models.Lead form = forms.LeadForm() fields = ['name','email','tel','kind'] This is my model form: class LeadForm(forms.ModelForm): def __init__(self, *args, **kwargs): kind = models.Lead.kind class Meta: model = models.Lead kind = forms.CharField(widget=forms.HiddenInput()) fields = ['name','email','tel','kind'] This is my model: class Lead(models.Model): name = models.CharField(max_length=265) email = models.EmailField(max_length=265) tel = models.IntegerField() kind = models.CharField(max_length=265) def __str__(self): return self.name def get_absolute_url(self): return reverse('registrations') This is my template: <form class="" method="post"> {% csrf_token %} {% bootstrap_form form %} <input type="hidden" name="kind" value="{{ form.kind.monthly }}" /> <input type="submit" name="" value="Submit" class="btn btn-info"> I have tried many options and spend 2 days using different solutions. But no matter what I do I can't seem to populate the kind field in the database. -
Django. Algorithm on the back of the server [on hold]
Need to make a schedule program with an algorithm on the back of the server. Is it possible to make it in "pure" python on the back or should I use something else, like Ajax to change data on the server? What should I use? -
How to get user id from JWT
How to get user id from JWT token. My JWT token has payload something like this: { "username": "Steve", "is_admin": false, "id": 1 } How do I get access to user id? I actually want to update certain fields in database as per the id, that are for a specific user. Secondly after gaining the access how do I get update the fields? models.py class Profile(models.Model): branch = models.CharField(max_length=20, null=True) year = models.IntegerField(null=True) image = models.ImageField(upload_to="accounts/images/", null=True, blank=True) serializer.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('branch', 'year' ,'image',) What will be the view to update these fields? -
How can we log into a webserver using username password csrftoken and csrfmiddlewaretoken
I am trying to log into a server using my authentication(username and password) for app development purpose with swift 4. However my server requires csfrtoken and csrfmiddlewaretoken. How can I extract the csrfmiddlewaretoken value and make a Post request to log with all the other authentication? -
Access to file uploaded with FileField Django
I'm trying to create a Django form with a filefield to upload a pdf based on a model. #models.py class ProductionRequest(models.Model): ... contract_file = models.FileField('Contract file (PDF)', upload_to='contracts/') ... I can upload the file and save it in my object, but when I try to show the file in my template with this code {{ prod_req.contract_file }} it only show me the path to the file "contracts/file_uploaded.pdf". How can I make a link to download (or open in a new tab ) the file ? Plus : when I try to open the file from Django admin, with this link Contract file (PDF) : Currently: contracts/file_uploaded.pdf I don't show me the file, i got this : Page not found (404) Request URL: http://127.0.0.1:8000/admin/appname/productionrequest/1/change/contracts/file_uploaded.pdf/change/ How can I access to my file ? -
Heroku + GA, wrong city
I have Django app deployed on Heroku. When I analyse data on Google Analytics and use city dimension, I see a lot entries with "Ashburn" city. When I made a research, I found out this: Server info - Heroku.com Where is heroku.com hosted? IP: 54.243.150.141 Binary IP: 110010100001001001001100100100111101 Octal IP: 624111144475 Hexadecimal IP: ca124c93d Decimal domain: 110101 Registrar: MarkMonitor Inc. Country: United States City: Ashburn Latitude: 39.043701171875 Longitude: -77.487503051758 So as I understand Heroku passes its server location to GA. How I can get real user location? -
Javascript vs Python Django for web development
For a beginner who wants to start learning web development. What is the differences between Javascript and Python Django. I have a good background in Python. The main question is: can I do everything with Python Django or I may need Javascript later ? Which one should I start with? Thanks! -
Filtering django rest framework query set using a custom filter backend
I'm having problems with filtering the query set. Here is a simplified data model: Entry - id - broadcast_groups User - id - groups So an entry can be broadcasted (shared) in a group. I have a GET /entries/ endpoint that returns entry objects. I want to filter a query set to return entries that fulfill following requirements: are not broadcasted in any group OR are broadcasted in groups the user is member of. I'm scratching my head how to achieve this. I figured that maybe writing a custom FilterBackend is a good idea. Here is what I have so far: class CanViewPublicOrGroupMemberEntriesFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): user = request.user return queryset.filter(broadcast_groups__in=user.groups.all()) However, this does not yield results that I am expecting. What would be a filter() syntax to achieve such filtering? Or maybe I'm approaching the problem from the wrong side? -
How to call specific textfield from model in templatetag?
Sorry if this question is very noobish but I have only been learning Python/Django for a month. I have Googled and searched on Stack Overflow for hours now but can't find a solution to my problem. I am basically trying to parse a URL from a TextField and then present it in a template. So far I have: models.py class Thing(models.Model): youtube_link = models.TextField(blank=True, null=True) I created templatetags/embeds.py with the following code: from django import template from urllib.parse import urlparse register = template.Library() from ..models import Thing @register.simple_tag def youtube_parse(): ytparse = urlparse('https://www.youtube.com/watch?v=bnKaOo67mLQ') # URL test return yt_parse And in my html template: {% load embeds %} {% youtube_parse %} So far so good. The template shows the parsed URL (although it's not very pretty yet). But what I am having trouble with is calling the field "youtube_link" from the model Thing in embed.py. Basically I want embed.py to do this: ytparse = urlparse(Get youtube_link from model Thing and parse it) But I have problems calling youtube_link. I have tried Thing.youtube_link and many other code snippets that I found after Googling for a while, but nothing seems to work. What am I missing? -
Django Crispy form set model feild as required
i have a modelform in which i want to set required attribute to True for email validation field:-email class RegisterMyBuisinessForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_action = '/registermybuisness/' Field('email', type='email') self.helper.add_input(Submit('submit', 'Submit',css_class="btn c-theme-btn c-btn-square c-btn-bold c-btn-uppercase")) super(RegisterMyBuisinessForm, self).__init__(*args, **kwargs) class Meta: model = RegistermyBusiness fields = ['name','email', 'org_name', 'contact','business_description','store_address','message','store_landmark','business_type','city'] i tried self.fields['email'].required=True this resulted in class RegisterMyBuisinessForm doesnot have fields error -
How to add Fields to the forms in Django through JavaScript
I'm trying to make a to-do list kinda app and want to add Fields to the the form through JavaScript NOTE - I don't wanna use formsets -
How to convert nested JSON object to Python in Django
I'm working on a Django application that posts data to the server. Here is the Python snippet: def save(request): if request.method != 'POST': return HttpResponse('Illegal Request') print(request.POST.get('dataObj')) return JsonResponse({'status':200}) JQuery on the client side: function submitQuoationClicked() { dataObj = getQuotationInJSON() console.log(dataObj) token = $("input[name=csrfmiddlewaretoken]").val() $.ajax({ type:"POST", url:"/quotations/save", data: { 'csrfmiddlewaretoken': token, 'dataObj' : dataObj, }, success: function(data){ if(data.status === 200) console.log("Good Work Falak!") //TODO Remove this line, FOR DEBUGGING ONLY } }); function getQuotationInJSON() { var data = {}; data['title'] = $("#title").val() data['companyName'] = $("#company").val() data['addressLine1'] = $("#addressLine1").val() data['addressLine2'] = $("#addressLine2").val() data['city'] = $("#city").val() data['country'] = $("#country").val() data['date'] = $("#date").val() data['number'] = $("#number").val() data['validTill'] = $("#validTill").val() sections = getItemsData(); data['sections'] = sections return data } function getItemsData() { sections = [] $("tr[id^='section']").each(function(index, element) { sectionId = $(element).attr('id').split('section')[1] name = $(element).find("#sectionName" + sectionId).val() section = {} section['name'] = name //Now get section items rowElems = $(".section" + sectionId) rows = [] $(rowElems).each(function(index, row){ if($(row).attr('id').indexOf('itemRow')>=0) { description = $(row).find("#description").val() quantity = $(row).find("#quantity").val() unitPrice = $(row).find("#unitPrice").val() margin = $(row).find("#margin").val() if(quantity!="" && unitPrice!="" && description!="" && margin!="") { row = {} row['description'] = description row['quantity'] = quantity row['unitPrice'] = unitPrice row['margin'] = margin rows.push(row) } } }); section['items'] = rows; sections.push(section) }); return sections … -
get_context_data - self.request.user with domain?
I'm attempting to use a simple view in Django that ties my username as a formatted username with the Domain\ prior to my username. I.E. (Domain\UserName). Below is the view that i've defined, but when I attempt to link my model with the view. I can hard code the domain since it will never change, but is there a way to just pull Domain\UserName? def applicationdetail(request, ntname, report_id): user = get_object_or_404(User, pk=self.request.user) applicationlist = QvReportList.objects.all(report_id=report_id) applicationaccess = QVReportAccess.objects.filter(ntname=ntname) context = {'user' : request.user, 'applicationdetail' : applicationaccess} return render(request, 'accounts/profile.html', context=context) -
Django UpdateView form with multiplechoicefield going to form in_valid when posted without selecting the multiple choice field?
I have a update view for my model and this model has a many to many relation with another model. Due to some filtering requirements I created a custom multiplechoicefield and am saving it by modifying the form_valid. But if this multiple choice field is not selected form is getting posted to form_invalid. This field is not required. My view and form look as follows: class Updatemodel(UpdateView): template_name = ... def get_success_url(self): return .. def get_from_class(self): .. .. def form_valid(self,form): kwargs = super(Updatemodel, self).get_form_kwargs() m2m_initial = kwargs['instance'].model_m2m.filter( .. ) chosen_m2m = model_m2m.objects.filter(pk__in = form.cleaned_data.get('model_m2m')) m2m_add = chosen_m2m.exclude(pk__in = m2m_initial.values_list('pk, flat = True)) m2m_remove = m2m_initial.exclude(pk__in = chosen_m2m.values_list('pk,flat = True)) form.instance.model_m2m.add(*m2m_add) form.instance.model_m2m.remove(*m2m_remove) return super(Updatemodel, self).form_valid(form) def get_form_kwargs(self): kwargs = super(Updatemodel, self).get_form_kwargs() kwargs['m2m_initial'] = kwargs['instance'].model_m2m.filter( ..) kwargs['m2m'] = model_m2m.objects.all().filter( .. ) .................. form ...................... class m2m_update_form(forms.ModelForm): def __init__(self, *args, **kwargs): m2m = kwargs.pop('m2m',None) m2m_initial = kwargs.pop('m2m_initial',None) super(m2m_update_form, self).__init__(*args, **kwargs) choices = [(M2M.pk, M2M.Name) for M2M in m2m ] self.fields['m2m_field'] = forms.MultipleChoiceField(choices = choices, widget = FilteredSelectMultiple("M2M", False, choices = choices)) self.initial['m2m_field'] = [M2M for M2M in m2m_initial] class Media: .. class Meta: model = model1 fields = ['field1', 'field2','field3'] widgets = { 'field3' = FilteredSelectMultiple("Field", False), } -
How correctly handle 2 forms on one page with NOT clearing one form handling other
I'm trying to create temlate with PhotoForm for Profile.image and ProfileForm for other Profile data. I found lots of answers how to handle 2 forms on one temlate, also found how to clear data when form is submitted, but I'm trying NOT to clear data of ProfileForm when PhotoForm is submitted. Here is my template( deleted all style staff to show the object of the question): <form method='post' enctype="multipart/form-data" id="formUpload"> {% csrf_token %} {{ image_form }} <button type="submit" class="js-crop-and-upload" name="crop">Crop</button> </form> <!--container for uploaded image --> <form method='post'> {{ profile_form.as_p }} {% csrf_token %} <button type="submit" class="btn" name="save_profile">Submit</button> </form> And here is my view: @login_required def profile_new(request): if Profile.objects.filter(user=request.user): return redirect('profile_edit') created_image = Photo.objects.filter(created_by=request.user) if request.method != "POST": profile_form = ProfileForm() image_form = PhotoForm() return render(request, 'personal_page_platform/edit_profile.html', { 'profile_form': profile_form, 'image_form': image_form, 'title': 'New profile', }) if request.method == 'POST' and 'crop' in request.POST: profile_form = ProfileForm(request.POST) image_form = PhotoForm(request.POST, request.FILES) if not image_form.is_valid(): return render(request, 'personal_page_platform/edit_profile.html', { 'profile_form': profile_form, 'image_form': image_form, 'title': 'New profile', 'created_image':created_image }) created_image = image_form.save(request=request) return render(request, 'personal_page_platform/edit_profile.html', { 'profile_form': profile_form, 'image_form': image_form, 'title': 'New profile', 'created_image':created_image }) if request.method == 'POST' and 'save_profile' in request.POST: profile_form = ProfileForm(request.POST) image_form = PhotoForm() if not profile_form.is_valid(): … -
DJANGO app loose path from batch file
I try to learn more about Django celery and rabbitmq to create some async tasks and I have some question. Some programs can provide PYTHON API to can some development to use modules from this program in python. one most way to take that PYTHON API from this program is to use batch file like this : @echo off SET PROGRAM_ROOT=C:\main-folder call "%PROGRAM_ROOT%"\bin\some-batch-file.bat SET PYCHARM="C:\Program Files\JetBrains\PyCharm 2017.1.5\bin\pycharm64.exe" set PYTHONPATH=%PYTHONPATH%;%PROGRAM_ROOT%\python; set PYTHONPATH=%PYTHONPATH%;%PROGRAM_ROOT%\site-packages; start "PyCharm aware of PROGRAM" /B %PYCHARM% %* if I run this batch file can I use all imports and modules from this program. that to release if add celery in my app and broker url rabbitmq server then if i use some module or some import from this python api then I take error message : no module name some_module_from_program (for all other modules celery and rabbitmq app work fine). that mean in celery and rabbitmq server loose that paths from batch file and I take this error. my question how to can define rabbitmq server to start server with that paths like batch file before to avoid this error? -
Should I constantly use Django select_related and prefetch_related?
Should I constantly use Django select_related or prefetch_related every time when use models with OneToMany relations? Should I use it if I have multiple Foreign keys? class A(models.Model): pass class B(models.Model): pass class C(models.Model): a = models.ForeignKey(A) b = models.ForeignKey(B) # example usage for entry in C.all().select_related('a').select_related('b'): pass