Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django. Creating a field that is a copy of an existing field in a related model.
I would like to have a field, that is simply a copy of another field. Class Foo(models.Model): bool = models.BooleanField(default=False) class Bar(models.Model): foo = models.ForeignKey(Foo, related_name='bar') copy = foo.bool # i would want this to be equal to bar.foo.bool -
Django: presenting in template an average of a foreign key model specific field
My system include 2 models one for items and second for reviews of these items. In every review there are many different fields (how fun it is, how friendly etc..) I'm trying to query the DB so I can present say the average score of friendly (which is a field in Review) of the festival i'm currently in (I guess by PK). Since I'm new to Django this task is a little bit confusing for me. Appreciate your help. Models.py class Item(models.Model): ... class Review(models.Model): def get_absolute_url(self): return reverse('festival_list:single', args=[self.festival.pk]) item = models.ForeignKey( Item, related_name='Item_Reviews', on_delete=models.CASCADE, null=False, blank = False, ) bad = 0 okay = 1 good = 2 great = 3 superb = 4 score_choices = ( (0, 'Bad'), (1, 'Okay'), (2, 'Good'), (3, 'Great'), (4, 'Superb'), ) friendly = models.IntegerField( choices=score_choices, default=score_choices[0], ) Views.py: class DetailItem(generic.DetailView): queryset = models.Item.objects.all() def get_context_data(self, **kwargs): context = super(DetailItem, self).get_context_data(**kwargs) context['item_reviews'] = models.Review.objects.all() return context Item_detail.html: <h4>Friendly</h4> <p> {% for score in item_reviews %} {{ ?? }} {% endfor %} </p> -
How to serializer django-mysql's JSON field
I'm using django together with the django-mysql library to be able to make use of its JSON Field. However I'm having a problem writing a serializer for my model. Here's the model: models.py class PhoneTest(Model): data = JSONField() views.py class PhoneTestView(viewsets.ViewSet): serializer_class = PhoneTestSerializer def create(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid() # serializer.save() should actually create a record in a DB return Response(serializer.data, status=status.HTTP_200_OK) serializers.py class PhoneTestSerializer(serializers.ModelSerializer): data = serializers.JSONField(binary=True) def validate(self, value): return value class Meta: model = PhoneTest fields = ['data'] What is returned is an empty object {}. Certainly it's a problem with the serializer. I think I could indeed avoid using it at all and write something like: PhoneTest.objects.create(data=request.data) But I'm not sure if it's bon ton. -
How to translate .js files in Django and Wagtail
I'm using Wagtail and Django and I'm trying to translate the content in html templates and js files. The content in html templates is added correctly to .po files but the strings from js files aren't added at all. The structure of my project is as follows: The urls.py file inside webDealers folder is as follows: urlpatterns = [ url(r'^django-admin/', admin.site.urls), url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), url(r'^search/$', search_views.search, name='search'), url(r'^api/', include('API.urls')), url(r'^i18n/', include('django.conf.urls.i18n'), name='set_language'), url(r'^jsi18n/$', JavaScriptCatalog.as_view(packages=['webDealers']), name='javascript-catalog'), url(r'', include(wagtail_urls)), ] The settings.py is as follows: PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(PROJECT_DIR) LANGUAGE_CODE = 'en' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = [('en', 'English'), ('fr', 'French'), ('nl', 'Dutch')] LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) All .js files are in static folder inside webDealers folder. I've added <script src="{% url 'javascript-catalog' %}"></script> to the <head> tag and I've added gettext("String to translate") in .js file where the string needs to be translated. But when I run django-admin makemessages -l en inside locale folder I get only translations from html files and not from js files. And I'm using Django==2.1.2 Any advice how to translate strings in js files? -
Django AJAX 'GET' form csrf_token not working for 'POST'
I am loading a form in a template with AJAX. I've included a {% csrf_token %} in the template, but when I POST the form, I get the csrf error screen. I've tried a few different things I've seen, but it hasn't worked. original view: def customer_profile(request, pk): name = get_object_or_404(CEName, id=pk) return render( request, 'customer/customer_profile.html', {'profile_name': name} ) original template: {% block content %} {% include 'ce_profiles/name_header.html' %} <div id="name" class="container d-flex justify-content-between pt-1"> {% include 'ce_profiles/profile_name.html' %} <button id="update_button" action="{% url 'ce_profiles:profile-update-name' profile_name.id %}" class="bold btn btn-main btn-sm button-main">UPDATE</button> </div> <div id="div_NameForm" class="container"> </div> {% endblock %} {% block script %} <script src="{% static 'ce_profiles/ce_profiles.js' %}"></script> {% endblock %} script.js $(document).ready(function() { $("#NameForm").submit(function(event) { event.preventDefault(); $.ajax({ url: $(this).attr('action'), type: $(this).attr('method'), data: $(this).serialize(), dataType: 'json', success: function(data) { $('#profile_name').html(data.profile_name); } }); }); }); let updateButton let toggleNameForm = function(e) { e.stopPropagation(); let btn = this; if (btn.innerHTML === "UPDATE") { $.ajax({ url: $(this).attr('action'), type: 'GET', dataType: 'json', success: function(data) { $('#div_NameForm').html(data.NameForm); } }); btn.innerHTML = "CANCEL"; btn.classList.replace("button-main", "button-secondary"); } else { $('#div_NameForm').html('<div id="div_NameForm" class="container"></div>'); btn.innerHTML = "UPDATE"; btn.classList.replace("button-secondary", "button-main"); } }; document.addEventListener('DOMContentLoaded', function () { updateButton = document.getElementById('update_button'); updateButton.addEventListener('click', toggleNameForm); }); form view and template: def profile_update_name(request, pk): name … -
django 1.8 - object has no attribute error on migration's RunPython
I am trying to add a new field to one of my models and I want to populate this field for all the existing instances of that module using the migration's RunPython. The problem is that populationg is being done using a class method of another model which has a ForeignKey to this model: class A(mptt_models.MPTTModel): baz = models.ForeignKey(to='b.B', related_name='aaa', ...) def get_yun(self): return self.get_root().yun class Meta: app_label = 'b' class B(models.Model): foo = ... yun = models.CharField(...) # This is the new field class Meta: app_label = 'b' My migration file contain this function which invoked using migrations.RunPython after migration.AddField operation: def set_yun(apps, schema_editor): B = apps.get_model("b", "B") for b in B.objects.all() b.yun = b.aaa.first().get_yun() The last line throws AttributeError: 'A' object has no attribute 'get_yun' I read similar question and I understood that apps.get_model returns a shallow model which doesn't contain the methods I declared in the model class. However none of the answers worked for me (it looks like they are relevant to newer versions of django - I am using 1.8) Is there a way to populate my new field using RunPython through the migration file or I would have to do it manualy after modifing … -
how to add token authentication to header
I tried to create a client that uses django test client and make a get request with token authentication. But I get a 401 error so something is wrong ..Of course this also happens for post. I was looking for different solutions but nothing works. this is part of the code: from django.test import Client class MyClient: def __init__(self): self.client = Client() self.token = None def get(self, url): if self.token is not None: new_url = base + url result = self.client.get(new_url, headers={'Content-Type': 'application/json','Authorization': 'Token {}'.format(self.token)}) else: result = self.client.get(url) return result def login(self, username, password): payload = { "username": username, "password": password } response = self.post_without_auth('/api/auth/token_auth/',payload) if response.status_code is 200: self.token = response.json()['token'] return response -
I can't make a html files inside a template
** [enter image description here][1] [1]: https://i.stack.imgur.com/ZTjG6.pngemphasized text -
Django models and querysets
I would like to get your help because I'm blocked in my Django web application. I have two classes in my model : class Document(models.Model): code = models.CharField(max_length=25, verbose_name=_('code'), unique=True, null=False, blank=False, default='') title = models.CharField(max_length=512, verbose_name=_('document title')) class Download(models.Model): email = models.CharField(max_length=150, verbose_name=_('e-mail'), null=False) country = models.ForeignKey(Country, verbose_name=_('country'), related_name='download') doc = models.ForeignKey(Document, verbose_name=_('Document'), null=True) token = models.CharField(max_length=40, verbose_name=_('download token'), unique=True, null=False) expiration_date = models.DateTimeField(verbose_name=_('expiration date'), null=False) As you can see, Download class is bounded to Document class thanks to ForeignKey. Now, in my views.py, I have this : def form_valid(self, form): email = form.cleaned_data['email'] country = form.cleaned_data['country'] for checkbox in self.request.GET.getlist('DocumentChoice'): document = Document.objects.get(code=checkbox) token = self.gen_token(email) now = timezone.now() expiration = now + settings.DOWNLOAD_VALIDITY Download.objects.create(email=email, country=country, doc_id=checkbox, token=token, expiration_date=expiration) return super(HomeView, self).form_valid(form) What I would like to do: In this line : Download.objects.create(email=email, country=country, doc_id=checkbox, token=token, expiration_date=expiration) I would like to setdocument.code = checkbox but I don't overcome to find the good way to do that. checbox corresponds to a list of code from documentmodel. I tried doc_code, doc_id_code ... but I don't find the good syntax to make reference to document.code from download class. Thank you -
email address is not being parsed in beautifulsoup
I am scraping a webpage using the beautifulsoup and requests in python3.5 . problem is when i tried to parse the email address in the div it gives me the [email protected]. I have tried the other links but no gain. cf_email tag is not even there. I am parsing through this email_addresses=[] for email_address in detail.findAll('p'): email_addresses.append(email_address.text) information = {} information['email'] = email_addresses emails are in the <p> tags. -
Saving image to Django Media Folder via POST request
I want to save the image captured via webcam in media folder VIEWS.PY from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt # Create your views here. def index(request): return render(request, 'index.html') @csrf_exempt def add(request): if (request.method == "POST"): # save it somewhere print("so") f = open(settings.MEDIA_ROOT + 'Pic.jpg', 'Pic') f.write(request.raw_post_data) f.close() # return the URL return HttpResponse('http://localhost:8080/media/Pic.jpg') else: return HttpResponse('no data') JS function Snapshot in html takes a snap and makes a post request. function snapshot() { // Draws current image from the video element into the canvas ctx.drawImage(video, 0,0, canvas.width, canvas.height); var Pic = document.getElementById("myCanvas").toDataURL("image/png"); Pic = Pic.replace(/^data:image\/(png|jpg);base64,/, "") // Sending the image data to Servers $.ajax({ type: 'POST', url: 'addface', data: '{ "imageData" : "' + Pic + '" }', contentType: 'application/json; charset=utf-8', dataType: 'json', success: function (xhr, status, error) { alert("Done, Picture Uploaded."); }, }); } I have configured media folder in settings.py. (BASE>Static>Media) MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static','media') -
Django url doesn't see context variable
I have Profile view in which I set context variable - user nick: class ProfileView(LoginRequiredMixin, TemplateView): template_name = 'profile/templates/profile.html' redirect_field_name = '' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) profile_id = Profile.objects.get(pk=self.request.user.id) context['user_nick'] = Blogger.objects.get(profile_id=profile_id).nick return context And url for it: path('bloggers/<slug:nick>/videos', bloggers_views.BloggerVideos.as_view(), name='blogger_videos'), Also I'm passing nick in my navbvar: {% if user.is_authenticated %} {% include 'navbar/templates/navbar.html' with nick=user_nick %} {% endif %} Referencing to it like: <li><a href= {% url 'bloggers' %}><span>Bloggers {{ nick }}</span></a></li> <li><a href= {% url 'blogger_videos' nick %}>Blogger's videos</a></li> It's weird that in first case Django renders nick correctly, but in second it crashes with following error: NoReverseMatch at /bloggers/Gardiner/videos Reverse for 'blogger_videos' with arguments '('',)' not found. 1 pattern(s) tried: ['bloggers\\/(?P<nick>[-a-zA-Z0-9_]+)\\/videos$'] It doesn't see nick at all: candidate_subs {'nick': ''} What will be the possible solution? -
Searching for list of values in a Django JSONField
So I've got this model with this JSONField - class Details(models.Model): ref_det = JSONField(null=True, default=dict()) ref_det stores values in this format {'user_id': '2231', 'org_id': 'qpdkm12'} Each object of the model has its ref_det as a dictionary of just those two values. Now I have this list of user IDs - user_ids - and I want to get those objects from the model where the user_id key in its ref_det field contains any of those user_id in the user_ids list. So if I have user_ids = ['2231', '973','431'], I should get those Details objects whose ref_det has its user_id as any of the 3 values in the list. I tried looking up through contains, but I think that supports lookups of only a single value and not a list. I think __values__contains (https://docs.djangoproject.com/en/1.9/ref/contrib/postgres/fields/#hstorefield) is appropriate for this usecase, but then again, I don't have an HStoreField. Does anyone know how I can get through this? Thanks! -
How to get filter key and result tuple in Django
Assume there is a list contains all keys to search called taglist. To filter all Post contains tag in taglist, I use the following command. Post.objects.filter(tags__tag__in=taglist).order_by('-id') and in class Post tags = models.ManyToManyField('PostMention') in PostMenthion class PostMention(models.Model): tag = models.CharField(unique=True,max_length=200) and I will get a Query list about the result. Can I get a list of tuple like(each_result,tag_that_used_to_found_the_result)? -
Django Send output with Ajax but Javascript doesn't work
I want to query the database and show the result don't refresh the page. So I use the Ajax! But when I append or paste the html code, the javascript isn't work. The style of my table is so ugly. This is table html part that output will be here (ID=output) : <div class='fresh-table' id="output"> <div class='toolbar'> <button type='button' id='alertBtn' class='btn btn-info'>Add To Cart</button> </div> <table id='fresh-table' class='table'> <thead> <th data-field='state' data-checkbox='true'></th> <th data-field='id' data-sortable='true'>id</th> <th data-field='name' data-sortable='true'>candidate</th> <th data-field='salary' data-sortable='true'>salary</th> <th data-field='gpa' data-sortable='true'>gpa</th> <th data-field='position'>position</th> <th data-field='actions' class='td-actions text-right' data-formatter='operateFormatter' data-events='operateEvents'>Actions</th> </thead> <tbody> {% for candidate in Candidate %} <tr data-val='{{candidate.id_number}}'> <td></td> <td><a href='/filter/{{candidate.id_number}}/' style='color: #ff9800; font-weight: 400;'>{{candidate.id_number}}</a></td> <td>{{ candidate.name_title }} {{candidate.firstname}} &nbsp&nbsp {{candidate.lastname}}</td> <td>{{candidate.salary}}</td> <td>{{candidate.nowEdu_gpa}}</td> <td>{{candidate.position}}</td> <td></td> </tr> {% endfor%} </tbody> </table> </div> This is Ajax in template: $.ajax({ type : 'POST', url : 'testajax/', dataType : "json", async : true, data : { filter_option : json_filter_option, operator_position : json_operator_position, filter_position : json_filter_position, csrfmiddlewaretoken:"{{ csrf_token }}" }, success: function(json){ console.log(json.message) html = "<div class='toolbar'> <button type='button' id='alertBtn' class='btn btn-info'>Add To Cart</button></div><table id='fresh-table' class='table'><thead><th data-field='state' data-checkbox='true'></th><th data-field='id' data-sortable='true'>เลขประจำตัวประชาชน</th><th data-field='name' data-sortable='true'>ชื่อผู้สมัคร</th><th data-field='salary' data-sortable='true'>เงินเดือนที่คาดหวัง</th><th data-field='gpa' data-sortable='true'>เกรดเฉลี่ยสะสม</th><th data-field='position'>ตำแหน่งที่สมัคร</th><th data-field='actions' class='td-actions text-right' data-formatter='operateFormatter' data-events='operateEvents'>Actions</th></thead><tbody>"; $.each(json.message, function( index, candidate ) { html += "<tr … -
Manual Exception rolled back in SQLite3 but not in MySQL using Django ORM
@transaction.atomic() def insert_in_sample_table(request): try: with transaction.atomic(): insert_obj = SampleTable1.objects.create(fld_id=1, fld_name='abc') raise Exception ("This is manual exception") insert_obj2 = SampleTable2.objects.create(fld_id=1, fld_name='xyz') return HttpResponse("SUCCESS") except Exception as e: return HttpResponse(str(e)) Here I've added an exception which would occur all the time. My only intension is to obtain a rollback after I call manual exception. First transaction is successfully rolled back when I use SQLite3(default django Database). But the transaction is not rolled back when I use MySQL. Using InnoDB mysql database. -
Django Python ProcessPoolExecutor Zip on the fly
I'm looking for speeding up a function that generate a zip on the fly. I have no other choice because users must download different files based on roles and can't prepare them in advance. I discover ProcessPoolExecutor that allow us to use parallel tasks to speed up serial functions. So i would like to know if it's possible for zip on the fly creation. Following my actual code which take 22,4s seconds to generate for 1900 files (jpg and pdf) for a zip of 416,7mo zipFilename = "%s.zip" % "test" buffer = BytesIO() zip = zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) for filepath in filepaths: absfilepath = os.path.join(settings.MEDIA_ROOT, filepath) filedir, filename = os.path.split(absfilepath) zip.write(absfilepath, os.path.join(zipFilename, filename)) zip.close() response = HttpResponse(buffer.getvalue(), content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=test.zip' response['Content-Length'] = buffer.tell() response.status_code = self.responseStatus = status.HTTP_200_OK buffer.seek(0) return response -
Django Guardian remove_perm not working (Permissions stay)
According to the Django Guardian docs I should be able to do something like this: user = User.objects.get(username="foo") user.has_perm("app.can_view_bar", bar_obj) >> True remove_perm("app.can_view_bar", user, bar_obj) user = User.objects.get(username="foo") user.has_perm("app.can_view_bar", bar_obj) >> False In my case, it always returns True, even after I've called remove_perm() to delete the permission. When I call remove_perm() I get (0, {'guardian.UserObjectPermission': 0}) returned, which I assume means that 0 items were removed or deleted. Anyone done this in the past? How to remove permissions with Django Guardian? -
Django GIS : Using location__dwithin gives Unable to get repr for <class 'django.db.models.query.QuerySet'> however location__distance_lte works fine
I have the following two queries. The first one works fine however the last one which uses location__dwithin returns back Unable to get repr for . Any suggestions on why the last one fails ? querySet = modelEmployee.objects.filter(location__distance_lte=(modelemp.location, D(mi=shared.DEFAULT_QSET_RANGE))) and the other one is: querySet = modelEmployee.objects.filter(location__dwithin=(modelemp.location, D(mi=shared.DEFAULT_QSET_RANGE))) -
'ForeignKey' object has no attribute
When I try to make migrations for the following models: class Location(models.Model): name = models.CharField(max_length=200) latitude = models.FloatField longitude = models.FloatField altitude = models.IntegerField def _str_(self): return self.name def getLatitude(self): return self.latitude def getLongitude(self): return self.longitude class Distance(models.Model): placeA = models.ForeignKey(Location, on_delete=models.CASCADE) placeB = models.ForeignKey(Location, on_delete=models.CASCADE) placeAlatitude = placeA.getLatitude() placeBlatitude = placeB.getLatitude() placeAlongitude = Location.objects.select_related().get(placeA.longitude) placeBlongitude = Location.objects.select_related().get(placeB.longitude) distance = models.FloatField(default = 0.0) I am getting the error: 'ForeignKey' object has no attribute 'getLatitude' I get a similar error if I try to directly access the latitude directly (placeA.latitude) What am I doing wrong? I am new to using the Django framework. -
How to pass value inside html content in django 2
I was trying to create an appointment system where appointment system will send mail to the user where mail data will be dynamic but the problem is how cloud I pass data inside html_content like the date is a variable how can I pass date value inside Meeting Date Here is my Code subject, from_email, to = 'You Have A Meeting Request', 'send@gmail.com', 'text@gmail.com' text_content = 'Dear Sir,' date = 12-12-2018 html_content = '<p>This is an ' \ '<strong>Meeting Request</strong>' \ ' <ul>' \ '<li><b>Meeting Date:</b> {{ date }}</li>' \ '<li><strong>Meeting Place:</strong> DRL , Meeting Room 1</li>' \ '<li><strong>Time:</strong> 10-30 To 13-30</li>' \ '<li><strong>Meeting Purpose:</strong> For Opening Appointment</li>' \ '<li><strong>No Of Person:</strong> 5</li>' \ '<li><strong>Priority:</strong> High</li>' \ '<li><strong>Request By:</strong> Mr X</li>' \ '</ul>.</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() -
Get the subtotal price and total price in django admin using javascript
How can I get the subtotal and total price in django admin? basically I am returning calculated field in the admin as readonly_field following this Display Total amount in the admin interface now I want it updating in the admin interface here is my admin What am basically asking is how to add Javascript to make the change instant in the template -
how to implement django-push-notifications for ios in details? providing all sample code
from push_notifications.models import APNSDevice, GCMDevice device = APNSDevice.objects.get(registration_id=apns_token) device.send_message("You've got mail") ` Here push_notifications models in APNDevice is not understood can anyone post example code with model details -
Applying changes in django/docker files
I'm new at the development with django and docker and I have a problem when I change a file in the project. My problem is as fallows: I make changes in the content of any file in the django project (Template, view, urls) but it does not update in my current running app. Always I want to see my changes I need to restart the server (I'm using nginx) doing docker-compose up. Is there a package or a alteration that I should install/do to make it able to accept change in running time? This is my Dockerfile: FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir -p /opt/services/djangoapp/src COPY Pipfile Pipfile.lock /opt/services/djangoapp/src/ WORKDIR /opt/services/djangoapp/src RUN pip install pipenv && pipenv install --system RUN pip install pipenv && pipenv install --system RUN pip install django-livereload COPY . /opt/services/djangoapp/src RUN cd hello && python manage.py collectstatic --no-input EXPOSE 8000 CMD ["gunicorn", "-c", "config/gunicorn/conf.py", "--bind", ":8000", "--chdir", "hello", "hello.wsgi:application"] Let me know any other information that I might provide to give a better glimpse of the problem (if it is not clear enough). -
Django pass variable into template
Hi thank you for helping, I'm poor in coding. To point: I'm doing a Django project that pass data form data-base to front-end; but right now i can't even pass anything views of Django into templates, I suspect i'm passing the wrong variable types; please do comment on your thought. This is my code on views.py: from django.shortcuts import render Def index (requset): return render(requset,'myapp/index.html') # link to be able open frountend Def testdex(requset): text = "hello world" context ={'mytext' : text } return render(requset,'myapp/inculdes.html', context) so my variable will be pass into inculdes where extend to index page This my codes on in inculdes.html: {% exntends "myapp/index.html" %} {%block includes%} {{mytext}} {%endblock includes%} this my code on index.html: <body> {%block includes%} {%endblock includes%} </body> Thanks again on giving me your time to help me and appreciate it if could write me some code because try fix this for whole week