Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Celery retry current task with failed data set only
I have the following code from utils import SendSMS from celery.exceptions import * @celery.task(bind=True, max_retries=3) def send_sms(self,sms_list): failed_items = [] for sms_item in sms_list: status = SendSMS( **sms_item ) if status in ['Timeout','Error']: failed_items.append( sms_item ) if len(failed_items) > 0: raise self.retry(failed_items) return "sms(s) send successfully." i want to retry the task but with different data set, with only failed data set i mean how can i achieve this line: raise self.retry(failed_items) ? Thanks in advance. -
Update many to many relation record without removing any existing valid records
Django : 1.11 Python : 3.4 I have a model Pattern that is many to many with Shape through PatternShape class Pattern(ProductVariantParent): name = models.CharField(_('Pattern Name'), max_length=100) serial_number = models.CharField( _('Pattern Number'), max_length=100, unique=True) shape_names = models.ManyToManyField(Shape, through='PatternShape') class PatternShape(models.Model): pattern = models.ForeignKey( Pattern, on_delete=models.CASCADE, related_name='patterns') shape_name = models.ForeignKey( Shape, on_delete=models.CASCADE, related_name='shape_names') I would like to be able to update the list of shapes associated with a single pattern without doing unnecessary deletion I could do a process like this: pattern_instance.shape_names.clear() for shape_instance in new_list_of_shape_data: PatternShape.objects.create( pattern=pattern_instance, shape_name=shape_instance) However, this will mean that unchanged pattern_shape records will be deleted and then subsequently added. Of course, brand new pattern_shape records will definitely be added and no longer valid pattern_shape records will be deleted. I wonder if there is a more elegant way to do this using Django ORM without resorting to mass delete and then adding back. -
random.choice not acting random at all
I have been working on a silly magic item creator that makes use of diffrent lists with stuff that can happen, feelings, coluers and so on. i have been using random.choice to pick from these lists but somehow the items generated do not really seem random at all. when i run it 10 times in a row i get stuff like: A feather that causes horrible visions of an impending disaster, when starring at it A lamp that makes you feel drunk when you lick a person who has something you want A feather that makes you feel drunk when you lick a person who has something you want A dagger that makes you feel drunk when you lick a person who has something you want A feather that causes horrible visions of an impending disaster, when starring at it A lamp that glows white when you touch a person thinking of you A book that makes you feel drunk when you lick a person who has something you want A cane that makes you feel drunk when you lick a person who has something you want A marble that makes you feel drunk when you lick a person who … -
DJANGO HIVE CONNECTIVITY
DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'sampletest', 'OPTIONS': { 'driver': '/opt/cloudera/hiveodbc/lib/64/libclouderahiveodbc64.so', 'dsn': 'Hive1', 'host_is_server': True, }, } } Above is the Django settings for the connectivity with the Hive database; Here I am facing an issue when I run the project which is given below: django.db.utils.Error: ('HY000', u"[HY000] [Cloudera][Hardy] (80) Syntax or semantic analysis error thrown in server while executing query. Error message from server: Error while compiling statement: FAILED: ParseException line 1:7 character '@' not supported here\nline 1:8 character '@' not supported here (80) (SQLExecDirectW)") The query where it is occurring is actually a standard query "SELECT @@TRANCOUNT" which is triggered by Django while connectivity Please suggest solution. Thanks in Advance. -
How to calculate response time in Django Python
I am new to Django Python. Please advise how to calculate a response time from the moment where the user input the search criteria until the relevant information are loaded/displayed onto the portal. Thanks. -
Going back after delete item
In my web, made with Django, once I delete an item if I go back with the browser I get an error because that url, with the ID of the item, no longer exists. How can I handle this error? -
Can I use no_sql database with all django features?
I am trying to start working on (mongodb or couchdb) with django. I am afraid that I will not be able to use the same django features such as django admin with users and groups permissions. -
Pandas read Excel Django 2.0
I am getting an error when trying to read Excel files with Pandas in Django 2.0. I bring in the File from a Form. form = NewAccountForm ( request.POST, request.FILES ) if form.is_valid (): file = request.FILES [ 'file' ] xlsx = pd.read_excel ( file ) This the the error. Request Method: POST Request URL: http://localhost:8000/ Django Version: 2.0 Exception Type: TypeError Exception Value: expected str, bytes or os.PathLike object, not NoneType I am feeling that this is a 2.0 error. same code worked before upgrading. Anyone else have this same experience? I am able to get the same data with django_excel so I know the path is fine. Cheers. -
Customizing django form based on currently logged in user
This is a part of my forms.py class SubjectForm(forms.ModelForm): title=forms.CharField(label='',widget=forms.TextInput(attrs={'maxlength':150, 'placeholder':'Write here. . .'})) body=forms.CharField(label='', widget=forms.Textarea(attrs={'placeholder':'Extend here. . .'})) board=forms.ModelChoiceField(label='',queryset=Board.objects.all(), empty_label='Select Board') class Meta: model = Subject fields = ('title','body','board') Right now it's rendering all Board objects in board form field but I want to render only those boards in which the user has subscribed. How can I get user in form and manipulate it? -
Error while installing Django-channels
I'm also getting the same error while installing Twisted. Here's version info: Django : 1.9 Python : 3.5 Trying to install latest version of Django-channels Command used : pip install channels The error : running build_ext building 'twisted.test.raiser' extension error: [WinError 2] The system cannot find the file specified I don't know what i'm missing, could someone help me please, thanks. -
What the use of tables in app django-celery?
I want to use celery to make a spider get proxy data for Internet timing. Now, I get some settings ahout how to use django-celery in django.Although it makes me a long time. But, I also have a problem below: Five tables had been made when I did python manage.py migrate,I know the three head tables is about timing task with the setting CELERYBEAT_SCHEDULER='djcelery.schedulers.DatabaseScheduler' ,but what the use of the tables ,tasks and workers? I try to make different setting about BROKER_URLandCELERY_RESULT_BACKEND,such as redis://,django://,djcelery.backens.database:DatabaseBackend,but I found , the table,tasks, no data born all the time.and the table workers,too. Could somebody explain the table,tasks and workders's use and how can I use it with right settings? -
How to display different model instance names in different places in django admin
I want to display say "name1" as name inside model instance of model "A" detail page and say "name2" for model instance of same model "A" as name in other places (if it is foreign key in other model say "B")in django admin.I tried to make changes in __str__ method but it changes in all places. Is there any other way to do.Any suggestions? Thanks in advance. -
Error Message: "No module named 'django.core.urlresolvers".Even though I've replaced the module
I was trying to create tables in my database by executing the command on the django shell in the Windows CLI migrate.py syncdb It returned with the error message django.core.exceptions.ImproperlyConfigured: Error importing debug panel debug_toolbar.panels.request: "No module named 'django.core.urlresolvers'" After reading up to resolve my problem I discovered it is because the module django.core.urlresolvers is not available in versions of python higher than 1.9 and django.urls is the more suitable module. I replaced the former module in my code with the latter from django.urls import reverse and somehow still manage to get the same error. How do I resolve this? Thanks in advance. -
Distinct Users Filtering
I'm trying to create a messaging App in django but I couldn't re-order the Users properly Here's the Models, class Message(models.Model): sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") msg_content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) Here's the View, def message(request): users = Message.objects.filter(Q(sender=request.user) | Q(receiver=request.user)).values('sender__first_name', 'receiver__first_name', 'receiver__id', 'sender__id').annotate(Max('id')).order_by('-id__max') return render(request, 'chat/users.html', {'users': users}) Here's what I tried in Template, {% for user in users %} {% if user.sender__id != request.user.id %} {{ user.sender__first_name }} {% else %} {{ user.receiver__first_name }} {% endif %} {% endfor %} This code seems working fine but it's returning same user "Twice" as long as request.user send someone a message & that person replies back to it. How can I fix that? Thank You . . . -
Python3 + Django : How to use Jquery in render_to_string template?
My sauce is below. Elements in the template created using render_to_string are not Jquery controls. ▶ index.html {% extends 'common/base.html' %} {% block contents %} <section> <div class="main-goods-area"> <div class="container" id="prod_list"> </div> </div> </section> {% endblock %} {% block jquery %} <script src="{% static 'js/index.js' %}"></script> {% endblock %} ▶ index.js $(function() { show_inf_list('0','0','0','0','0'); function show_inf_list(section, selection, ordering, start, limit){ $.ajax({ url:'/campaign/list/', data:{ 'campaign_section': section, 'selection_type': selection, 'ordering_type': ordering, 'start': start, 'limit': limit }, dataType:'json', success: function (data) { $('#prod_list').html(data.campaign_list); } }); } $('a[name=btn_like]').on('click', function (e) { e.preventDefault() console.log('a'); return false; }); }); ▶ views.py def ... data['campaign_list'] = render_to_string( 'main/include/prod_list.html', context=context, request=request ) return JsonResponse(data) ▶ prod_list.html <div class="ic-area"> <ul> <li> <a href="" name="btn_like" data-id="{{ campaign.id }}"> {% if user.influencer in campaign.like_users.all %} <i class="ic_heart_small active"></i> {% else %} <i class="ic_heart_small"></i> {% endif %} </a> </li> </ul> </div> I want control 'btn_like' element But, I can't control the 'a[name=btn_like]' How to use Jquery Control in element of render_to_string template? -
Return String if object Existed Function in Django Rest Framework
I have a question about Function which Return String if object Existed in Django Rest Framework. I want to set condition: If FriendshipRequest model have from_user = request.user and to_user=self.user, this relationship_to_user fields will return: 'Existed', if not, print 'Not Existed' Serializers: class UserDetailSerializer(ModelSerializer): relationship_to_user = SerializerMethodField() class Meta: model = User fields = [ 'id', 'relationship_to_user', ] def get_relationship_to_user(self): friend_request_sent = FriendshipRequest.objects.filter(from_user=self.request.user, to_user=user) if friend_request_sent.exist(): return ('Existed') else: return ('Not Existed') -
How to save in database new order of nodes in tree with ajax | django?
I use django-mptt application in backend and jsTree plugin in frontend to create such tree as in the picture below in my Django project: jsTree plugin allows you to drag and drop nodes inside tree. django-mptt application by default in DB create fields like: tree_id, lft, rght and parent_id. tree_id field store information about order of nodes. parent_id field store information about ancestor. When user click the button after drag and drop nodes I want to save the new order of items and there new dependencies (parent_id field) in database. Сan someone say me how to make such thing? template: {% load mptt_tags %} <div id="documents"> <ul> {% recursetree documents %} <li data-id='{{ node.tree_id }}'> {{ node.title }} <ul class="children"> {{ children }} </ul> </li> {% endrecursetree %} </ul> </div> JS: $(function () { $('#documents').jstree({ 'plugins': ["wholerow", "dnd", "search"], 'core': { 'themes': { 'name': 'proton', 'responsive': true }, "check_callback" : true }, }); var to = false; $('#search-documents').keyup(function () { if(to) { clearTimeout(to); } to = setTimeout(function () { var v = $('#search-documents').val(); $('#documents').jstree(true).search(v); }, 250); }); }); -
Adding Reply Form to every Comment in django
I'm trying to build a website where people can comment on a thread and others can also make replies to these comments. I've already made a commenting system but don't know how to add reply form to every single comment so that they can make a reply to that specific comment. Need help and suggestions?? -
how to make objects iterable and count the length elments in objects
What i am try to do is filtering the model according to date . And iterating the those objects what i actually want do is taking the objects from Grade in particular date range and iterating each object then counting the len after that passing range printing the values rows = Grades.objects.filter(user_ql__created_at__range=(from_date, to_date)) for row in rows: row_num += 1 for col_num in range(len(row): ws.write(col_num+2, row_num, row[col_num], font_style) When i do this i got first object of type len() is not found and unable to iterate those row -
Create custom template tag
I have a model that has a method which needs a parameter (the request.user.some_field) to do the job. So, to send this request.user, I've created a template tag. extra_tag.py from django import template register = template.library() @register.simple_tag def precio(sub_medida, tipo_usuario): return sub_medida.precio_venta(tipo_usuario) and when i go to the template where is loaded, I get the following error: on template: 'module' object is not callable on console: "../../extra_tag.py", line 3, in register = template.library() I don't know if this helps, but i followed this documentation: https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/ Thanks in advance.. -
Django - optional url parameter returns null
I'm using an optional url parameter using this solution: If the optional argument isn't set, I get "null" in the browser url after the template is rendered: http://localhost:8000/home/Guest/create/null urls.py path('home/<str:username>/create', views.CreateModel.as_view(), name='model_create'), path('home/<str:username>/create/<int:pk>', views.CreateModel.as_view(), name='model_create_id'), views.py class CreateModel(generic.FormView): template_name = 'pythonmodels/user_content/createModel.html' form_class = CreateModel There are a lot of posts on optional url arguments, but I'm lost on where to add a default value inside the class based view if the argument is empty, so it would look like: http://localhost:8000/home/Guest/create Thanks in advance. -
Django Rest and Axios
I am trying to post data using DRF and Axios. I have tried a couple different options so far with the same result, 403 (Forbidden). I am able to get data using axios.get but not able to post data. I am new to rest and using ajax so I apologize if it is something obvious. Axios call return axios({ method: 'post', url: "/schedules/", data: { "emp": this.emp.emp, 'start_time': this.startTime, "end_time": this.endTime, "date": this.today, "location": this.location }, xsrfHeaderName: "X-CSRFToken", responseType: 'json' }) Settings.py CSRF_COOKIE_NAME = "XSRF-TOKEN" Serializer class SchedSerializer(serializers.ModelSerializer): class Meta: model = Schedule fields = ( 'location', 'emp', 'date', 'start_time', 'end_time' ) View class SchedViewSet(viewsets.ModelViewSet): queryset = Schedule.objects.all() serializer_class = serializers.SchedSerializer -
Using redirect url to clear GET paremeters with SessionWizard from django-formtools
I'm using a SessionWizard in my view and my use case is that want to create a link which bypasses step 1 of the wizard. This step represents simply selecting a plan. So, these links would have hrefs of say, url/?plan=0, url/?plan=1.... etcetera In the get view of the wizard I'm capturing whether there are parameters in request.GET and submitting the first step of the form by building the request.POST QueryDict and calling the wizard's post view to go to the next step. However, since it just calls self.render which returns a TemplateResponse the ?plan=* is left in the url. Is there a way to redirect to the next step so this parameter is removed? -
Django Rest Framework serializing nested data
I am trying to serialize data in this Serializer but I am always getting the output {} Here is my serializer: class RelationshipSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) related_user = UserSerializer(read_only=True) class Meta: model = models.Relationship fields = ( 'user', 'related_user', ) Here is my view: related_user_id = body["related_user"] related_user = models.User.objects.get(id=related_user_id) user = self.get_object() user_serializer = serializers.UserSerializer(user).data related_user_serializer = serializers.UserSerializer(related_user).data # user_serializer and related_user_serializer return valid data. data = {"user": user_serializer, "related_user": related_user_serializer} serializer = serializers.RelationshipSerializer(data=data) serializer.is_valid() # valid return Response(serializer.data) I am getting the id of related_user from post request then getting the queryset of the actual object, and user is the id passed in the url: user/{1}/. I then serialize each user and create a dictionary to pass to RelationshipSerializer. The serializer returns valid but the response is {}, what did I do wrong? -
Logging errors in DRF using Sentry
Am trying to get Django logging working with Django Rest Framework and Sentry. Using the LOGGING entry below, I am able to invoke a logging.error("some error") from my own defined modules running as Celery workers and I can see the error is being pushed to Sentry. Unfortunately, when I invoke the same in a Django Rest Framework Serializer.py or a View.py the errors are not being captured by Sentry. Is there a parameter am missing maybe in DRF or Django to allow them to send errors to Sentry? Below is a sample that is not getting logged. serializer.py import logging logger = logging.getLogger(__name__) class MySerializer(serializers.Serializer): def validate(self, data): logger.error("Log an error") The config below was auto generated using cookie cutter LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'root': { 'level': 'WARNING', 'handlers': ['sentry', ], }, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s ' '%(process)d %(thread)d %(message)s' }, }, 'handlers': { 'sentry': { 'level': 'ERROR', 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' } }, 'loggers': { 'django.db.backends': { 'level': 'ERROR', 'handlers': ['console', ], 'propagate': False, }, 'raven': { 'level': 'DEBUG', 'handlers': ['console', ], 'propagate': False, }, 'sentry.errors': { 'level': 'DEBUG', 'handlers': ['console', ], 'propagate': False, }, …