Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to link votes of answers to votes of a user?
I'm working on a Django project that users can ask and answer the questions. meanwhile users can vote answers like stackoverflow answers. now I wanna link vote numbers of answers and votes of a user. for example user A answered a question and his answer gets 10 votes, again user A answer another question and gets 5 votes. now votes of this user should be 15. How can I do this? any ideas? Thanks in advance. This is my Model: class Answer(models.Model): user = models.ForeignKey(msignup, related_name="uanswer") question = models.ForeignKey(Question) description = models.TextField(max_length=2000) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True, auto_now_add=False) votes = models.IntegerField(default=0) is_accepted = models.BooleanField(default=False) upload = models.FileField(upload_to=upload_location, null=True, blank=True) class Meta: verbose_name = 'Answer' verbose_name_plural = 'Answers' ordering = ('-is_accepted', '-votes', 'create_date',) def __str__(self): return self.description def accept(self): answers = Answer.objects.filter(question=self.question) for answer in answers: answer.is_accepted = False answer.save() self.is_accepted = True self.save() self.question.has_accepted_answer = True self.question.save() def calculate_votes(self): up_votes = Activity.objects.filter(activity_type=Activity.UP_VOTE, answer=self.pk).count() down_votes = Activity.objects.filter(activity_type=Activity.DOWN_VOTE, answer=self.pk).count() self.votes = up_votes - down_votes self.save() return self.votes And This is my view: def vote(request): answer_id = request.POST['answer'] answer = Answer.objects.get(pk=answer_id) vote = request.POST['vote'] userID = request.session.get('mainSession', 0) user = msignup.objects.get(id=userID) activity = Activity.objects.filter( Q(activity_type=Activity.UP_VOTE) | Q(activity_type=Activity.DOWN_VOTE), user=user, answer=answer_id) if activity: activity.delete() … -
PATCH request to ModelViewSet in django rest framework doesn't update data. Why?
I'm trying to implement PATCH handling using a ModelViewSet for my Product API. (The Product instance primary key is a uuid, and hence the uuid appears as the lookup_field in the code below). I'm confused about how to override the update() ModelSerializer class method. The stub in the source looks like this: def update(self, instance, validated_data): raise NotImplementedError('`update()` must be implemented.') I don't understand why instance and validated_data should be provided, because they should be properties of the serializer as per its instantiation: get_serializer(self, instance=None, data=None, many=False, partial=False) (scroll up one paragraph here in the documentation). And why should I be providing the validated data? Isn't the serializer is supposed to validate it? Here's my partial_update() implementation: product.py (ViewSet class) def get_object(self, uuid=None): """ Utility method to get the object """ # authentication logic, returns None if object not found def partial_update(self, request, uuid=None): instance = self.get_object(uuid) if not instance: return Response(status=status.HTTP_404_NOT_FOUND) serializer = self.get_serializer(instance, data=request.data, many=isinstance(request.data, list), partial=True) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.update() #NOT WORKING; NEEDS ARGS instance, validated_data return Response(serializer.data, status=status.HTTP_200_OK) serializers.py def update(self, instance, validated_data): # we link up the user foreign key here user=User.objects.filter(email=validated_data.pop('user', None)).first() if user: instance.fk_user = user #specify which fields to … -
Duplicate key oiolates unique constraint during signup
duplicate key value violates unique constraint "auth_user_username_key" DETAIL: Key (username)=() already exists. models.py class Profile(User): user = models.OneToOneField(User) mobile = models.CharField(max_length=100, null=True, blank=True) country_code = models.CharField(max_length=100, null=True, blank=True) shipping_street_1 = models.CharField(max_length=100, null=True, blank=True) shipping_street_2 = models.CharField(max_length=100, null=True, blank=True) shipping_city = models.CharField(max_length=100, null=True, blank=True) shipping_state = models.CharField(max_length=100, null=True, blank=True) shipping_country = models.CharField(max_length=100, null=True, blank=True) shipping_zip = models.CharField(max_length=100, null=True, blank=True) shipping_tel = models.CharField(max_length=100, null=True, blank=True) billing_street_1 = models.CharField(max_length=100, null=True, blank=True) billing_street_2 = models.CharField(max_length=100, null=True, blank=True) billing_city = models.CharField(max_length=100, null=True, blank=True) billing_state = models.CharField(max_length=100, null=True, blank=True) billing_country = models.CharField(max_length=100, null=True, blank=True) billing_zip = models.CharField(max_length=100, null=True, blank=True) billing_tel = models.CharField(max_length=100, null=True, blank=True) views.py class SignUpView(FormView): model = models.User template_name = "registration/signup.html" form_class = forms.SignupForm success_url = "/" @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(SignUpView, self).dispatch(request, *args, **kwargs) def form_valid(self, form): e = models.User.objects.filter(email=self.request.POST.get("signup_email")).first() if e is None: user_obj, created = \ u = models.User.objects.get_or_create( email=self.request.POST.get("signup_email"), username=self.request.POST.get("signup_email"), ) user_obj.set_password(self.request.POST.get("signup_password")) user_obj.save() login(self.request, user_obj) models.Profile.objects.create( user=user_obj, mobile=self.request.POST.get("signup_mobile"), country_code=self.request.POST.get("signup_country_code") ) return super(SignUpView, self).form_valid(form) It works the first time but database entry is blank. Second time it gives this error. forms.py class SignupForm(forms.Form): signup_email = forms.EmailField(required=True) signup_password = forms.CharField(widget=forms.PasswordInput, required=True) signup_confirm_password = forms.CharField(widget=forms.PasswordInput, required=True) signup_first_name = forms.CharField(required=True) signup_last_name = forms.CharField(required=True) signup_country_code = forms.CharField(required=True) signup_mobile = forms.CharField() def __init__(self, … -
AssertionError: <QuerySet [<OnlineUsers: OnlineUsers object>]> != <QuerySet [<OnlineUsers: OnlineUsers object>]>
I got an error said: AssertionError: ]> != ]> , while testing GetAllOnlineUsers function, I want to solve this from test side only not to change the function in views, here is my view function: def GetAllOnlineUsers(self): allusers = models.OnlineUsers.objects.all() return allusers and this is the test function that raised the error: class GetAllOnlineUsers_Test(TestCase): def test_GetAllOnlineUsers(self): # country = Country.objects.create(CountryID=1, Name='UK;) # status = Status.objects.create(StatusID=1, StatusType='Active') # usertype = UserType.objects.create(UserTypeID=1, Type='Admin') # user = User.objects.create(UserID=1, Email='test@gmail.com', Password='12345678', UserTypeID=usertype, # StatusID=status, Username='test', Name='test', CountryID=country, # UserPicture="IntroTypeOfGestures.jpg", University='IT') # self.Online = OnlineUsers.objects.create(id=1, UserID=user) self.online2 = OnlineUsers.objects.all() try: self.assertEquals(ADMIN.GetAllOnlineUsers(), self.online2) except: self.assertRaises(Http404, 'something went wrong') -
How to have a "catchall" method in a python class?
In a class I need to have quite a lot of methods that are alike, so I'd like to have as less code as possible. Here is my current solution: # I am using Dajngo class Foo(admin.ModelAdmin): ... def get_a(self, obj): return obj.a def get_b(self, obj): return obj.b def get_c(self, obj): return obj.c def get_d(self, obj): return obj.d ... And there is much more get_... methods. I got a strong constraint on the name of those method and their signature, I cannot change them. So I tried to used __getattr__ to do something like that, but it didn't work and I am not even sure this is where I should looking for. Do you know if I can refactor my code in some way ? -
This QueryDict instance is immutable
I have a Branch model with a foreign key to account (the owner of the branch): class Branch(SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE name = models.CharField(max_length=100) account = models.ForeignKey(Account, null=True, on_delete=models.CASCADE) branch_alias = models.CharField(max_length=100, blank=True, null=True, help_text="Field that will be used on the front-end when displaying the branch name.") location = models.TextField() phone = models.CharField(max_length=20, blank=True, null=True, default=None) create_at = models.DateTimeField(auto_now_add=True, null=True) update_at = models.DateTimeField(auto_now=True, null=True) def __str__(self): return self.name class Meta: permissions = (('create_branch', 'Can create branch'),) unique_together = (('name','account'),) ... I have a Account model with a foreign key to user (one to one filed): class Account(models.Model): _safedelete_policy = SOFT_DELETE_CASCADE name = models.CharField(max_length=100) user = models.OneToOneField(User) # metadata = JSONField(load_kwargs={'object_pairs_hook': collections.OrderedDict}) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name + ' - ' + self.create_at.strftime('%Y-%m-%d %H:%M:%S') I've created a ModelViewSet for Branch which shows the branch owned by the logged in user: class BranchViewSet(viewsets.ModelViewSet): serializer_class = BranchSerializer permission_classes = (permissions.IsAuthenticated,) def get_queryset(self): queryset = Branch.objects.all().filter(account=self.request.user.account) return queryset Now to create a new branch, I want to save account field with request.user.account, not with data sent from the rest client (for more security). for example: def create(self, request, *args, **kwargs): if request.user.user_type == User.ADMIN: request.data['account'] = request.user.account return super(BranchViewSet, … -
`TypeError` when calling create(). You may need to make the field read-only, or override the create() method
Not sure what's going on here. I'm trying to perform create a new instance via Django-rest-framework. What am I doing wrong? There are a few read-only fields being submitted back. I've tried marking them as read-only via read_only_fields in the serializer, as well as specifying them as editable=False within the model's fields. Note: I would prefer to avoid specifying my own create method if possible. This should work via standard functionality as documented here when POSTing the following: { "displayName": "New test", "backgroundColour": "#4d3567", "foregroundColour": "#FFFFFF", "helpText": "test", "description": "test", "comment": "test." } i'm getting: TypeError at /api/v1/classifications/ Got a `TypeError` when calling `ClassificationLabel.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `ClassificationLabel.objects.create()`. You may need to make the field read-only, or override the ClassificationLabelListSerializer.create() method to handle this correctly. models.py: class ClassificationLabel(models.Model): """ this model is used to create all instances of classifications labels that will be displayed to a user """ displayName = models.CharField('Classification label display name', max_length = 32) helpText = models.TextField('Explanatory text about this label', max_length = 140, blank=True) backgroundColour = models.CharField('Hex code for background colour including Alpha', max_length=8) foregroundColour = models.CharField('Hex code for … -
Wagtail, use a predefined set of tags
I am getting started with Wagtail to build a blog and its working well so far. When using tags it seems that the Wagtail admin does a get_or_create call - so any new tags are saved to the database as a new tag. Is it possible to provide a set of tags in advance and only these tags can be used to tag blog posts (no new tags are created)? -
celery: could not connect to rabbitmq
Using rabbitmq as broker for celery. Issue is coming while running command celery -A proj worker --loglevel=info celery console shows this [2017-06-23 07:57:09,261: ERROR/MainProcess] consumer: Cannot connect to amqp://bruce:**@127.0.0.1:5672//: timed out. Trying again in 2.00 seconds... [2017-06-23 07:57:15,285: ERROR/MainProcess] consumer: Cannot connect to amqp://bruce:**@127.0.0.1:5672//: timed out. Trying again in 4.00 seconds... following are the logs from rabbitmq =ERROR REPORT==== 23-Jun-2017::13:28:58 === closing AMQP connection <0.18756.0> (127.0.0.1:58424 -> 127.0.0.1:5672): {handshake_timeout,frame_header} =INFO REPORT==== 23-Jun-2017::13:29:04 === accepting AMQP connection <0.18897.0> (127.0.0.1:58425 -> 127.0.0.1:5672) =ERROR REPORT==== 23-Jun-2017::13:29:14 === closing AMQP connection <0.18897.0> (127.0.0.1:58425 -> 127.0.0.1:5672): {handshake_timeout,frame_header} =INFO REPORT==== 23-Jun-2017::13:29:22 === accepting AMQP connection <0.19054.0> (127.0.0.1:58426 -> 127.0.0.1:5672) Any input would be appreciated. -
How to serialize data of model User since another model Userfull
I'm using a model for save some data of my user different to model User of contrib.auth.user and now I need get a json using django.core.serializers with some data of those models. The model 'Usuario' save data as name and phone and role (The role is a integer that segment the users) class User_info(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE, null=False) name=models.CharField(max_length=255, null=False) phone=models.IntegerField(default=0, null=False) role=models.ForeignKey(type_role, default=3) class type_role(models.Model): type=models.IntegerField() For get a QuerySet and serlize my data I'm using that view def list_clients(request): clients = User_info.objects.filter(role_id=3) data=serializers.serialize('json',clientes) return HttpResponse(data, content_type="application/json") But I'm getting a JSON as the next [{ "model": "user_info.user_info", "pk": 1, "fields": { "username": 1, "name": "George", "phone": 5244356, "role": 3 } }] And I really need the user__username not the user__id I know that can get this using .values(), but ValuesQuerySet aren't supported for serlizer and I get a error: 'dict' object has no attribute '_meta' If anyone can help me I would be very thankful. -
Use Single table inheritance in Django
AFAIK Django supports these types of inheritance: Abstract base classes Multi-table inheritance Proxy models According to the StackOverflow tag description, Single table inheritance is the simplest of several ways to design SQL tables that reflect a class/subclass or generalization/specialization relationship. See: https://stackoverflow.com/tags/single-table-inheritance/info Is there a way to use this pattern in Django? -
GAE: Unicode JSON String Not Working in Multipart Post After Blob Upload
To upload files to Google storage, I sent multipart POST request to the url returned by create_upload_url(redirect_path). The POST request includes files and a JSON string that I need to use in redirect_path. If the JSON string has unicode character, then it will be broken after GAE forward the multipart POST request to me. JSON String sent to upload url: {"subject": "日文", "tag_key": "ahNifnN1aXF1aS1kZXYtMTcwMDAycjkLEgRUZWFtIgtzdWlxdWlfdGVzdAwLEgdUYWdUeXBlGICAgICAgIAKDAsSA1RhZxiAgICAgK6ZCQw"} JSON string after GAE forward the request to redirect_path {"subject": "=E6=97=A5=E6=96=87", "tag_key": "ahNifnN1aXF1aS1kZXYtMTcwMDAyc= jkLEgRUZWFtIgtzdWlxdWlfdGVzdAwLEgdUYWdUeXBlGICAgICAgIAKDAsSA1RhZxiAgICAgK6Z= CQw"} The unicode becomes unreadable and the '=' and 'newline' are inserted unexpectedly. Strangely, A shorter JSON string with unicode works fine. {"subject": "日文", "tag_key": ""}. Other points, the problem only happens in production environment. I cannot reproduce in local development server. Multipart POST request to redirect_path doesn't have the problem. The issue only occurs on posting to blobstore.create_upload_url. I am using GAE standard environment, Python, Django, Django Rest framework, and Postman to test. Please let me know if you think of any possible cause. -
how to create different product size chart for different categories
I need to write shop on Django Framework. Shop must contain few categories of goods, like t-shirts, shoes, pants, etc. And each of this category will be contain its own sizes parameters, for example: shoes will be contain parameters - size and foot length; t-shirts - size, bust, waist and hip. Detail's page of choosen good must show size chart, like this enter image description here How to describe django's models for filling size chart in django admin, and display this size chart on products's page. -
Replace rgex in python
I have a text like this @110605!~~!Abhay_f!~~!Abhay%20Raj%20Fac!>>! @138547!~~!testvarun!~~!Varun%20Test%20User!>>! @136588!~~!jitendra_pathak!~~!Jitendra%20Pathak!>>! #gffj #varun okjjbbbd and in this string i want to replace !~~! with "". I am using template tag and i used this method but didn't work for me @register.filter("metioned_user_text_encode") def metioned_user_text_encode(string, args): search = args.split(args[0])[1] replace = args.split(args[0])[2] return re.sub(search, replace, string) In my template:- result_data_for_editing.newsText | metioned_user_text_encode:"/l(u+)pin/m\1gen" -
Is it possible to pause and resume an http file upload?
My application needs heavy files(>=20GB) to be uploaded to the server. Can we pause and resume an upload made through http? I am using Django to build my application. -
Paho-Mqtt django, on_message() function runs twice
I am using paho-mqtt in django to recieve messages. Everything works fine. But the on_message() function is executed twice. I tried Debugging, but it seems like the function is called once, but the database insertion is happening twice, the printing of message is happening twice, everything within the on_message() function is happening twice, and my data is inserted twice for each publish. I doubted it is happening in a parallel thread, and installed a celery redis backend to queue the insertion and avoid duplicate insertions. but still the data is being inserted twice. I also tried locking the variables, to avoid problems in parallel threading, but still the data is inserted twice. I am using Postgres DB How do I solve this issue? I want the on_message() function to execute only once for each publish my init.py from . import mqtt mqtt.client.loop_start() my mqtt.py import ast import json import paho.mqtt.client as mqtt # Broker CONNACK response from datetime import datetime from raven.utils import logger from kctsmarttransport import settings def on_connect(client, userdata, flags, rc): # Subcribing to topic and recoonect for client.subscribe("data/gpsdata/server/#") print 'subscribed to data/gpsdata/server/#' # Receive message def on_message(client, userdata, msg): # from kctsmarttransport.celery import bus_position_insert_task # bus_position_insert_task.delay(msg.payload) from … -
How to set items to a specific Todolist in Django Rest Framework?
Im building a TODO app using django rest framework. I have to two models namely todolist and todoitem.How can I set a new todoitem to a specific todolist? I tried using foreign key but it didn't worked out,Sorry for my bad english,Can anyone please help me my models.py: class todolist(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE,default=None) name=models.CharField(max_length=128) creation_date=models.DateField(auto_now=True) def __unicode__(self): return self.name class todoitem(models.Model): description=models.CharField(max_length=150) completed=models.BooleanField(default=False) due_by=models.DateField(auto_now=True) parent=models.ForeignKey(todolist,on_delete=models.CASCADE) def _unicode__(self): return self.description ` my classviews.py: ` class Todolist(LoginRequiredMixin,ListCreateAPIView): serializer_class = listserializer def perform_create(self, serializer): serializer.save(user=self.request.user) def get_queryset(self): self.queryset = todolist.objects.filter(user=self.request.user) return super(Todolist, self).get_queryset() class Todolistdetail(LoginRequiredMixin,RetrieveUpdateDestroyAPIView): def get_queryset(self): self.queryset = todolist.objects.filter(user=self.request.user) return super(Todolistdetail, self).get_queryset() serializer_class = listserializer class Todoitem(LoginRequiredMixin,ListCreateAPIView): def perform_create(self, serializer): temp = self.queryset(todolist.objects.filter(id=self.kwargs['pk'])) serializer.save(parent=temp) def get_queryset(self): temp=todolist.objects.filter(id=self.kwargs['pk']) self.queryset=todoitem.objects.filter(parent=temp) return super(Todoitem, self).get_queryset() serializer_class = itemserializer class Todoitemdetail(LoginRequiredMixin,RetrieveUpdateDestroyAPIView): def get_queryset(self): temp=todolist.objects.filter(id=self.kwargs['list_id']) self.queryset = todoitem.objects.filter(parent=temp) return super(Todoitemdetail, self).get_queryset() serializer_class = itemserializer ` my serializers.py: ` class listserializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.username') class Meta: model=todolist fields='__all__' class itemserializer(serializers.ModelSerializer): parent=serializers.ReadOnlyField(source='todolist.id') class Meta: model=todoitem fields='__all__' ` my urls.py: ` from todoapp import classviews app_name="todoapp" urlpatterns=[ url(r'^list/$',classviews.Todolist.as_view(),name="list_lists"), url(r'^list/(?P<pk>[0-9]+)/$',classviews.Todolistdetail.as_view(),name="each_list"), url(r'^list/(?P<pk>[0-9]+)/item/$',classviews.Todoitem.as_view(),name="list_items"), url(r'^list/(?P<list_id>[0-9]+)/item/(?P<pk>[0-9]+)/$',classviews.Todoitemdetail.as_view(),name="each_item") ] ` -
Django admin interface: using horizontal_filter with ManyToMany field with intermediate table
I am trying to enhance the django admin interface similar to what has been done in the accepted answer of this SO post. I have a many-to-many relationship between a User table and a Project table. In the django admin, I would like to be able to assign users to a project as in the image below: It works fine with a simple ManyToManyField but the problem is that my model uses the through parameter of the ManyToManyField to use an intermediary table. I cannot use the save_m2m() and set() function and I am clueless on how to adapt the code below to make it work. The model: class UserProfile(models.Model): user = models.OneToOneField(User, unique=True) projects = models.ManyToManyField(Project, through='Membership') class Project(models.Model): name = models.CharField(max_length=100, unique=True) application_identifier = models.CharField(max_length=100) type = models.IntegerField(choices=ProjectType) ... class Membership(models.Model): project = models.ForeignKey(Project,on_delete=models.CASCADE) user = models.ForeignKey(UserProfile,on_delete=models.CASCADE) # extra fields rating = models.IntegerField(choices=ProjectType) ... The code used for the widget in admin.py: from django.contrib.admin.widgets import FilteredSelectMultiple class ProjectAdminForm(forms.ModelForm): class Meta: model = Project fields = "__all__" # not in original SO post userprofiles = forms.ModelMultipleChoiceField( queryset=UserProfile.objects.all(), required=False, widget=FilteredSelectMultiple( verbose_name='User Profiles', is_stacked=False ) ) def __init__(self, *args, **kwargs): super(ProjectAdminForm, self).__init__(*args, **kwargs) if self.instance.pk: self.fields['userprofiles'].initial = self.instance.userprofile_set.all() def save(self, commit=True): … -
python django dictionaries
I have a list with this format: [{'BURGLARY': [0, 1, 1, 0], 'PHYSICAL ASSAULT': [0, 0, 1, 0], 'ROBBERY': [0, 0, 0, 1], 'VANDALISM': [2, 0, 1, 0], 'THEFT': [1, 3, 2, 1], 'DRUGS AND SUBSTANCE ABUSE': [0, 0, 1, 0], 'SEXUAL HARASSMENT': [0, 0, 0, 1]}] I want to change its format to: [ { name:"BURGLARY", data:[0, 1, 1, 0] } { name:"PHYSICAL ASSAULT", data:[0, 0, 1, 0] } ... ] How can I archive this? Please help. -
Django upgrade 1.7 to 1.11
We upgraded our django from 1.7.7 to 1.11. But after upgrading we do see increase in our response time from 20 ms to 40 ms. After debugging we figured out that there is subsequent increase in the frequency of this particular query. SELECT @@SQL_AUTO_IS_NULL How the response time can be reduced? Do we have to change the way how the MySQL connection is made? -
Django bulk_create raises "Database is in recovery mode"
Upload ~15MB csv file and then bulk_create One round it task id to 100k records. Next round it will remove existing records and INSERT INTO again. My guess: I am suspecting that sequence_id overflow is the root cause of my problem Because it used to be able to uploaded before this time, but broken just for now and could not be able to upload it again Here is my postgres log: 2017-06-23 04:55:21.087 UTC [27896] LOG: server process (PID 20529) was terminated by signal 9: Killed 2017-06-23 04:55:21.087 UTC [27896] DETAIL: Failed process was running: INSERT INTO "sales_sales" ("imc", "order_number", "original_order_date", "count") VALUES ('1049129', '415000458', '2017-03-01T03:00:00+00:00'::timestamptz, 1), ('1113804', '415000457', '2017-03-01T03:00:00+00:00'::timestamptz, 1), ('1151620', '415000460', '2017-03-01T03:00:00+00:00'::timestamptz, 1), ('1522771', '415000462', '2017-03-01T03:00:00+00:00'::timestamptz, 1), ('2280038', '415000459', '2017-03-01T03:00:00+00:00'::timestamptz, 1), ('7374979', '415000461', '2017-03-01T03:00:00+00:00'::timestamptz, 1), ('399428', '415000618', '2017-03-01T03:02:00+00:00'::timestamptz, 1), ('399428', '415000619', '2017-03-01T03:02:00+00:00'::timestamptz, 1), ('1049129', '415000614', '2017-03-01T03:02:00+00:00'::timestamptz, 1), ('1059455', '415000636', '2017-03-01T03:02:00+00:00'::timestamptz, 1), ('1059455', '415000638', '2017-03-01T03:02:00+00:00'::timestamptz, 1), ('1075963', '415000605', '2017-03-01T03:02:00+00:00'::timestamptz, 1), ('1113804', '415000607', '2017-03-01T03:02:00+00:00'::timestamptz, 1), ('1137600', ' 2017-06-23 04:55:21.090 UTC [27896] LOG: terminating any other active server processes 2017-06-23 04:55:21.100 UTC [19656] WARNING: terminating connection because of crash of another server process 2017-06-23 04:55:21.100 UTC [19656] DETAIL: The postmaster has commanded this server process to roll back the current transaction … -
How to decode the protobuf binary serialization at reactjs
I have a django web app, I am sending the protobuf as my response at view end , but I don't have any idea how should I decode at reactjs end. I am new to reactjs still I am at learning phase -
Django template and loader
`enter code here' from django.http import HttpResponse from django.template import loader from .models import Album def index(request): all_albums=Album.objects.all() template= loader.get_template('music/index.html') context= { 'all_albums': all_albums, } return HttpResponse(template.render(context,request)) def detail(request, album_id): return HttpResponse("<h2>details for album id " + str(album_id) + " </h2>") -
How to reset primary key sequence from python program
How to reset the sequence for IDs on PostgreSQL tables I know that I can reset from terminal, but I want to reset it from Django python program. I am now trying to use RAW sql postgres=# \c uihspot You are now connected to database "uihspot" as user "postgres". uihspot=# \dt List of relations Schema | Name | Type | Owner --------+------------------------------+-------+---------- public | amway_accessrule | table | postgres public | amway_log | table | postgres public | auth_group | table | postgres public | auth_group_permissions | table | postgres public | auth_permission | table | postgres public | auth_user | table | postgres public | auth_user_groups | table | postgres public | auth_user_user_permissions | table | postgres public | django_admin_log | table | postgres public | django_content_type | table | postgres public | django_migrations | table | postgres public | django_session | table | postgres public | member_profile_memberprofile | table | postgres public | ruckus_login_accesslog | table | postgres public | ruckus_login_membertomac | table | postgres public | sales_sales | table | postgres public | uploaded_files_uploadedfile | table | postgres (17 rows) uihspot=# select currval('sales_sales_id_seq'); ERROR: currval of sequence "sales_sales_id_seq" is not yet defined in this session uihspot=# select … -
Django Python inserting queryset into dictionary come with tag (<>). How to remove tag?
I'm trying to make dictionary with content list as it value. Problem here is while inserting in dictionary it comes with a tag. shades = Shade.objects.filter(shade_code__contains=search_text) colorListDict = {} for color in shades: colorListDict[color.color_one] = [] colorListDict[color.color_one].append(color.color_quantity) print colorListDict Result: {<Color: Blue MTR>: [Decimal('4.000')], <Color: Yellow 2GL>: [Decimal('0.390')], <Color: Orange RL>: [Decimal('1.500')], <Color: Brown GRL>: [Decimal('5.000')], <Color: DarkViolet>: [Decimal('2.700')], <Color: Red SG>: [Decimal('1.000')], <Color: Violet B>: [Decimal('1.000')], <Color: Red 10B>: [Decimal('2.000')], <Color: Dark Violet RL>: [Decimal('20.000')], <Color: TBlue>: [Decimal('1.050')], <Color: Blue 2R>: [Decimal('1.900')], <Color: Yellow 4GL>: [Decimal('2.100')], <Color: Grey SBL>: [Decimal('1.250')], <Color: Blue 5G>: [Decimal('1.200')]} I want it to be like: {Blue MTR: [4.000], Yellow 2GL: [0.390], Orange RL: [1.500], Blue 5G: [1.200]}