Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I add multiple symptoms for one disease in same Table
Example: I have table named disease and It contains 4 fields: DiseaseId DiseaseName DiseaseType Symptoms As for 1 disease many symptoms can be present.So,can I store as many data as needed in that one field-symptoms? How? And if I cant than whats the other solution? -
form in modal action not working
This is some code from my index.html. My issue is that the action on the form in the modal is not working (no error, just doing nothing) yet the form outside the modal is working fine (commented test button). The modal is opening fine and seems correctly formatted, yet the 'yes' button does nothing but close the modal. The problem does not seem to be in the url. Any help would be much appreciated. {% for patient in all_patients %} <div class="col-lg-12"> <div class="panel panel-default"> <div class="panel-body"> <!-- Name --> <h4>{{ patient }}</h4> <!-- View Details --> <a href="{% url 'patients:patientInfo' patient.id %}" class="btn btn-primary btn-sm" role="button">View Details</a> <!-- Edit Details --> <a href="{% url 'patients:patient-update' patient.id %}" class="btn btn-primary btn-sm" role="button">Edit Details</a> <!-- Delete Patient --> <input type="hidden" name="patient_id" value="{{ patient.id }}" /> <button type="submit" class="btn btn-default btn-sm" data-toggle="modal" data-target="#patient_id"> <span class="glyphicon glyphicon-trash"></span> </button> <!-- Modal --> <div class="modal fade" id="patient_id" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Confirm delete</h4> </div> <div class="modal-body"> <p>Are you sure you want to delete {{ patient }}?</p> </div> <div class="modal-footer"> <button type="submit" class="btn btn-default" data-dismiss="modal">No</button> <form action="{% url 'patients:patient-delete' patient.id %}" method="post" style="display: inline;"> {% … -
Remove b'' from a bytes object to obtain only a string of data
How do i remove the b (bytes) symbol before the long string of data. The code below gets image data from a image input field and try's to convert the data into a string without the b symbol. def view(request): form = FileForm(request.POST or None, request.FILES or None) if form.is_valid(): img_data = request.FILES.get('image').read() data = base64.b64decode(img_data) request.session['img_data'] = data I'v tried encoding and decoding the image data, however in both cases the b symbol remains. data after decode (The decoded data is the exact same as the original image data) b'\x18\x81|\xf5\xa7]\xac\x99\xb4\xf5\xae\xc6&\x127\x1a\xfdw6\xb1\xfe\xfe\x02S6j\x95\xd8\x94\x82\x9d~K\x9bg\x88\xba\xc1\x99\x1b\xe1y\xdd\xf7\xcf\xda\xa0HC\x12Z`:u\x1d\xd4\xa7tAiw\xbe\xfb\xf2\xea\x13\xbc\x1a\x0f\xf9\xf0\xb9\xd4\x07]\xb2\xce\xa7FN\xfbQ\x1d+\xda8m\x92=\x06\x1a8ZA\xb8P\xd6\x07D \n\x97\x05\x95\xcb\xddy8\x01\xd9\x1e\x1d\xfc\x1c\x0b\xce\x01z\x96J\x1c-+\x12V\xb8s\xb9\x00\x11\xfa\x96\x0e\xc4\xf8\xa1\xba\xc0\x18:m\x15\x0c\x9d>\xe8q\x03\x94\xa0\xe4\x10m\xbc\xf8m\xd4\x10\x05\xc1\xa0*\xc8/*\x18\x95\xa1<\x14\x05@Ma\x16]o<R \xc4\xb6\x13\xea\x10*\xa5\x90\xf6\xa1e\xdc\x8f0\x15\xa8\xccC\xb68\x8b\x10\x08\x06LW\xda\x00\x82\xea\x05-sw(\x03\x82X\x85~:1\xcc\x95mS\xfd8`\x039\xfd\xdaC\xb6\xa0q^\xa9\x9d\x0e`\xf8G\x17V#\xc1\xaa\x0bp\x0b\xa7\x1et\xebU\xc1\x04}\x04\xb8c\xc3\x04\xc0\x8c\xd15IF\xa1w\xd4\x0c\x0f\x05iL6\x96\xa4\n\xb0z\x02\xae\xea\x00L\xe8\x08\xfd\x184P\xff"\xe0i\xe2PkC\r\x08l\xbd\x9f' -
Want to Print data from Data Set (Touples) in Django template?
There are response from Django query Data format is : (237146768, u'43 S LUBEC RD', u'LUBEC', u'ME') (455414678, u'PO BOX 41', u'LUBEC', u'ME') Want to print like This in my template : - 237146768 - 43 S LUBEC RD - UBEC - ME ------------ - 455414678 - PO BOX 41 - LUBEC - ME -
How to test Nonetype in python
I am trying to create a model with a upload_photo function using instance of a class. Before creating my first object I always get error claiming 'NoneType' object has no attribute 'id'. I checked various answers and solutions but still could not find a way to test NoneType for a class. I use 3.6 version of Python3 and 1.11 version of Django. Here is my upload function which is used in CFE tutorials. def upload_location(instance, filename): PostModel = instance.__class__ new_id = PostModel.objects.order_by("id").last().id + 1 return '{} {}'.format(new_id, filename) How can I test in the first instance of a class without getting an error? Thanks -
Django - hide app in admin panel
I have django-admin-interface installed in my django app. I configured layout using this plugin and I would like to hide it from admin panel. My goal is to store basic setings in database. Is it possible? I can't find any relations in my code to this plugin. There is only one place in my code (setings.py) where phrase admin_interface appears. INSTALLED_APPS = [ 'mainapp.apps.MainappConfig', 'admin_interface', 'colorfield', 'flat_responsive', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'smart_selects', 'activatable_model', 'bootstrap3', 'mainapp.apps.ConstanceConfig', 'constance.backends.database', 'kronos', 'ckeditor', 'django_admin_listfilter_dropdown', ] Is is possible to hide this area in admin panel? -
AttributeError at /app/api/get
I got an error, AttributeError at /app/api/get Got AttributeError when attempting to get a value for field task_name on serializer TaskSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Color instance. Original exception text was: 'Color' object has no attribute 'task_name'. Now I wanna make a page that shows model's content in json format. models.py is from django.db import models # Create your models here. class Color(models.Model): name = models.CharField(max_length=255) background_color = models.CharField(max_length=255) h1_color = models.CharField(max_length=255) p_color = models.CharField(max_length=255) def __str__(self): return self.name serializers.py is from .models import Color from rest_framework import serializers class TaskSerializer(serializers.Serializer): task_name = serializers.CharField(max_length=100) status = serializers.SerializerMethodField('get_task_status') def get_task_status(self, instance): return instance.status.status class Meta: model = Color fields = ('name', 'background_color', 'h1_color', 'p_color', 'task_name') urls.py is from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'api/get',views.TaskGet.as_view(),name='task-get') ] views.py is from django.shortcuts import render from .models import Color from .forms import ColorForm from .serializers import TaskSerializer from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status # Create your views here. def index(request): d = { 'colors': Color.objects.all(), 'form': ColorForm(), } return render(request, 'index.html', d) class TaskGet(APIView): def get(self, request, format=None): obj … -
Django production build cannot load static files
Previously when DEBUG=True was set my app correctly loaded static files. However I am now creating a production build where DEBUG=False and the static files are not loading. My static files are located within the path: Tutoring/connecting/static When I run the command: python manage.py findstatic --verbosity 2 search_style.css I receive: Found 'search_style.css' here: /Users/callum/Documents/Tutoring/Tutoring/connecting/static/css/search_style.css Looking in the following locations: /Users/callum/Documents/Tutoring/Tutoring/connecting/static /Users/callum/Documents/Tutoring/Tutoring/connecting/static/css /Users/callum/Documents/Tutoring/Tutoring/connecting/static/js /Users/callum/Documents/Tutoring/Tutoring/venv/lib/python2.7/site-packages/django/contrib/admin/static /Users/callum/Documents/Tutoring/Tutoring/venv/lib/python2.7/site-packages/s3direct/static However in the browser the static files do not load. Below I have shared my settings.py and settings_production.py. settings.py ... # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'connecting') ... # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = 'staticfiles' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), os.path.join(os.path.join(BASE_DIR, 'static'), 'css'), os.path.join(os.path.join(BASE_DIR, 'static'), 'js') ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) ... settings_production.py # Inherit from standard settings file for defaults from tutoring.settings import * # Everything below will override our standard settings: # Parse database configuration from $DATABASE_URL import dj_database_url DATABASES['default'] = dj_database_url.config() # Honor the 'X-Forwarded-Proto' header for request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Allow all host headers ALLOWED_HOSTS = ['*'] # Set debug to False DEBUG = False # Static asset configuration STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' … -
How to access populated django 1.11 test database
I have a failing test with Django 1.11. I need to be able to access the test database. The --keepdb option is useless because the saved database contains no data due to transactions being rolled back after each test. I've seen this question asked lots of times before, but always for old versions, or just suggesting to use --keepdb. How can I access the test database populated with test data from a third-party program like Intellij? If I set a breakpoint in my test I can see there's data, but if I connect to the :memory: database, it's still blank presumably because the transaction opened for the test hasn't been committed. -
Django AttributeError: 'NoneType' object has no attribute 'has_header'
Django 1.10 give error when i am try to login in my dashboard. Traceback (most recent call last): File "/Users/guest/epifiction/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/Users/guest/epifiction/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/guest/epifiction/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/guest/epifiction/lib/python2.7/site-packages/django/views/decorators/cache.py", line 58, in _wrapped_view_func add_never_cache_headers(response) File "/Users/guest/epifiction/lib/python2.7/site-packages/django/utils/cache.py", line 230, in add_never_cache_headers patch_response_headers(response, cache_timeout=-1) File "/Users/guest/epifiction/lib/python2.7/site-packages/django/utils/cache.py", line 219, in patch_response_headers if not response.has_header('Last-Modified'): AttributeError: 'NoneType' object has no attribute 'has_header' Here is View code class AuthorLoginView(bracesviews.AnonymousRequiredMixin,authviews.LoginView): form_class = forms.AuthorLoginForm template_name = 'landing_page/demo.html' def form_valid(self, form): username = form.cleaned_data.get('username') userId = User.objects.get(username=username).id try: profile_obj = UserProfile.objects.get(user_id=userId) except UserProfile.DoesNotExist: return super(AuthorLoginView, self).get(self) else: if profile_obj.role_id == 3: redirect = super(AuthorLoginView, self).form_valid(form) remember_me = form.cleaned_data.get('remember_me') if remember_me is True: ONE_MONTH = 30 * 24 * 60 * 60 expiry = getattr(settings, "KEEP_LOGGED_DURATION", ONE_MONTH) self.request.session.set_expiry(expiry) return redirect -
In Django1.8 project, can't find static files in different application
I have started learning Django1.8. In my project, I have 2 applications - one is account app and the other is images app. Each application directory contains static directory. The static directory structures of 2 apps are as follows. account app static/ css/ base.css images app static/ js/ bookmarklet.js css/ bookmarklet.css When I go to http://127.0.0.1:8000/static/css/base.css in account app on the browser, I can find base.css file on the browser. But when I go to http://127.0.0.1:8000/static/js/bookmarklet.js in images app, I get 404 error. 'js\bookmarklet.js' could not be found I'm not sure how can I fix this issue. -
Generate multiple PDF from Django view with Weasyprint
When user click download button I want to generate multiple pdf Currently I can only generate one PDF What I want is to generate two PDF from Django view when user click download button with weasyprint. Below code only generate single PDF def get(self, *args, **kwargs): obj = self.get_object() html_result = super(GenerateInvoicePDFView, self).get(*args, **kwargs) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="%s.pdf"' % obj.name weasyprint.HTML(string= html_result.getvalue()).write_pdf(response) return response This response should generate two PDF, is it possible ? Please help Thanks -
Pushing a field and a method to mixin ruined the program
Django==1.11.4 This model worked fine: class File(CommonUrlMethodsMixin, ItemIsMainMixin, models.Model): item = models.ForeignKey(Item, on_delete=models.PROTECT) user_file = models.FileField(blank=False, max_length=255, upload_to=get_file_path, verbose_name=_("file")) def __str__(self): if self.user_file.name: str_repr = "{}:{}".format(str(self.id), self.user_file.name) else: str_repr = str(self.id) return str_repr But then I wanted to add another model that also has a FileField. The new model will look quite similar to this one. The only difference will be the foreign key. I did like this: class GeneralFileMixin(): user_file = models.FileField(blank=False, max_length=255, upload_to=get_file_path, verbose_name=_("file")) def __str__(self): if self.user_file.name: str_repr = "{}:{}".format(str(self.id), self.user_file.name) else: str_repr = str(self.id) return str_repr class File(CommonUrlMethodsMixin, ItemIsMainMixin, GeneralFileMixin, models.Model): item = models.ForeignKey(Item, on_delete=models.PROTECT) I made migrations. forms.py class FileForm(ModelForm): class Meta: model = File exclude = [] widgets = { 'item': forms.HiddenInput() } **views.py** class FileCreate(LoginRequiredMixin, CreateView): model = File form_class = FileForm But now the FileCreate doesn't show the input field for a file. Well, the migration is here: class Migration(migrations.Migration): dependencies = [ ('files', '0004_auto_20170831_0917'), ] operations = [ migrations.RemoveField( model_name='file', name='user_file', ), ] Well, it really removed user_file. But why didn't it take into account the user_file from the mixin? Well, could you give me a kick here? -
How to display data from ajax response ( json type ) in Django template?
I am using Django Template for displaying data, in template i am calling ajax request like this : {% for entry in entries %} <script> var ids = {{ entry }}; $.ajax({ ....... ....... success: function (data) { alert(JSON.stringify(data)); } }); {% endfor %} Got data in json formate like : [{"model":"main.mymodel","pk":258160,"fields":{"idn":920087058,"name":null,"ico":null,"street":"PO BOX 149","city":"HYDER","state":"AK","zip":"99923"}}] I want to display in Table like (In same template) : idn-920087058 name-null street-PO BOX 149 ... -
How to use ForeignKey django models for USERNAME_FIELD?
In the documentation I read USERNAME_FIELD now supports ForeignKeys USERNAME_FIELD now supports ForeignKeys. Since there is no way to pass model instances during the createsuperuser prompt, expect the user to enter the value of to_field value (the primary_key by default) of an existing instance. I am using Django 1.11.2 and want to set USERNAME_FIELD as a foreign key which is not in my model AUTH_USER_MODELS ? Can someone please show with an example of doing it ? -
Django.. I need to have a DateField which should be updated when auth_user table gets updated
I have created userprofile table. In that table, I have a field date_updated. my date_updated table should automatically update when auth_user table or userprofile table get update. Models.py class UserProfile(models.Model): user = models.ForeignKey(User, related_name='userprofile', on_delete=models.CASCADE) phone_number = models.CharField(max_length=15) known_languages = models.CharField(max_length=100) date_updated = models.DateTimeField(auto_now=False, null=True) user_domain = models.CharField(max_length=100, default=None) Can any one help me????? -
python/django adding directory files to db
I have a folder which contains several pdfs which i would like to add to my db, however with the code below, every time I refresh my page, same data gets added to db again, is there a way to avoid this and only have new data added to the db? Thank you def index(request): path = "/Users/Sam/Desktop/docs" mylist1 = os.listdir(path) mylist2 = glob.glob(path + "//*.pdf") mylist1.pop(0) file = [] for z in mylist1: file.append(os.path.splitext(z)[0]) for (x, y) in zip(file, mylist2): p = File(file_name=x, file_path=y) p.save() all_files = File.objects.all().order_by('file_name') return render(request, 'form/index.html', {'all_files': all_files}) -
Django: Put instance in Html form
I have created a Html check-box form as shown below: <div class="panel b-a"> <h4 class="font-thin padder">Television</h4> <ul class="list-group checkbox-list-group"> {% for channel in channels%} {%if channel.type == 0%} <li class="list-checkbox-item"> <div class="checkbox"> <label class="i-checks i-checks-sm"> <input value="{{channel.id}}" name="channels" type="checkbox"> <i></i> {{channel.name}} </label> </div> </li> {%endif%} {%endfor%} </ul> </div> I have created an Edit page to change the information through the form. The problem is, I am able to load all the data that are in the crispy form but unable to load (in this case, show check the checkbox) the instatnce in the above form. The form.py for the form in my Edit page is shown below: class SubscriptionForm(ModelForm): def __init__(self, *args, **kwargs): super(SubscriptionForm, self).__init__(*args, **kwargs) self.fields['package'].choices = [ (p.id, str(p)+" ("+str(p.tv_number)+" TV(s) and "+str(p.radio_number)+" Radio(s))") for p in Package.objects.all()] self.fields['package'].empty_label = None class Meta: model = Subscription fields = ['package', 'from_date', 'to_date', 'company', 'is_competitor', 'tracking_channels'] widgets = { 'package': forms.Select(attrs={'class': 'form-control', 'ui-jq': 'chosen'}), # 'ad': forms.SelectMultiple(attrs={'class': 'w-md form-control', 'ui-jq': 'chosen', 'data-placeholder':'Campaign'}), 'from_date': DateInput(attrs={'class': 'form-control'}), 'to_date': DateInput(attrs={'class': 'form-control'}), 'company': forms.Select(attrs={'class': 'form-control', 'ui-jq': 'chosen'}), 'is_competitor': forms.Select(attrs={'class': 'form-control', 'ui-jq': 'chosen'}), #'tracking_channels': forms.ChoiceField(attrs={}), } All the data for the checkbox is in the 'tracking_channels' model. How can I show the instance in the … -
Django-Allauth Pipeline Doesn't Get Called
I'm trying to get the following module called from my pipeline: def add_account(backend, details, response, user=None, is_new=False, *args, **kwargs): print ("testing") if is_new: Account.objects.create(id=user.id) with my pipeline settings in my settings.py as: SOCIAL_AUTH_PIPELINE = ( 'social_auth.backends.pipeline.social.social_auth_user', 'social_auth.backends.pipeline.user.get_username', 'social_auth.backends.pipeline.user.create_user', 'Credit_Ledger.pipeline.add_account' 'social_auth.backends.pipeline.social.associate_user', 'social_auth.backends.pipeline.social.load_extra_data', 'social_auth.backends.pipeline.user.update_user_details', ) -
Cannot install Postgis for geodjango
I am trying to follow a geodjango tutorial but am not able to get past the intial installing of all the settings. The app i was working completely worked before my attempt to change it to a psotgresql. I dont mind losing the data just want to able to use geodjango and postgis #settings.py INSTALLED_APPS = [ 'reporter.apps.ReporterConfig', ] DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'geodjango', 'USER': 'postgress', 'HOST':'localhost', 'PASSWORD':'*****', 'POST':'5432' } } GEOS_LIBRARY_PATH = 'C:/Program Files/GDAL/geos_c.dll' #command line error: C:\Users\Janet\Desktop\geodjango>python manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001C13F882950> Traceback (most recent call last): "C:\Users\Janet\AppData\Local\Programs\Python\Python36\lib\ctypes\__init__.py", line 344, in __init__ self._handle = _dlopen(self._name, mode) OSError: [WinError 126] The specified module could not be found I found the library path online as a solution to the problem of not being able to install GDAL -
Database model relationship between two table where each entity can have multiple entity of itself
I am working on travelling app, where users can book online vehicles to travel. On the customer side I would like this flow: Users have to select a from location and a to location Enter how many seats they require Select a travel date Search for a ride/vehicle. Which means, I need to search all the vehicles/rides whose available seats are equal or more than the user wants, and who has this route: from location - to location. And on the merchant/vehicle owner side I would like this flow: Owner/merchant selects a vehicle Create a route by selecting a from location --> and a to location Set price for that trip. An owner can have many vehicles and each vehicle can take different routes and each route can have a different price. Also whether the route is back and forth. However, please consider the example below: A vehicle has a route from A to D and it has a price for that trip. i.e., A-----------------D Price 100 But it can also have sub routes within that route. Example from A to B or B to C, e.t.c. A-----B------------ Price 25 A-----------C------ Price 75 ------B-----C------ Price 25 ------B-----------D Price 75 How … -
JS get buttons’ name and transfer to Django
HELLO,I need to get some buttons' value from HTML, and transfer the value to django view.py. I hardly ever learned JS. Please give me some advice and example. HTML: <button name='A' value='A'></button> <button name='B' value='B'></button> <button name='B' value='B'></button> I want to get the values:A,B,C. and use it in my view, Please notice, I have many buttons, so I can not just write: if 'A' in request.POST ...do something... if 'B' in request.POST ...do something... if 'C' in request.POST ...do something... I need to click one button and get its name value at the same time Thanks for your time. -
Create user from the command line in Django
I am confusing now. I have 3 apps in one project. App1 : use from enduser(web view based app) App2 : use from service provider(web service) App3 : use from system administrator. I want to use django authentication system all of each apps. I can make django project to authenticate App1 user. But, how can I use authentication system of App2 and App3 at the same time. When I run "python manage.py createsuperuser" command, django make App1 user. How can I make App2 user and App3 user using this command? Does someone have any idea? Please help me. -
How to send XML via Django view but still return another HTTP response?
I am dealing with a payment system. The way it works is as follows, You put together a payment request via XML, send it to a URL. The payment server requires that the source URL be defined ahead of time in their backend admin site so it has to come from a specific URL. The server sends back a confirmation that requires a response to a callback URL (specified in the XML). Successful confirmation then signals that the payment has gone through. Done. I have several questions. FIRST, how does the payment server determine the "source URL"? So say I have this line in my urls.py and views.py: urls.py: url('^wx/payment/$', san.views.WechatPayView.as_view()) views.py: class WechatPayView(View): def get(self, request, *args, **kwargs): # puts together a xml package return HttpResponse(xml_response, content_type='text/xml') Does this mean that the payment server will see the request coming from http://www.example.com/wx/payment/? SECOND, as I understand it, a view can only return 1 response. But that means as soon as I reach this view, my site logic just terminates? As in there's nowhere to go after this... (hopefully this makes sense), since it ends with sending a XML to another site. My original plan was to have an jQuery AJAX … -
Django Rest Framework and Graphene comparison
I want to develop a django application with Vue.js which needs JSON data. As a result of my research both Django Rest Framework (DRF) and Graphene will help me give me the JSON data I need. I am now incline to learn and use Graphene because: They say Graphql is better than REST API DRF is more than just giving JSON data so I think it could be too much to use DRF just for the JSON data for the Vue.js Graphene looks to have shorter learning curve than DRF Are all my thoughts right? Please correct me