Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Celery task and transacrtion
assuming that you have some Model that contains unique field and you have an async task that saves a new instance of the model to DB. something like this: @shared_task def create_model(model_identifier): with transaction.atomic(): serializer=MyModelSerializer(data=model_data) serializer.is_valid() serializer.save() . . . some more actions And you create 2 of those tasks one after the another, with the same identifier. The first one will save the new instance first, so when the second one arrives to the 'save()' part - the object is already exists but it's not committed yet. What should happen in that case? If I get it right, it looks like when the second one arrives to the 'save()' (after the is_valid() passes), it awaits for the first one to finish the transaction (although they basically run in parallel) and only then an integrityError exception is raised. Does it sound right? -
Trouble integrating Django-cms with django-2.0.3
I realize there is a subjective element to this question but I have to ask for help from this community. This is the first time I'm dabbling with django-cms. It uses django-1.11 whereas the current django --V is 2.0.3 . I need to use --v 2 and last night I was trying to make django-cms compatible with django2.0.3 . Trust me, it's a nightmare. After around 20 fixes, I gave up. The docs aren't very good either - for instance, what should 'on_delete' do? - models.CASCADE, models.DO_NOTHING, etc, etc,-and it differs for many2 many relns, many2one relns, etc. Therefore my question is - is it worth the effort and time to try and make both work together (once again, I have to go with django-2.0.3 - that is non-negotiable) or just skip it and try to develop a CMS with pure django (& some plugins/libraries, perhaps). The project will have multiple pages and should have the functionalities to edit both from the front-end side and back-end side. A few tables would receive dynamic data which has to be displayed immediately. There's more to the project but for now, this is the requirement. Am I trying to use a bulldozer to … -
django - showing OrderedDict in templatetag
I have a OrderedDict and I need to show its key, value but I am unable to get its value, I have this dict = ([('sainbath', 'thesailor'), ('HELLO', 'WORLD')]), I have tried this {{object.specifications}} <ul> <li>{% for key in object.specifications %} {{key}} {%endfor%} I am getting this output OrderedDict([('sainbath', 'thesailor'), ('HELLO', 'WORLD')]) sainbath HELLO I am getting its key only not value, when I tried this {{object.specifications}} <ul> <li>{% for key,value in object.specifications %} {{key}} : {{value}} {%endfor%} it give me error Need 2 values to unpack in for loop; got 8. please tell me how can I get value? -
Django: Filter & function
I have currently these to utils functions. The only difference between unique_account_link_generator and unique_order_id is what they filter within qs_exists. It's either .filter(slug=new_id) or .filter(order_id=new_id) I now wonder is there a way to combine them and then being able to define the filter method when I call the function: unique_id_generator(instance, _filter = "order_id") import random import string def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) def unique_account_link_generator(instance): """ 1. Generates random string 2. Check if string unique in database 3. If already exists, generate new string """ new_id = random_string_generator() myClass = instance.__class__ qs_exists = myClass.objects.filter(slug=new_id).exists() if qs_exists: return unique_account_link_generator(instance) return new_id # How to send field_name via function? def unique_id_generator(instance): """ 1. Generates random string 2. Check if string unique in database 3. If already exists, generate new string """ new_id = random_string_generator() myClass = instance.__class__ qs_exists = myClass.objects.filter(order_id=new_id).exists() if qs_exists: return unique_id_generator(instance) return new_id -
angular django rewrite unmatched urls to index.html (angular app)
I have a django server and an angular app. I am able to launch the angular app and navigate to the various parts of the site using links i have added to the app. But if I want to go to a part of the site directly I get a 404 error. example if I have a link in my app that directs me to niftysite.com/team it works but if I put in my browsers url niftysite.com/team it fails with 404 I understand this is because the default behavior is to look for the link to the page in the servers urls. I also understand that the fix is to have server side 404s redirect to the angular index.html page with the route params included. My question is how? I have already started on an implementation but I am not sure how to fix it. Any guidance the rest of the way through would be helpful. here is what I have so far. urls.py handler404 = views.error_404 views.py from django.shortcuts import render def error_404(request): data = {} return render(request, 'index.html', data) -
How to choose a Wagtail image across a ParentalManyToManyField?
Environment: Wagtail 1.13 Django Version: 1.11.11 Python Version: 2.7.12 I'm following the Wagtail documentation to try to add an image showcase (not a category) to a page using ParentalManyToManyField: class HomePage(Page): showcase_title = models.CharField(max_length=100, blank="true", default="SHOWCASE") showcase_images = ParentalManyToManyField('wagtailimages.Image') content_panels = Page.content_panels + [ FieldPanel('showcase_title'), InlinePanel('showcase_images', label="Showcase images", panels=[ ImageChooserPanel('showcase_images') ]), ] Everything is fine if I comment out the showcase_images editing panel, but I get a KeyError as soon as uncomment the panel showcase_images. In addition to the above variation of editing showcase_images, I've also tried simply InlinePanel('showcase_images'), FieldPanel('showcase_images'), InlinePanel('showcase_images', label="Showcase images", panels=[ImageChooserPanel('image')]), and probably another variation or two. Can someone propose a solution? Environment: Request Method: GET Request URL: http://dev.somedomain.com:8181/admin/pages/3/edit/ Django Version: 1.11.11 Python Version: 2.7.12 Installed Applications: [u'my_app', u'search', u'wagtail.wagtailforms', u'wagtail.wagtailredirects', u'wagtail.wagtailembeds', u'wagtail.wagtailsites', u'wagtail.wagtailusers', u'wagtail.wagtailsnippets', u'wagtail.wagtaildocs', u'wagtail.wagtailimages', u'wagtail.wagtailsearch', u'wagtail.wagtailadmin', u'wagtail.wagtailcore', u'wagtail.contrib.wagtailstyleguide', u'modelcluster', u'taggit', u'wagtailfontawesome', u'django.contrib.admin', u'django.contrib.auth', u'django.contrib.contenttypes', u'django.contrib.sessions', u'django.contrib.messages', u'django.contrib.staticfiles'] Installed Middleware: [u'django.contrib.sessions.middleware.SessionMiddleware', u'django.middleware.common.CommonMiddleware', u'django.middleware.csrf.CsrfViewMiddleware', u'django.contrib.auth.middleware.AuthenticationMiddleware', u'django.contrib.messages.middleware.MessageMiddleware', u'django.middleware.clickjacking.XFrameOptionsMiddleware', u'django.middleware.security.SecurityMiddleware', u'wagtail.wagtailcore.middleware.SiteMiddleware', u'wagtail.wagtailredirects.middleware.RedirectMiddleware'] Traceback: File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/django/views/decorators/cache.py" in _cache_controlled 43. response = viewfunc(request, *args, **kw) File "/opt/virtualenvs/gmmiTMID/lib/python2.7/site-packages/wagtail/wagtailadmin/urls/__init__.py" in wrapper 96. return view_func(request, *args, … -
Django dependent forms with foreignkey
I have two models: class Home(models.Model): name = ... # some technical info address = models.ForeignKey(Address) class Address(models.Model): city = ... street = ... # etc... How to serve this two form in view like one form? When I create ModelForm class HomeForm(forms.ModelForm): class Meta: model = Home fields = [ 'name', 'address'] I got select input, but I want to get all fields from Address form separately, no one select to Address object. -
Is it possible to query Django objects by their FileField's url attribute
I have a Django class with a FileField. I know that you can get the FileField's url, or path, by calling filefield.path, or filefield.url . I tried to query for all of those objects by their FileField's url using media = MediaLibraryFile.objects.filter(media_file__url='some_key') but I get this error. Unsupported lookup 'url' for FileField or join on the field not permitted. I looked around the web, and found that you can only use lookup fields on foreignkey related objects, so my question is how can you query objects by file field url if thats the case ? It seems like this would be a very common query performed. -
django email fails to send in production, works for errors, fails for a particular view
I'm trying to automatically send an email with a django contact us form. The contact form view works in development properly via django.core.mail.backends.console.EmailBackend Sending of emails to admins for errors in procution works properly. However sending emails for the contact view/form doesn't work in production. No errors are produced in production when submitting the contact form. the post request appears in the logs, but there isn't any other useful information (that I can see) apart from that. I'm not sure how best to pinpoint the error? view: @require_http_methods(['GET', 'HEAD', 'POST']) def contact_view(request): form = ContactForm() if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): contact_name = form.cleaned_data.get('contact_name', '') contact_email = form.cleaned_data.get('contact_email', '') email_content = form.cleaned_data.get('message', '') email = EmailMessage( subject="New contact form submission", body=email_content, to=('support@somedomain.com',), from_email=f'{contact_name} <{contact_email}>', reply_to=(contact_email,), ) email.send() messages.success(request, "Your email has been sent. Thanks for contacting us, we'll get back to you shortly") return redirect('contact') context = {'form': form} return render(request, 'pages/contact.html', context) production email settings: DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL', default=' <noreply@some_domain.com>') EMAIL_SUBJECT_PREFIX = env('DJANGO_EMAIL_SUBJECT_PREFIX', default='[some_domain]') SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL) # Anymail with Mailgun INSTALLED_APPS += ("anymail", ) ANYMAIL = { "MAILGUN_API_KEY": env('DJANGO_MAILGUN_API_KEY'), "MAILGUN_SENDER_DOMAIN": env('MAILGUN_SENDER_DOMAIN') } EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend" -
ImageField with django-storages leads to: "Error parsing the X-Amz-Credential parameter; the region 'us-east-1' is wrong; expecting 'us-west-1'"
I'm trying to add an ImageField to a model called LucyGuide which will save user-uploaded images to S3 using django-storages. Here is the (simplified) model: class LucyGuide(TimeStampedModel): headshot = models.ImageField(upload_to='uploads/', null=True) bio = models.TextField(blank=True) I've added the following to my settings.py: # Use Boto3 backend to interact with Amazon's S3 DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # Amazon S3 credentials (for django-storages) AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID', default='') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY', default='') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME', default='') AWS_S3_REGION_NAME = os.getenv('AWS_S3_REGION_NAME') AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } # Use v4 of the signing protocol (recommended for all new projects) AWS_S3_SIGNATURE_VERSION = 's3v4' where the actual keys are read from a .env file (using a mechanism similar to django-decouple). To try this out, I uploaded a random picture for a LucyGuide in Django's admin UI: In the shell, I'm able to access the url attribute of the guide's headshot field, which is indeed a link to an AWS bucket: In [6]: guide = LucyGuide.objects.filter(bio__startswith="Kristen").first() In [7]: guide Out[7]: <LucyGuide: Kristen Hoover> In [8]: guide.headshot Out[8]: <ImageFieldFile: uploads/320px-Waaah.jpg> In [9]: guide.headshot.url Out[9]: 'https://lucy-prod.s3.amazonaws.com/uploads/320px-Waaah.jpg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIMC2A%2F20180327%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20180327T200248Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=ae75dbdd75d13020113c12ef2d655e3' (where I've deleted parts of the URL). The problem is that when I try to go to this URL in the browser, I get a "This … -
pipenv cant install django
So I just recently got into coding, and I'm using pipenv to set up a virtual environment and trying to install django in the virtual environment. I'm using python 3.6.4, but have tried installing with 3.5 as well and get the same error. After running 'pipenv install django' I get this error: Installing django… Collecting django Using cached Django-2.0.3-py3-none-any.whl Collecting pytz (from django) Using cached pytz-2018.3-py2.py3-none-any.whl Installing collected packages: pytz, django Successfully installed django-2.0.3 pytz-2018.3 Adding django to Pipfile's [packages]… Pipfile.lock (711973) out of date, updating to (220011)… Locking [dev-packages] dependencies… Locking [packages] dependencies… raise SSLError(e) requests.packages.urllib3.exceptions.SSLError: [Errno 2] No such file or directory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/pipenv/resolver.py", line 82, in <module> main() File "/usr/local/lib/python3.5/dist-packages/pipenv/resolver.py", line 71, in main clear=do_clear, File "/usr/local/lib/python3.5/dist-packages/pipenv/resolver.py", line 63, in resolve verbose=verbose, File "/usr/local/lib/python3.5/dist-packages/pipenv/utils.py", line 471, in resolve_deps timeout=10, File "/usr/local/lib/python3.5/dist-packages/pipenv/vendor/requests/sessions.py", line 488, in get return self.request('GET', url, **kwargs) File "/usr/local/lib/python3.5/dist-packages/pipenv/vendor/requests/sessions.py", line 475, in request resp = self.send(prep, **send_kwargs) File "/usr/local/lib/python3.5/dist-packages/pipenv/vendor/requests/sessions.py", line 596, in send r = adapter.send(request, **kwargs) File "/usr/local/lib/python3.5/dist-packages/pipenv/vendor/requests/adapters.py", line 497, in send raise SSLError(e, request=request) requests.exceptions.SSLError: [Errno 2] No such file or directory I'm new to linux and development in … -
When using django-reversion, all revisions appear the same
This bug that got weird quickly. In a fairly complex django project, I noticed that it's impossible to revert anything registered with django-reversion. The displayed history of changes is accurate (dates and comments on what was changed match reality), but visiting object's /history/rev_number always shows form pre-filled with newest version present. I confirmed that revisions actually stored in the DB are fine, contain correct data in serialized_data field, and are not identical. Only after rendering history/revision view, the resulting HTML contains newest values. Then I created a new model in this project, made a few changes, tried reverting them - same bug appeared. There are no admin customizations to this new model. Furthermore, I removed my custom template directories to make sure nothing non-standard affects rendering. Still, bug is there. Finally, I created a new django project with a single reversion-registered model, made a few changes and tried reverting - the bug still appeared. This is a project made from scratch, having nothing in common with the main one. In desperation, I removed and re-built a virtualenv with fresh Python installation and installed all the requirements for the main project, and added all dependencies of main project to INSTALLED_APPS of … -
Prevent loading of data with select2 until minlength is met
I'm not sure if i'm going about this the correct way, but if you have any constructive comment that can help lead me in the right direction please share. I've been stuck on this for quite some time. I have the following select2 control that is loading the entire table for a field of that table. There is a function with select2 called minimumInputLength, which still seems to load the table in it's entirety instead of querying on the first three characters. The pagination works correctly as shown in this fiddle.js: http://jsfiddle.net/jgf5fkfL/66/ $.fn.select2.amd.require( ['select2/data/array', 'select2/utils'], function (ArrayData, Utils) { function CustomData($element, options) { CustomData.__super__.constructor.call(this, $element, options); } function contains(str1, str2) { return new RegExp(str2, "i").test(str1); } Utils.Extend(CustomData, ArrayData); CustomData.prototype.query = function (params, callback) { if (!("page" in params)) { params.page = 1; } var pageSize = 50; var results = this.$element.children().map(function (i, elem) { if (contains(elem.innerText, params.term)) { return { id: [elem.innerText, i].join(""), text: elem.innerText }; } }); callback({ results: results.slice((params.page - 1) * pageSize, params.page * pageSize), pagination: { more: results.length >= params.page * pageSize } }); }; $(".js-example-basic-multiple").select2({ ajax: {}, minimumInputLength: 3, allowClear: true, width: "element", dataAdapter: CustomData }); }); The problem is my view is loading the … -
Activate and run a jQuery script using a value from a Django view?
On a Django template I have a form that allows users to upload images to a remote server. Once the upload is complete, the server returns the url to the image to my Django view. I have this image url as a string in my view. How can I use this url to activate and be used in a jQuery script? I'd like to append it a form without refreshing the page. I'm pretty sure I'm supposed to be returning a JsonResponse and using an Ajax sciprt, but I am pretty new to this and am having a hard time getting it working. I'm not getting any errors from the Ajax script, and I can see the img_url is in the JsonResponse content, but when I upload a file, nothing happens. This is the relevant bits to what I have so far: Django View: else: img_form = forms.PostImageForm(request.POST, request.FILES or None) if img_form.is_valid(): new_img = models.PostImage.objects.create(post=post) new_img.file = request.FILES['file'] new_img.save() img_url = new_img.file.url return JsonResponse({'img_url': img_url}) HTML/Ajax: <script> function append_form() { $.ajax({ method: "POST", url: "/blogs/{{topic}}/{{post_url}}/edit_post/", data: {}, success: function(){ var contentField = $("#myPostForm textarea[name=content]"); contentField.val( contentField.val() + "<img src='" + data.img_url + "' >" ); } }) }; </script> -
Django unique for one object (not global)
In the Django model, one django user shall have many devices (one to many relation). This device shall have a globally(!) unique mac address, which means no other user has a device with that mac address. Thats why I used "unique = true" which is easy. But how do I allow one user to choose the devicename freely but with the restriction that the chosen devicename is just allowed once for himself (not globally unique, just for this single user). What I mean is, there can be two Users "UserA" and "UserB", both can name their device "pikachu" but "UserA" must not call a second device of his "pikachu" again. This is my model. from django.db import models from django.contrib.auth.models import Userfrom datetime import date from django.db.models.signals import post_save class Device(models.Model): user = models.ForeignKey(User) mac = models.CharField(max_length=17, default='00:00:00:00:00:00', unique=True) devicename = models.CharField(max_length=20, default='', unique=True) Any ideas? -
Django manytomany form for imagefield
I am not a Django pro and I have a Question which is almost similar to this django manytomany multiple upload file, my app name is called "myprofile" and my models look like this # myprofile/models.py class Image(models.Model): image_file = models.ImageField(upload_to='images/', null=True, blank=True) def __unicode__(self): return unicode(self.image_file.url) class Thumbnail(models.Model): image_files = models.ManyToManyField(Image) I want a form with browse button and when I click it I can select and add multiple images. And later if I want, I can change the detail of image ( similar to the problem in the link I posted above ) The Image model returns the urls of image_file e.g "images/img01.jpg" The main problem here is how to create a form with a browse button to upload multiple images and with the ability to change the image if there is need to do so . I tried to use inline formset so here is my forms.py # myprofile/forms.py from django.forms import ModelForm, inlineformset_factory from .models import Image, Thumbnail class ImageForm(ModelForm): class Meta: model = Image exclude = () class ThumbnailForm(ModelForm): class Meta: model = Thumbnail exclude = () ThumbnailFormSet = inlineformset_factory(Image, Thumbnail, form = ThumbnailForm, extra=1) Now before I even proceeded to views.py I got the … -
Checkbox not rendering when materialize css is used in html page
Checkbox not rendering in the html page when materialize css is used. I am trying to use materialize css for my Django form. I tried in the Django form and it didn't work. So, I tried a separate sample html page. Still checkbox doesn't render. I have attached of screenshot of the rendered html page. "Married" checkbox can be seen without a checkbox. I tried using inspector tool on the page and seems like a checkbox is there but it is not visible. Below is the sample html code I tried using to test the functionality. <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jQuery UI Datepicker - Default functionality</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script> <script> $( function() { $('.collapsible').collapsible(); $( "#datepicker" ).datepicker(); } ); </script> </head> <body> <p>Date: <input type="text" id="datepicker"></p> <div class="container"> <h2>Collapsible Panel</h2> <p>Click on the collapsible panel to open and close it.</p> <div class="panel-group"> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" href="#collapse1">Collapsible panel</a> </h4> </div> <div id="collapse1" class="panel-collapse collapse"> <div class="panel-body">Panel Body</div> <div class="panel-footer">Panel Footer</div> </div> </div> </div> <ul class="collapsible"> <li> <div class="collapsible-header"><i class="material-icons">filter_drama</i>First</div> … -
python - transform a C# method in python method
I'm new in Python and I trying to make this C# method protected void read(){ string[] attributes = new string[16]; attributes[0] = "ref_num"; attributes[1] = "tenant.name"; attributes[2] = "request_by.first_name"; attributes[3] = "request_by.first_name"; attributes[4] = "customer.first_name"; attributes[5] = "customer.last_name"; attributes[6] = "customer.id"; attributes[7] = "category.sym"; attributes[8] = "status.sym"; attributes[9] = "group.last_name"; attributes[10] = "zreporting_met.sym"; attributes[11] = "assignee.combo_name"; attributes[12] = "open_date"; attributes[13] = "close_date"; attributes[14] = "description"; attributes[15] = "summary"; int sid = soap.login("user", "pass"); string objectType = "cr"; string whereClause = "ref_num = '15967'"; int maxRows = -1; //Valor de tiempo en Epoch var epoch = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds; //Transforma en valor de fecha humana string _epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(epoch).ToShortDateString(); ArrayList resultado = new ArrayList(); XmlDocument xml = new XmlDocument(); try { string _selectResponse = soap.doSelect(sid, objectType, whereClause, maxRows, attributes); xml.LoadXml(_selectResponse); XmlNodeList nodeList = xml.GetElementsByTagName("AttrValue"); for (int i = 0; i < nodeList.Count; i++) { resultado.Add(nodeList[i].InnerXml); } soap.logout(sid); } catch (Exception l) { Console.Write(l.Message); } } this method works perfectly, in python I have this for the moment class WebService: soap = 'webservice url' client = Client(soap) sid = client.service.login("user","pass") attributes = ["ref_num", "open_date"] objectType = "cr" whereClause … -
IntegrityError when sending multiple post requests
I am sending a post request for each tag front-end is here: handleOnClick() { const { resource, csrf } = this.props; let postFunc = (ele) => { const label = ele.label.toLowerCase() request .post(`/bookmarks/groups/${label}`) .set('X-CSRFToken', csrf) .send(resource.id).then(() => { console.log('we did it') }) } _(this.state.multiValue).forEach(postFunc) Both post request seem to deliver, but any one after the first get and integrity error. My view: def post(self, request, slug): """Create a bookmark of the resource for the current user.""" # print request.user to_add = Resource.objects.get(id=int(request.body)) try: bm = Bookmark.objects.get(resource=to_add) except Bookmark.DoesNotExist: bm = Bookmark.objects.create(user=request.user, resource=to_add) bookmark_group = BookmarkGroup.objects.get(name=slug) bookmark_group.bookmarks.add(bm) return JsonResponse({}, status=201, safe=False) I am essentially checking to see if a bookmark is exists, and if it doesn't I create it. Bookmark and group models: class Bookmark(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) resource = models.ForeignKey("Resource", on_delete=models.CASCADE, related_name="bookmarks") # meta created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class Meta: unique_together = ('user', 'resource',) ordering = ('resource',) def __str__(self): return "{} | {}".format(self.user, self.resource) class BookmarkGroup(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(null=False, unique=True) bookmarks = models.ManyToManyField(Bookmark, related_name='bookmarks', blank=True) def __str__(self): return self.name I've included the stack-trace, and can include more code if needed: Traceback (most recent call last): File "/Users/path/to/my/venv/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) … -
django __str__ returned non-string(type tuple)
Hello i'm studying django, and i have a problem with def str on models models.py class Student(models.Model): id = models.AutoField(primary_key=True) school_year = models.CharField(max_length=4,choices=SCHOOL_YEAR_CHOICES,default='2019') campus = models.CharField(max_length=1,choices=CAMPUS_CHOICES,default='M') type = models.CharField(max_length=1,choices=TYPE_CHOICES,default='N') affiliate = models.CharField(max_length=1,choices=AFFILIATE_CHOICES,default='N') name = models.CharField(max_length=30, unique=True) def __str__(self): return self.name,self.campus class Comment(models.Model): student = models.ForeignKey(Student, related_name='comments',on_delete=models.CASCADE) created_by = models.ForeignKey(User,related_name='comments',on_delete=models.CASCADE) message = models.TextField(max_length=1000, unique=False) about = models.CharField(max_length=1,choices=ABOUT_CHOICES,default='L') created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __str__(self): return self.created_by.first_name, self.student.name if i remove that " student = models.ForeignKey ~~" it'll work i think 'student' on comment is problem anyone help? thanks and i'm using python3 with the lastest version of django -
django sitemaps multilang and duplicate content
My site is about hotels and has 3 langs: en, es and fr. en is the default, when the user load a page that has not been translated yet the default is showed, but the url remains with the intended lang. for exampe domain.com/fr/hotels/123/ and this page is not translated for fr the user gets the en version, which is duplicated content for differents urls. After appling the sitemap framework that ships with django I got this (a fragment of the entire sitemap.xml) <url> <loc>http://www.example.com/en/hotels/599/</loc> <lastmod>2018-03-27</lastmod> <changefreq>weekly</changefreq> <priority>0.7</priority> </url> ... <url> <loc>http://www.example.com/es/hotels/599/</loc> <lastmod>2018-03-27</lastmod> <changefreq>weekly</changefreq> <priority>0.7</priority> </url> ... <url> <loc>http://www.example.com/fr/hotels/599/</loc> <lastmod>2018-03-27</lastmod> <changefreq>weekly</changefreq> <priority>0.7</priority> </url> My question is whether this approach will affect my SEO, because of the problem of duplicate content. -
Django populate formset data when editing form
I have two models Chapter and ChapterQuestion. I'm using formset to create multiple ChapterQuestion records while creating Chapter record and it's working fine. But, when I edit the form, it does not populate formset values. I'm using UpdateView to update the record class EditChapter(UpdateView): model = Chapter form_class = ChapterForm template_name = 'courses/chapter/edit_chapter.html' def get_context_data(self, **kwargs): context = super(EditChapter, self).get_context_data(**kwargs) course = Course.objects.get(pk=self.kwargs['course_id']) if course is None: messages.error(self.request, 'Course not found') return reverse('course:list') context['course'] = course if self.request.POST: context['chapter_questions'] = ChapterQuestionFormSet(self.request.POST) else: context['chapter_questions'] = ChapterQuestionFormSet() return context def form_valid(self, form): context = self.get_context_data() chapter_questions = context['chapter_questions'] with transaction.atomic(): self.object = form.save() if chapter_questions.is_valid(): chapter_questions.instance = self.object # chapter_questions.instance.created_by = self.request.user chapter_questions.save() return super(EditChapter, self).form_valid(form) def get_success_url(self): return reverse('course:detail', kwargs={'pk': self.kwargs['course_id']}) @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(self.__class__, self).dispatch(request, *args, **kwargs) The urls.py contains path('<course_id>/chapter/<uuid:pk>/edit', EditChapter.as_view(), name='edit_chapter'), and in template, I'm using crispy form <form method="POST" role="form" class="form"> {% csrf_token %} <h3 class="panel-title">Chapter Detail</h3> <label for="chapter-name">Chapter Name</label> <input name="name" placeholder="Chapter Name" value="{{ chapter.name }}" id="chapter-name"> <h3 class="panel-title">Add Question to Chapter</h3> {{ chapter_questions|crispy }} </form> {{ chapter_questions|crispy }} renders the form fields but fields are empty. forms.py from django.forms import ModelForm, inlineformset_factory from courses.models import Chapter, ChapterQuestion class ChapterForm(ModelForm): class Meta: … -
Django get all fields from custom field model
Sorry for my english. I have model class Companies(models.Model): .. managers = models.ManyToManyField(User, related_name="managers", blank=True) view class CompaniesList(generics.ListCreateAPIView): queryset = Companies.objects.all() serializer_class = CompaniesSerializer permission_classes = (permissions.IsAuthenticated,) serializer class UsersInCompanySerializer(PrimaryKeyRelatedField, serializers.ModelSerializer): class Meta: model = User fields = ('id', 'first_name', 'last_name', 'email', 'is_active', 'is_staff', 'last_login', 'created_date') class CompaniesSerializer(serializers.ModelSerializer): managers = UsersInCompanySerializer(many=True, queryset=User.objects.all().filter(groups__name='manager')) class Meta: model = Companies fields = ('id', 'managers', .....) but when i get json, i have field managers only id, like this: "managers": [ "6b7f40f2-73a7-43cb-b1b7-4e24374495e8" ], How i can view all field in managers like this: { "id": "97727151-8724-443a-a1c8- "first_name": "", "last_name": "", "email": "admin@gmail.com", "is_active": true, "is_staff": true, "last_login": "2018-03-27T18:23:43.868368Z", "created_date": "2018-03-27T14:54:33.566971Z" } -
django escapejs output is not text, How can I make the escaped output as text rather than a code (< instead of \u003C)
in a django website, I have a text input where a user can enter a text message. I used jquery-shorten plugin to shorten text with a 'see more...' . However, I found that this plugin uses .html() for output and the user message will not be escaped. so I used the |escapejs template filter to escape js as follows: <p class="card-text shorten-text">{{post.message|escapejs}}</p> however, if the user entered: <b> Hello </b> the output will be : \u003Cb\u003E Hello \u003C/b\u003E How can I make the output be escaped and appear as text: <b> Hello </b> -
Django no PUT method
I have a problem with my django rest framework views. The PUT method is calling a GET instead. So I cannot update any objects. Some views were working and now there are not.Here an example of view: class BiduleEditView(generics.RetrieveUpdateAPIView): """A view that allows to edit a position of a promotion """ serializer_class = BiduleEditSerializer queryset = Bidule.objects.filter(is_active=True) Does anybody have an idea ? lookup_fields = 'pk' Here is the corresponding url: url(r'^bidule/(?P<pk>[a-z0-9\-]+)/edit/$', views.BiduleEditView.as_view()),