Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Difficulties in Sage One integration with Django (Python)
I have developed an one page application using AngularJs and Django(Python). I want to integrate Sage One Application with my application for accounting purpose(country US). I have gone through so many links and blogs in google and what I have found that all the libraries are written in PHP, Ruby and some other language. And I could not find any solution. This is the link I followed : https://developer.columbus.sage.com/docs#/us/sageone/core/gs-welcome Then I found another link https://pypi.python.org/pypi/sageone-api-client/0.0.2 for the integration with Python. And here, We need an API Key. I tried to get the API Key by following their instructions. But after asending some email and all still they are asking me to provide some company information and all. And i just lost the process. So Can any one tell whether I am following the right way ? Or I have to build some code as it was written in their PHP Example? Is there any way to get the API key for development purpose? Any help will be appreciated. Thanks. -
Generic Foreign Key with computed content type instead of fk to content type model
The simplest case of creating a generic foreign key is like this: class ModelWithGFK(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') But in my case there are other fields wich I can infer the content type from, so adding a content_type FK is both redundant and prone to cause inconsistency over time. So I tried this: class ModelWithGFK(models. object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') @property def content_type(self): return ContentType.objects.get(..........) but seems like GFK class only accepts the content type argument to be a foreign key: def _check_content_type_field(self): """ Check if field named `field_name` in model `model` exists and is a valid content_type field (is a ForeignKey to ContentType). """ Is there a workaround (perhaps via overriding GFK and some of its methods like get_content_type) or I shall give in, add the FK and live in a constant fear of inconsistency and agony of knowing about this (tiny) inevitable redundancy? -
How can dynamically create permission in django?
Now i can create new groups using Django group module. from django.contrib.auth.models import Group I can assign permissions to group. For example i created a new group "HR" by Group(name="HR") . Now i want to create permission like can_create_hr can_edit_hr I should able to assign this permission to another groups. How can i do ? -
Django wants to load images from s3
I am using django cookiecutter template (https://github.com/pydanny/cookiecutter-django), when generating i choosed WHiteNoise lib, now every file i have css,js,fonts at the begining are loaded from app/staticfiles, but my models if they have imagefield, and when i call in template {{myimage.url}} it wants to load it from Amazon S3, even though its not uploading to S3 (i have it in config but it seems its not working this way). Any idea how i can change that it will load from my staticfiles instead of S3 url? -
DRF. NESTED SERIALIZERS PYTHON. object has no attribute
I have a test here for my django application: class GiftEnSerializerTest(APITestCase): def test_if_GiftEnSerializer_return_required_fields(self): data = { 'gift': '1', 'name': 'Neapoletan', 'description': 'A very delecios pizza!', 'short_description': 'Eat our pizza and be happy!', 'categories': 'Pizzas', 'partner': 'PizzaMania', 'addresses': 'Miron Costin 15/3' } serializer = GiftEnSerializer(data) self.assertEqual(serializer.data, "") It gives me error, when i try to run it - AttributeError: 'dict' object has no attribute 'gift' Here is serializer: class PhotoSerializer(DynamicFieldsModelSerializer): picture_url = serializers.SerializerMethodField() class Meta: model = GiftPicture fields = ('picture', 'picture_url') def get_picture_url(self, obj): return self.picture.url And models: class GiftPicture(models.Model): gift = models.ForeignKey(Private, related_name='gift_picture', on_delete=models.CASCADE) picture = models.ImageField(upload_to="gift_galery") -
why showing Reverse for 'delete' with arguments '(27,)' not found. 1 pattern(s) tried: ['del/$']....?
i was trying to delete a record in model, can't query the object by id my code Html : <a href="{% url 'todo:delete' todo.id %}">DELETE</a> url.py : url(r"^del/$" ,views.DeleteContent,name="delete"), views.py : def DeleteContent(request,u_id): if not request.user.is_authenticated(): return redirect('accounts:login') #todo=ToDo.objects.all() todo=ToDo.object.filter(u_id=id) todo.delete() return render(request,"index.html") -
How to apply 301 redirect in urls.py in dajango python
I want to redirect my old url to new url .http://www.cancleanpressurewashers.com/ to http://royturk.macraesdev.com/services/shop-service-repair/ . Here this will be redirected to different domain. -
django best way of managing template and it's views
In django is it the only way to have only one view for one whole page/url. And whatever functions(upload/post/update/log-in) that page contains just needs to pass inside that view. I found this is the only way as i can only return one url with one view. I am wondering if there has any way where i can make different view(may be classed base or normal) for each function and at last add all of them on one single view(that view return that url also). If it is possible than how ? Because having all the functions of a url inside one view is looking weird and messy to me. -
Convert SQLite to Django ORM
I have a query in SQLite which groups the fields by weeks and performs sum and average over distance and time fields in the same table: select strftime('%W', datetime) WeekNumber, sum(distance) as TotalDistance, sum(distance)/sum(time) as AverageSpeed from sample_login_run group by WeekNumber; I am trying to convert this query to Django ORM and avoid using Raw function. I understand that I would need to use extra in Django ORM. That should not be a problem though. I came up this: Run.objects.extra(select={'week': "strftime('%%W', datetime)"}).values( 'week','distance').annotate( total_distance=Sum('distance'), average_time=F('distance') / F('time')) But this is also grouping the data by average_time and average_distance field. Any help will be really appreciated. Thank you. -
in my program if statement doesnt return any object in django else statement is executing
class wenket(View): print "qqqqqqqqqqqqqq" def get(self,request): number1=request.GET['number'] print"bbbbbbbbbb",number1 return self.primenumbdef(number1) def primenumbdef(self,number1): print"aaaaaaaaaaaaaaaaaaaaaaaa" if number1==100: return HttpResponse(d({"value of number is 100":number1})) else: return HttpResponse(d({"value of number is not 100": number1})) -
Populate Django updateview form filefield with Wavesurfer.js buffer
I'm trying to build an audio editor, where the user can edit the sound waveform and save the trimmed file. Right now I'm able to select a region of the audio (with wavesurfer.js) and load it into a new buffer: document.getElementById("trim").addEventListener("click", function(){ //CREATE NEW BUFFER var buffer = createBuffer(wavesurfer.backend.buffer, duration) //COPY copyBuffer(wavesurfer.backend.buffer, start, end, buffer, 0) // LOAD NEW BUFFER wavesurfer.clearRegions() wavesurfer.empty() wavesurfer.loadDecodedBuffer(buffer) }); }); This works and loads the selection into the wavesurfer buffer. Now I'm trying to figure out a way to load this edited buffer into a Django form through an updateview. The updateview form gets loaded with into a bootstrap modal with some jquery: $(document).ready(function() { $(".contact").click(function(ev) { // for each edit contact url ev.preventDefault(); // prevent navigation var url = $(this).data("form"); // get the contact form url $("#contactModal").load(url, function() { // load the url into the modal $(this).modal('show'); // display the modal on url load }); return false; // prevent the click propagation }); $('.contact-form').on('submit',function() { $.ajax({ type: $(this).attr('method'), url: this.action, data: $(this).serialize(), context: this, success: function(data, status) { $('#contactModal').html(data); } }); return false; }); }); And basically the form is displayed using djangos' form_as.p. The form that is currently displayed with the updateview is … -
Output username from user_id field on separate model in Django Template
When a post is created, the user's User ID is saved to the post table under the user_id field. On the home page (for right now) I'm outputting all the posts in the post table. I want to get the username into the template based off of the user ID on the Post object. models.py class Post(models.Model): user_id = models.IntegerField() post_name = models.CharField(max_length=300) total_votes = models.IntegerField(default=0) created_date = models.DateTimeField() views.py @login_required def home(request): posts = Post.objects.raw('SELECT * FROM posts ORDER BY created_date DESC') return render(request, 'home.html', {'posts': posts}) home.html {% for post in posts %} <div> <a href="posts/{{post.id}}">{{ post.post_name }}</a> <p>{{ post.created_date }}</p> <p>{{ post.total_votes }}</p> <p>{{ post.user_id }}</p> </div> {% endfor %} -
Python & Django: Working on a chroot jail to run a single bash script
I am facing the following problem and I am not sure if my approach is anywhere near 'right'. I've built a Django application that handles students' assignments for a programming subject at university. The original version of this application (https://github.com/elcoya/seal) used a chroot'd daemon to get the code, delivered by the students, place a bash script along-side that code and execute de bash, which could contain any kind of opeartions, like building and testing the students' code. So far... so good. However, running this daemon was a bit of a headache. Since it ran within a jail, the binded /proc, within that jail, became obsolete every time the server was restarted (it was restarted from time to time :( ) or some error occur in the daemon, the process died or was killed, and therefor, stop doing it's job of "correcting" the students' deliveries. To prevent this errors from happening, and have a more trust worthy automatic correction service, I would like to install a 'django-kronos' task (which runs from the crontab in the server) to do the same job. This would be great, but that would mean that from my Django stack code, I would need to move into … -
django model get_absolute_url not working
I have seen an example of using the above method directly on a book. However this is not working actually. Is this method removed in latest versions? Here is the code. In [24]: django_tag Out[24]: <Tag: Django> In [22]: django_tag.get_absolute_url() --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-22-bde20b3ec098> in <module>() ----> 1 django_tag.get_absolute_url() AttributeError: 'Tag' object has no attribute 'get_absolute_url' I looked with dir function. It don't show such method exists. I'm using django v. 1.11. In [23]: dir(django_tag) Out[23]: ['DoesNotExist', 'MultipleObjectsReturned', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_check_column_name_clashes', '_check_field_name_clashes', '_check_fields', '_check_id_field', '_check_index_together', '_check_local_fields', '_check_long_column_names', '_check_m2m_through_same_relationship', '_check_managers', '_check_model', '_check_model_name_db_lookup_clashes', '_check_ordering', '_check_swappable', '_check_unique_together', '_do_insert', '_do_update', '_get_FIELD_display', '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_pk_val', '_get_unique_checks', '_meta', '_perform_date_checks', '_perform_unique_checks', '_save_parents', '_save_table', '_set_pk_val', '_state', 'blog_posts', 'check', 'clean', 'clean_fields', 'date_error_message', 'delete', 'from_db', In [24]: django_tag Out[24]: <Tag: Django> In [25]: dir(django_tag) Out[25]: ['DoesNotExist', 'MultipleObjectsReturned', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_check_column_name_clashes', '_check_field_name_clashes', '_check_fields', '_check_id_field', '_check_index_together', '_check_local_fields', '_check_long_column_names', '_check_m2m_through_same_relationship', '_check_managers', '_check_model', '_check_model_name_db_lookup_clashes', '_check_ordering', '_check_swappable', '_check_unique_together', '_do_insert', '_do_update', '_get_FIELD_display', … -
Post to URL running django
I have a login page Mayan EDMS that's running on django. You would usually login by entering username and password and clicking on the login button. What I need to achieve instead is from my server side which is running on sailsjs to post this username and password. How can I do This? This is an example of the login page mentioned, I want to be able to submit the username and password from my server side instead of manual entry. http://demo.mayan-edms.com This is what I tried but received a 403 Forbidden message. $.post({ Url: "https://mayan/authentication/login/", Data:"username=admin&password=mypass&next=/", Success: function(data){ Console.log(data); } }); -
Django - Column 'user_id' cannot be null
An error occurs when I try to save the data. Column 'user_id' cannot be null. Below are the settings I'm using for the Model class XML(models.Model): nome_destinatario = models.CharField(max_length=255) cnpj_destinatario = models.CharField(max_length=15) user = models.ForeignKey(User) def __str__(self): return self.nome_destinatario Serializer class XMLCreateSerializer(serializers.ModelSerializer): class Meta: model = XML fields = ('nome_destinatario', 'cnpj_destinatario', 'user_id') View xml_create = XMLCreateSerializer(data={'nome_emitente': 'NILVA', 'cnpj_destinatario':'5645654654','user_id': 1}) if xml_create.is_valid(): salvo = xml_create.save() else: salvo = xml_create.errors -
why am i getting "he view post.views.post_new didn't return an HttpResponse object. It returned None instead."?
I am trying to save form data into my database. This is my code in views.py. Please forgive me if it's nonsensical, i started learning Django today. def post_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): Post = form.save(commit=False) Post.save() return redirect('post_detail', pk=Post.pk) else:`enter code here` form = PostForm() return render(request, 'post/index.html', {'form': form} ) -
Django Rest 'api-docs' is not a registered namespace
I'm setting the docs for my api and when I ask for (http://localhost:8000/api/v0/docs/) The app show me this error: NoReverseMatch at /api/v0/docs/ 'api-docs' is not a registered namespace when try to do this <script src="{% url **'api-docs:schema-js'** %}"></script> this is my urls.py file: from django.contrib import admin from django.conf.urls import url, include from django.contrib.auth.models import User from . import views from rest_framework import routers, serializers, viewsets from rest_framework.documentation import include_docs_urls # Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter() router.register(r'goals', views.GoalViewSet) urlpatterns = [ url(r'^goals/$', include(router.urls)), url(r'^docs/', include_docs_urls(title='My API title')), ] I added the namespace to include_docs_urls but it doesn't work. (I have installed coreapi, pygments and markdown). Beforehand thanks for helping me. -
Django post not showing on homepage, but in category list
I made a blog with django. The blog lets the admin create posts and categories. I used bootstrap to align the posts next to each other. This is the homepage of my blog. when the posts reach the other end of the screen. look at the Example below: post1 post2 post3 post4 post5 post6 post7 post8 post9 post10 post11 post12 post 13 post14 post16. post 16 wouldnot show on the homepage, but if you go to its category it will show on the category list but not on the homepage which is index.html Index.html: {% extends 'base.html' %} {% block content %} {% if categories %} <div class="tab"> {% for category in categories %} <button class="tablinks"><a href="{{ category.get_absolute_url }}">{{ category.title }}</a></button> {% endfor %} {% else %} <p>There are no posts.</p> {% endif %} </div> <br><br><br> <div class="container "> {% if posts %} <div class="row "> {% for post in posts %} <div class="poosts col-md-2"> <p class="past"><a class="link" href="{{ post.get_absolute_url }}"><span class="tda"> {{post.title}}</span><br><br><span class="postbody"> {{post.body|truncatewords:13}}</a></span></p> </div> {% endfor %} {% else %} <p class="text-center">There are no posts.</p> </div> {% endif %} </div> {% endblock %} categories page: {% extends 'base.html' %} {% block head_title %}Viewing category {{ category.title }}{% endblock … -
Save data array using serializers in rest framwork in django
Save data array using serializers in rest framwork in django. I created an array of data to save to the database. Fields are populated and are compatible with serialization. But the error below occurs. Thanks for listening data = [{'nome': 'NILVA HELENA DA SILVA', 'cnpj_emitente': '11306471000149'}, {'nome': 'NILVA HELENA DA SILVA', 'cnpj_emitente': '11306471000149'}] xml_create = XMLCreateSerializer(data=data) result Non_field_errors ["Invalid data. Needed a dictionary but received list."] How can I save an array of data using serialization? -
Checking if date in date range in Python but over 100k records
We are trying to overhaul a scheduling application at the moment. It is written in Python/Django and using DRF to power a React frontend. I just have a quick question- apologies if this has been answered already. I have seen Dietrich Epp's answer to this problem on this thread. I am just wondering if I have to check if a time is between two datetime objects over 100k records, what the fastest way to achieve this is? I have considered indexing all of the datetimes in Haystack so that Elasticsearch can deal with the searching but do not want to overcomplicate if it can be solved simply. Thanks all! -
How to get only django-taggit tags posted by user?
I have a Photo model: class Photo(TimestampModerated): owner = models.ForeignKey('auth.User', related_name='photos', on_delete=models.CASCADE) uuid = models.UUIDField(default=uuid4, editable=False) slug = models.SlugField(max_length=80, editable=False) title = models.CharField(max_length=80, blank=False, null=False) description = models.TextField(verbose_name='description of entity', blank=True, null=True) photo = models.ImageField(upload_to=user_directory_path, height_field="height", width_field="width", blank=True) height = models.IntegerField(blank=True) width = models.IntegerField(blank=True) tags = TaggableManager(blank=True) hash = models.CharField(max_length=64, unique=True, null=True) I can get all the tags using this view: @list_route(methods=['get']) def tag_list(self, request): """ get list of tags to search :param request: :return: """ tags = Tag.objects.values_list('name', flat=True) return Response( data=tags ) How can I get only the tags that the owner of the photo has used? -
Cannot successfully parse Django DateField in form
I have: date_due = models.DateField(null=True, blank=True) and a related model form for the class in which the above occurs. All other values validate fine in the model form, but when I put in a date in the format August 25, 2017, I receive an error message: "Enter valid date". In settings.py I have set USE_L10N = True (and also set USE_L18N = False to ensure that only the USE_L10N setting is being observed). In the documentation it says: A list of formats that will be accepted when inputting data on a date field. Formats will be tried in order, using the first valid one. Note that these format strings use Python’s datetime module syntax, not the format strings from the date template filter. and it gives examples. Using the examples given, in my settings I have placed: DATE_INPUT_FORMATS = [ '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' '%d %b %Y', '%d %b, %Y' # '25 Oct 2006', '25 Oct, 2006' ] … -
Trying to install easy_install or pip for gjango
I try to install django and here is what i get when i try to instal pip => " Fatal error in launcher: Unable to create process using '"' When i enter de command => python -m pip install XXX it does not work. Any help ? -
Paypal returning empty QueryDict - Django
I'm adding paypal to my project website. I'm using IPN and at the moment it looks like it works fine apart from the fact that when I return to the merchant's page (paypal_return or paypal_cancel) it doesn't post back the transaction information, I can only see and empty "" in my {{ post }} and {{ get }}. No errors or anything, just that in the page. Here is my code in github. https://github.com/IreneG5/spss_online Any idea why the information is not posted back to my template? Thanks in advance!