Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to decode token and get back information for djangorestframework-jwt packagefor Django
I have started using djangorestframework-jwt package instead of PyJWT , I just could not know how to decode the incoming token (I know there is verify token methode).... All I need to know is how to decode the token and get back info encoded...... -
Django: ChoiceField depending on choices??
I have two ChoiceField in forms.py: class PaymentForm(forms.ModelForm): A_CHOICES = ( ('aa1', 'aa1'), ('aa2', 'aa2'), ) a = forms.ChoiceField(choices=A_CHOICES) B_CHOICES = ( ('bb1', 'bb1'), ('bb2', 'bb2'), ) C_CHOICES = ( ('cc1', 'cc1'), ('cc2', 'cc2'), ) bc = forms.ChoiceField(choices=C_CHOICES) # or B_CHOICES What I want to do in front side is: If aa1 were chosen, then B_CHOICES would be shown in bc fields. If aa2 were chosen, then C_CHOICES would be shown in bc fields. I have no idea even search-keyword for implementing this! Need helps. Thanks -
UUID Field in django behave weired at mysql
I have a Django model which looks like following class CdrByBusinessFlowID(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) cc_id = models.IntegerField() business_flow_id = models.CharField(max_length=255, blank=True) status = models.CharField(max_length=10, blank=True) I have created a model model with api response following { "status": "pending", "business_flow_id": "13630f30-bfed-4e8d-bdbd-263d0da75175", "id": "3c337f4c-3236-4117-b519-c57fbcc001f8", "cc_id": "1610" } But unfortunately this id doesn't exist in database. The value just modified to some other value like 1f604e31a4054d1e998b97433cc661a5. Thanks -
Complex grouping list items
I need to display notifications in Facebook format using python. But finding it difficult to group the items. Following is the list from query The notification must be displayed as follows John changed Name, Code, Description of Product Shirt John changed Name of Product Hat John changed Variant Code of Hat Mike changed Name of Product Trouser, Hat Kiet changed Name of Variant XXL Shirt Is there any possibility of doing this using python group by? and order by date? -
Error while submitting a form in django
i am submitting a form in django and i am getting a error global name 'url_validate' is not defined error while submitting a form -
Can't collectstatic in Travis CI using django
In my project I make 2 parts 'development' 'production' In development STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' In wef/settings/production STATICFILES_STORAGE = 'wef.storage.S3PipelineManifestStorage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = os.environ.get("AWS_STORAGE_BUCKET_NAME") In my local project when I command python wef/manage.py collectstatic --noinput It's ok (it has no problem) it is development command so staticfile were saved my local storage and when I command python wef/manage.py collectstatic --settings=wef.settings.production it's ok too, staticfiles uploaded my AWS S3 storages(finished double check) so I decide to run unnit test in Travis CI(testing static file load success) here is my .travis.yml In .travis.yml language: python python: - 3.5.1 addons: postgresql:"9.5.1" install: - pip install -r requirement/development.txt before_script: - psql -c 'CREATE DATABASE bookconnect;' -U postgres - createuser hanminsoo - psql -c 'GRANT ALL PRIVILEGES ON DATABASE bookconnect TO hanminsoo;' -U postgres - psql -c 'ALTER USER hanminsoo CREATEDB;' -U postgres - npm -g install yuglify - npm install yuglify script: - pep8 - python wef/manage.py makemigrations users items - python wef/manage.py migrate - python wef/manage.py collectstatic --noinput - python wef/manage.py test users and travis show me error boto.exception.NoAuthHandlerFound: No handler was ready to authenticate. 1 handlers were checked. ['HmacAuthV1Handler'] Check your credentials It is So … -
How to prevent Django messages from leaking out to other modules?
I am currently using the built-in django-messages framework of django version 1.10. However, since the messages are stored in the request, and therefore not "namespaced" as it were for different modules, I am concerned that this might lead to potential circumstances where messages created by one module (e.g. a messaging framework "your message has been sent") might bleed into another. Is there a way to "namespace" these messages so we dont have this unintended affect? In addition, the documentation says that messages expire if they are iterated over, does that mean that if I forget to iterate over them, they have the potential to build up over multiple requests? -
Using 3rd party json data in django
I have live monitoring data from a tool called PRTG via an API I want to build a django site that brings it in for some real time reporting along with some other dashboards i have created. I'm stuck at the first step of just bring in the API data to display on the page. The API data is like this: {"prtg-version": "14.1.8.1371", "treesize": 381, "sensors": [ { "objid": 1001, "probe": "newname", "group": "newname", "device": "BR-S-LOG", "sensor": "System Health", "status": "Up", "status_raw": 3, "message": "<div class=\"status\">OK<div class=\"moreicon\"></div></div>", "message_raw": "OK", "lastvalue": "100 %", "lastvalue_raw": 100.0000, "priority": 5 }, { "objid": 1002, "probe": "newname", "group": "newname", "device": "BR-S-LOG", "sensor": "Core Health", "status": "Up", "status_raw": 3, "message": "<div class=\"status\">OK<div class=\"moreicon\"></div></div>", "message_raw": "OK", "lastvalue": "100 %", "lastvalue_raw": 100.0000, "priority": 5 }, { "objid": 1003, "probe": "newname", "group": "newname", "device": "BR-S-LOG", "sensor": "Probe Health", "status": "Up", "status_raw": 3, "message": "<div class=\"status\">OK<div class=\"moreicon\"></div></div>", "message_raw": "OK", "lastvalue": "98 %", "lastvalue_raw": 98.0000, "priority": 5 }, { "objid": 1004, "probe": "newname", "group": "newname", "device": "BR-S-LOG", "sensor": "Disk Free", "status": "Up", "status_raw": 3, "message": "<div class=\"status\">OK<div class=\"moreicon\"></div></div>", "message_raw": "OK", "lastvalue": "", "lastvalue_raw": "", "priority": 4 } ]} I have a view, but can't get it working def list_all(request): jsonList = … -
How to replay a message for app.control.revoke when handling SIGTERM in celery?
I'm using celery 3.1 with django. Right now, I have a task which need run forever, and I hope I can stop it manually. The code is like: import signal @shared_task(bind=True) def mainjob(self, name): def handler: stop_running_jobs() return 'terminated!' # the message hope to reply. signal.signal(signal.SIGUSR1, handler) keep_running_job() And I call the task using: result = mainjob.delay() When I want to stop the task, I call it like this to make sure the task has stopped. result.revoke(terminate=True, signal='SIGUSR1', wait=True, timeout=3) But when revoking the task, it always wait for 3 seconds, and never receive a reply.What should I do? -
Reverse for 'shop_cart' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
I am trying out Django Mezzanine. I have installed it with pip. After successful installation I added the Cartridge package via pip install -U cartridge. I have also included it in my Installed_Apps. I am able to see the package and able to tweak with it in admin panel. But when I try to go onto home page it is giving me the following error:- Reverse for 'shop_cart' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Inside the debugger I am shown the following error at line 4 highlighed:- 1 {% extends "base.html" %} 2 {% load i18n %} 3 4 {% block meta_title %}{% trans "Home" %}{% endblock %} 5 {% block title %}{% trans "Home" %}{% endblock %} 6 7 {% block breadcrumb_menu %} 8 <li class="active">{% trans "Home" %}</li> 9 {% endblock %} 10 11 {% block main %} 12 {% blocktrans %} 13 <h2>Congratulations!</h2> 14 <p> Also to mention that I have not edited any urls or any files. -
Django: what is difference between to set CHOICES in models and in forms?
I think that only defining ChoiceField in forms is best solution if I'm 100% sure to use form, right?. I mean, I don't have to do like this: models.py class Payment(TimeStampedModel): PAY_METHOD_CHOICES = ( ('card', '카드'), ('cash', '무통장입금'), ) pay_method = models.CharField( max_length=10, choices=PAY_METHOD_CHOICES ) forms.py class PaymentForm(forms.ModelForm): PAY_METHOD_CHOICES = ( ('card', '카드'), ('cash', '무통장입금'), ) pay_method = forms.ChoiceField( choices=PAY_METHOD_CHOICES ) class Meta: model = Payment This is redundant code, isn't it? In this sense, I can not understand why use choices in models field... When does it being used? which case? Thanks -
how to find height and width of image for FileField Django
How to find height and width of image if our model is defined as follow class MModel: document = FileField() format_type = CharField() and image is saved in document then how we can find height and width of a document if it is image ? -
How to hide a django field in a form but keep its original widget attributes
I know to hide a django field in a form by a forms.HiddenInput widget: flavor_type = forms.CharField(choices=(('a', _('A'),), ('b', _('B'),)), widget=forms.HiddenInput()) The field will be hidden from display but still is kept in the form. But at the same time, I need its other attributes like 'class' and 'data-slug': flavor_type = forms.ChoiceField(choices=choices=(('a', _('A'),), ('b', _('B'),)),, widget=forms.RadioSelect( attrs={'class': 'switch_radio', 'data-slug': 'flavor_type'})) -
how to show custom error in django instead of its default error?
i have put restriction on FileField that the user can only upload .doc, .pdf, .docx formst only but when user upload a different format file than it is showing this screen validation error but i want to show my own error instead of this. If the user upload doc or pdf file format then the form is successfully submitting. -
How to extend my contact form to main page?
I'm trying to extend my contact.html which contains contact form to my 'home.html' which acts as base.html. But it's not working and I trying looking and try many ways yet not working. My code are as following. Home.html <section id="contact-us" class="section"> <div class="main-contact"> <div class="col-xs-6 col-lg-4"> <div class="contact"> <h2>LET US HELP YOU</h2> <p> Push the boundaries of efficiency and excellence through game changing solutions.<br> We provide innovative solutions that combine international best practices with cutting edge technology for finaciers, governments and property professionals.<br> Speak to us or email us at info@resolutions.com.my today about how we can help your organisation get ahead.</p> </div> </div> <div class="form"> <h3>FILL UP THE FORM BELOW FOR MORE INFORMATION ABOUT VALUATION MANAGEMENT SYSTEM</h3> <div id="active"> <li><a href='{% url "contact.html" %}'></a></li> {% block content %} {% endblock %} </div> </a></li> </div> </div> </section> contact.html {% extends "home.html" %} {% load envelope_tags %} {% block default-active %}active{% endblock %} {% block content %} <form action="{% url 'envelope-contact' %}" method="post"> {% csrf_token %} {% antispam_fields %} {{ form.as_p }} <input type="submit" value="Send!" /> </form> {% endblock %} -
possible to generate sql from a migration file in django?
I defined some models, after migration I found foreign key column are integer type in the database while I expected it as varchar, since in the parent table it was defined as varchar. So I'd like to generate a sql from that migration file (0001_initial.py). Is it possible to do it? -
including extra data in Django intermediate table in Django-Rest-Framework Serializer
I've looked at lots of docs and SO questions and can't quite get what I need. I have slew of models, including one that is simply: class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) then I have three I'll show here that are relevant to the current problem: class Version(models.Model): version_number = models.CharField(max_length=50) cmd_line_script = models.CharField(max_length=250, null=False) SOP = models.TextField(null=False) FK_method = models.ForeignKey(Method, on_delete=models.CASCADE) class Meta: unique_together = ('version_number', 'FK_method') class Instrument(models.Model): serial_number = models.CharField(max_length=50, unique=True) asset_number = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=50) checksum_string = models.CharField(max_length=128, null=True) FK_instr_type = models.ForeignKey(InstrType, related_name='installations', on_delete=models.PROTECT) VersionsFromInstrument = models.ManyToManyField( Version, through='Instr_Version', related_name = 'InstrumentsFromVersion', ) class Instr_Version(models.Model): FK_version = models.ForeignKey(Version, related_name='versions', on_delete=models.CASCADE) FK_instrument = models.ForeignKey(Instrument, on_delete=models.CASCADE) validating_user = models.ForeignKey(UserProfile, on_delete=models.PROTECT) timestamp = models.DateField(auto_now_add=True) class Meta: unique_together = ('FK_version', 'FK_instrument') I have serializers (from DRF 3) working for most of this, however the 'extra data' is not included in the serialized data set. when InstrumentSerializer is used by a view, I get basically everything I want, but no timestamp, nor validator as I tried to include in the Instr_to_VersionSerializer below. see the serializers here, I've excluded some that cause no issues: class UserSerializer(serializers.ModelSerializer): class Meta: model = settings.AUTH_USER_MODEL excludes = 'password' class UserProfileSerializer(serializers.ModelSerializer): #user = serializers.serialize(settings.AUTH_USER_MODEL, read_only=True) … -
How do binaryfields work in Django?
I am using Django 1.10. And I'm looking to upload text field or jpg to my database in Postgresql. And later download it ??? I haven't find anything relate to this. Any suggestion ? -
Is it correct to add static link to my urlpatterns at urls.py
I am new at Django, and as I'm about to finalize my project, I toggled DEBUG from True to False to see if there are any actual errors. Now the static files are giving me an error 404 which I found the reason here. As a work around, I included this in my urls.py urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I then did python manage.py collectstatic Included this in my settings.py STATIC_ROOT = 'static' STATIC_URL = '/static/' Now static files load whenever I toggle DEBUG. Am I doing this incorrectly? -
Render JSON response to django template after ajax call
I am creating a poll test site which shows the result of the poll and the poll itself in the same page. What I want to do is when a user votes the result will change simultaneously. This is my code for jquery: <script> var result= document.getElementById('result'); (function poll(){ $.ajax({url: "http://localhost:8007/api/get_poll/", success: function(data){ result.innerHTML = data; }, dataType: "json", complete: poll }); })(); </script> And this is my views.py: def get_result(request): ... # this is what i want to pass poll = {'set1': [{'poll': 1, 'votes': 25}, {'poll': 2, 'votes': 20}], 'set2': [{'poll': 1, 'votes': 3}]} return JsonResponse(poll) For my template: <div id="result"></div> -
Get token as response when creating a new user
I am trying to make my response return the Token of the user when a new user is created. Essentially how it could work is take the user PK from the response when a user is created. Then it could return the token by looking it up at Token.objects.get(user=PK_TAKEN_FROM_RESPONSE) If there is a better way I am open to suggestions too. //Response I get when posting : curl -X POST -d "username=t2224&password=admin" localhost:8000/api/usercreate/ {"id":45,"password":"pbkdf2_sha256$24000$4v8oUPbNQxs6$Um1S23oGOSAxjRTP5MI11B0YQaXOYienXXO//9Mna3g=","last_login":null,"is_superuser":false,"username":"t2224","first_name":"","last_name":"","email":"","is_staff":false,"is_active":true,"date_joined":"2016-11-10T01:39:11.147652Z","groups":[],"user_permissions":[]} //Views.py class UsercreateViewset(viewsets.ModelViewSet): queryset = User.objects.none() serializer_class = UsercreateSerializer permission_classes=[] # This disables AUTH/Token on this Viewset only http_method_names = ['post'] # This only ALLOWS method POST (ie cannot see the URL) def retrieve(self, request, pk=None): if pk == 'i': return Response(UsercreateSerializer(request.user, context={'request':request}).data) return super(UsercreateViewSet, self).retrieve(request, pk) //Serializers.py class UsercreateSerializer(serializers.ModelSerializer): class Meta: model = User write_only_fields = ('password',) read_only_fields = ('id',) def create(self, validated_data): user = User.objects.create( username=validated_data['username'], ) user.set_password(validated_data['password']) user.save() return user // I also attempted using a TokenSerizlier on my Serilzers.py but it failed. This might be a better way? Error was: create() takes exactly 3 arguments (2 given) class TokenSerializer(serializers.ModelSerializer): class Meta: model = Token fields= ('token',) class UsercreateSerializer(serializers.ModelSerializer): token = TokenSerializer(many=True, read_only=True) class Meta: model = User write_only_fields = ('password',) read_only_fields = … -
Django templates with "dynamic" determination of the header tag
I want to add a help text to a Django app. To do this, I am going to create a Django template which may be included into another templates. The trouble is that I do not know what the title tag for my title should be. For example, it can be <h1> or <h2> or <h3>. How to handle the possibility to easily change the tag? -
Django Upload 'filename' error
The code is simply to upload CVS file and convert data to a LIST. When users upload a csv file, the filename individual users use is not enforced. I will like to be able to work with any filename users uses for the csv file. I am getting this error: File "views.py", line 35, in upload_file phone_list = handle_uploaded_file(request.FILES['phonelistfile']) File "views.py", line 17, in handle_uploaded_file with open(settings.MEDIA_URL+'documents/'+str(filename),'wb') as destination: NameError: name 'filename' is not defined Views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponseRedirect from .models import Upload from .forms import UploadFileForm import csv import io # Imaginary function to handle an uploaded file. #from somewhere import handle_uploaded_file def handle_uploaded_file(f): with open(settings.MEDIA_URL+'documents/'+str(filename),'wb') as destination: for chunk in f.chunks(): destination.write(chunk) destination.close() #csvfile = f csvfile = io.TextIOWrapper(f) # Python 3 Only #dialect = csv.sniffer().sniff(codecs.EncodedFile(csvfile, "utf-8").read(1024)) dialect = csv.sniffer().sniff(csvfile.read(1024), delimiter=";,") #csvfile.open() csvfile.seek(0) #csvreader = csv.reader(codecs.EncodedFile(csvfile, "utf-8"), delimiter=',', dialect=dialect) csvreader = csv.reader(csvfile, dialect) return list(csvreader) def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): phone_list = handle_uploaded_file(request.FILES['phonelistfile']) upload_phone_list = Upload() upload_phone_list.name = request.name upload_phone_list.phonelistfile = request.FILES['file'].file upload_phone_list.phonelist = phone_list #form.save() upload_phone_list.save() return HttpResponseRedirect('/success/url/') else: form = UploadFileForm() return render(request, 'upload.html', {'form': form}) models.py from django.db … -
Dajango rest remove password after creation
I have user create serializer but still it is returning the password and c_password fields. How can I remove that to response. class UserCreateSerializer(ModelSerializer): phone = CharField(label='Phone number') password = CharField(label='password') c_password = CharField(label='confirm passowrd') class Meta: model = User fields = [ 'phone', 'username', 'password', 'c_password' ] extra_kwargs = {"password": {"write_only": True}, "c_password": {"write_only": True}} def create(self, validated_data): phone = validated_data['phone'] username = validated_data['username'] password = validated_data['c_password'] user_obj = User(phone=phone, username=username) user_obj.set_password(password) user_obj.save() return validated_data And I also tried to add the perform_create method and returned the custom Response object. but it is returning the serializer object with passwords. Any help please? -
Django template page display wrong date time format (using DataTable)
My script return a list of date time with a format like '2016-11-09 06:42:53.028447+00:00'. However, on the front end the order of month and date changed to '2016-09-11' Template: '<td>{{ entry.datetime|date:"Y-m-d H:i:s"}}</td>' when I start manage.py on my local machine it display correctly. So i'm wondering there is a setting that I mis-configured. setting.py USE_L10N = False SHORT_DATETIME_FORMAT = 'Y m j, H:i:s.u'