Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Win10 Django: NoReverseMatch at / Reverse for 'index' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
I am new to python and Django and use win10 system. Django Version:1.9.4. and Python Version:3.6.3. In template D:\Music\music\templates\music\index.html, error at line 29 19 <div class="caption"> 20 <h2>{{ album.album_title }}</h2> 21 <h4>{{ album.artist }}</h4> 22 23 <!-- View Details --> 24 <a href="{% url 'detail' album.id %}" class="btn btn-primary btn-sm" role="button">View Details</a> 25 26 <!-- Delete Album --> 27 <form action="{% url 'delete_album' album.id %}" method="post" style="display: inline;"> 28 {% csrf_token %} 29 <input type="hidden" name="album_id" value="{{ album.id }}" /> 30 <button type="submit" class="btn btn-default btn-sm"> 31 <span class="glyphicon glyphicon-trash"></span> 32 </button> 33 </form> 34 35 <!-- Favorite Album --> 36 <a href="{% url 'favorite_album' album.id %}" class="btn btn-default btn-sm btn-favorite" role="button"> 37 <span class="glyphicon glyphicon-star {% if album.is_favorite %}active{% endif %}"></span> 38 </a> It's my music\urls.py: from django.conf.urls import url from . import views app_name = 'music' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^register/$', views.register, name='register'), url(r'^login_user/$', views.login_user, name='login_user'), url(r'^logout_user/$', views.logout_user, name='logout_user'), url(r'^(?P<album_id>[0-9]+)/$', views.detail, name='detail'), url(r'^(?P<song_id>[0-9]+)/favorite/$', views.favorite, name='favorite'), url(r'^songs/(?P<filter_by>[a-zA_Z]+)/$', views.songs, name='songs'), url(r'^create_album/$', views.create_album, name='create_album'), url(r'^(?P<album_id>[0-9]+)/create_song/$', views.create_song, name='create_song'), url(r'^(?P<album_id>[0-9]+)/delete_song/(?P<song_id>[0-9]+)/$', views.delete_song, name='delete_song'), url(r'^(?P<album_id>[0-9]+)/favorite_album/$', views.favorite_album, name='favorite_album'), url(r'^(?P<album_id>[0-9]+)/delete_album/$', views.delete_album, name='delete_album'), ] urls.py: from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', … -
Celery got neo4j connecting error when run worker on vagrant
I'm using vagrant box ubuntu 14.04 to develop at local. But in vagrant environment, when run celery worker, I got this error: [2017-10-17 10:33:15,188: ERROR/MainProcess] Task insurance.tasks.neo_update_insurance_package[6713980d-1b76-4dc0-9a58-d2ef4ed7f68a] raised unexpected: ServiceUnavailable("Cannot acquire connection to Address(host='127.0.0.1', port=7687)",) Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 438, in __protected_call__ return self.run(*args, **kwargs) File "/vagrant/my_project/my_app/tasks.py", line 78, in neo_update_package save_general_node(pk, Package, NeoPackage) File "/vagrant/meddy_site/core/neo4j_utils.py", line 27, in save_general_node neo_obj = neo_object_type.nodes.get_or_none(id=pk) File "/usr/local/lib/python2.7/dist-packages/neomodel/match.py", line 523, in get_or_none return self.get(**kwargs) File "/usr/local/lib/python2.7/dist-packages/neomodel/match.py", line 507, in get result = self.query_cls(self).build_ast()._execute() File "/usr/local/lib/python2.7/dist-packages/neomodel/match.py", line 411, in _execute results, _ = db.cypher_query(query, self._query_params) File "/usr/local/lib/python2.7/dist-packages/neomodel/util.py", line 28, in wrapper return func(self, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/neomodel/util.py", line 90, in cypher_query self.set_connection(self.url) File "/usr/local/lib/python2.7/dist-packages/neomodel/util.py", line 61, in set_connection max_pool_size=config.MAX_POOL_SIZE) File "/usr/local/lib/python2.7/dist-packages/neo4j/v1/api.py", line 124, in driver return driver_class(uri, **config) File "/usr/local/lib/python2.7/dist-packages/neo4j/v1/direct.py", line 65, in __init__ pool.release(pool.acquire()) File "/usr/local/lib/python2.7/dist-packages/neo4j/v1/direct.py", line 44, in acquire raise ServiceUnavailable("Cannot acquire connection to {!r}".format(self.address)) ServiceUnavailable: Cannot acquire connection to Address(host='127.0.0.1', port=7687) I tried to edit the Vagrantfile and neo4j.conf settings like below but it didn't work: Vagrantfile # -*- mode: ruby -*- # vi: set ft=ruby : VAGRANTFILE_API_VERSION = "2" client_vagrantfile = File.expand_path('../Vagrantfile.custom', __FILE__) if … -
Django: No m2m_changed signal when one side of a many-to-many is deleted?
I want to trigger some behaviour whenever a many-to-many relationship changes, but I'm unsure what signal setup is best for capturing changes to that relationship that come about due to the deletion of one side of the relationship. m2m_changed does not seem to fire in this case, nor do the regular post_save and post_delete signals seem to be applicable to the through model? My current solution is to listen to pre_delete on the models which compose either side of the relationship and then clear the relationship within that signal in order to trigger a m2m_changed. I'm surprised that I have to do this though, and feel I've got something wrong. What am I missing here? And if I am not missing anything why is this necessary (ie why is no such signal fired by default)? Code example: class ResearchField(models.Model): name = models.CharField(unique=True, max_length=200) class Researcher(models.Model): name = models.CharField(max_length=200) research_fields = models.ManyToManyField(ResearchField, blank=True) @receiver(m2m_changed, sender=Researcher.research_fields.through) def research_fields_changed(sender, instance, action, **kwargs): # need to do something important here print('m2m_changed', action) volcanology = ResearchField.objects.create(name='Volcanology') researcher = Researcher.objects.create(name='A. Volcanologist') researcher.research_fields.add(volcanology) >>> m2m_changed pre_add >>> m2m_changed post_add This m2m_changed signal fires as expected when the relationship is removed from either side: researcher.research_fields.remove(volcanology) # or equally … -
Django/Wagtail trying to create generic child classes
I'm working on a Django/Wagtail app and I'm trying to create generic, reusable components in my models. I'm trying to follow the way the built-in Image classes work since they can be attached to any other object type. However I keep getting an error: AttributeError: 'ReverseSingleRelatedObjectDescriptor' object has no attribute 'related' Here is my code for the models: class DownloadObject(models.Model): title = models.CharField(max_length=255) description = RichTextField(blank=True) download_link = models.URLField() cover_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) class Meta: abstract = True class Download(DownloadObject): admin_form_fields = ( 'cover_image', 'title', 'description', 'download_link', ) class Container(Page): body = RichTextField(blank=True) downloads = models.ForeignKey( 'Downloads', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), InlinePanel('downloads', label="downloads"), ] -
How would my template look like given this Django model?
I am trying to make a simple dental chart interface but having troubles making the template. I guess my challenge started with how I designed my previous models. A dental chart is composed of 32 teeth, each tooth has its own attributes. Below is my model: class DentalChart(models.Model): patient = models.ForeignKey(PatientInfo, on_delete=models.CASCADE) date = models.DateField() dentist = models.CharField(max_length=100) PERIODONTAL_CHOICES = ( ('Gingivitis', 'Gingivitis'), ('Early Periodontitis', 'Early Periodontitis'), ('Moderate Periodontitis', 'Moderate Periodontitis'), ('Advanced Periodontitis', 'Advanced Periodontitis'), ('N/A', 'N/A') ) periodontal_screening = MultiSelectField(choices=PERIODONTAL_CHOICES, default='') OCCLUSION_CHOICES = ( ('Class(Molar)', 'Class(Molar)'), ('Overjet', 'Overjet'), ('Overbite', 'Overbite'), ('Midline Deviation', 'Midline Deviation'), ('Crossbite', 'Crossbite'), ('N/A', 'N/A') ) occlusion = MultiSelectField(choices=OCCLUSION_CHOICES, default='') APPLIANCES_CHOICES = ( ('Orthodontic', 'Orthodontic'), ('Stayplate', 'Stayplate'), ('Others', 'Others'), ('N/A', 'N/A') ) appliances = MultiSelectField(choices=APPLIANCES_CHOICES, default='') TMD_CHOICES = ( ('Clenching', 'Clenching'), ('Clicking', 'Clicking'), ('Trismus', 'Trismus'), ('Muscle Spasm', 'Muscle Spasm'), ('N/A', 'N/A') ) TMD = MultiSelectField(choices=TMD_CHOICES, default='') class Tooth(models.Model): chart = models.ForeignKey(DentalChart, on_delete=models.CASCADE) tooth_id = models.CharField(max_length=2) CONDITIONS_LIST = ( ('', ''), ('Present Teeth', 'P'), ('Decayed', 'D'), ('Missing due to Carries', 'M'), ('Missing (Other Causes)', 'Mo'), ('Impacted Tooth', 'Im'), ('Supernumerary Tooth', 'Sp'), ('Root Fragment', 'Rf'), ('Unerupted', 'Un') ) condition = models.CharField(max_length=30, choices=CONDITIONS_LIST, default='') RESTORATIONS_LIST = ( ('', ''), ('Amalgam Filling', 'A'), ('Composite Filling', 'Co'), ('Jacket Crown', 'Jc'), ('Abutment', … -
How to bring data from selected user to update it
I'm studying django and trying to make a simple CRUD, following the djangoGirls tutorial. But unfortunatelly they don't show how to UPDATE data. I'm already Inserting, Reading/listing how may I Delete and Update? I listed the users with an link to edit it: {% extends 'bloodDonation/master.html' %} {% block content %} <h1 class="center">LIST DONATORS<h1> <ul> {% for donator in donators %} <div class="row"> <div class="container"> <div class="col s12 blue-grey lighten-5 border_lighten"> <div class="col s12 m12 padding_normal"> {{ donator.name }} <div id="icon" class="right"> <a href="{% url 'edit_donator' %}" class="tooltipped" data-position="right" data-delay="50" data-tooltip="Editar Dados""> <i class="material-icons">edit</i></a> </div> </div> </div> </div> </div> {% endfor %} </ul> {% endblock %} As you can see, I have a a tag pointing to edit_donator url. How may I pass the ID/data of the selected/clicked user so I can pull his data and throw it inside the form? Form creation: class EditDonatorForm(forms.ModelForm): class Meta: model = Donator fields = [ 'name', 'age', 'email', 'phone', 'bloodType', 'observation' ] How may I get data from database and already place it inside form so I can perform an Update? -
Map over AForm to change form "name" settings
I am trying to implement something akin to Django's formsets, where you have multiple nested forms inside a single main form. type FormsetCount = Int mainForm :: AForm FormsetCount mainForm = areq intField "formset-count" (Just 0) subForm :: AForm Bool subForm = areq boolField "foo" Nothing -- later ... ((result, formW), _) <- lift $ runFormPost $ renderDivs $ mainForm Nothing formsetWidgets <- case result of FormSuccess count -> do for [1..count] $ \i -> lift $ runFormPost $ renderDivs $ subForm Nothing _ -> pure [] In this example, the generated ids for mainForm and subForm would obviously clash. Combining them first into a single form and therefore get fresh ids is not an option, because I want to be able to generate more formsets dynamically from javascript. My idea is to render each subForm independently of the mainForm, but as part of the same <form>. To do this, I would suffix (or prefix) all fields in the subForm with a running integer (up to "formset-count"). This would isolate each subform from the fields in it's parent and would allow me to dynamically (via JS) add more formset items. Now, the problem I am facing is that in order … -
Django new URL not working
So I'm trying to access a URL, http://localhost:8000/calc, but it gives me this error: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^admin/ ^$ [name='home'] ^calc/ The current path, calc, didn't match any of these. This is what I currently have for mysite URL and secondapp URL: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'',include('firstapp.urls')), url(r'^calc/',include('secondapp.urls')), ] from django.conf.urls import url from secondapp.views import CalcPage urlpatterns = [ url(r'calc/', CalcPage.as_view(), name='calc'), ] -
django global variable across web pages?
How to pass a variable between web pages/functions? For example, let's say when I visit webpage "test3.html", I'd like to get the sum of variables a_test1 and a_test2, which are "global" variables which increased as visiting test1.html and test2.html. test1.html, test2.html and test3.html could be visited multiple times and independently. The following code doesn't work as it is, but it would if I can somehow make a_test1 and a_test2 global variables? Can that be done? Another option maybe passing these variables by the "request" parameter? Can it be done that way? urlpatterns = [ url(r'^test1/$', views.test1), url(r'^test2/$', views.test2), url(r'^test3/$', views.test3), ] in views.py: def test1(request): a_test1=1+a_test1 return render(request,'test1.html',{'a_test1': a_test1}) #other stuffs def test2(request): a_test2=1+a_test2 return render(request,'test2.html',{'a_test2': a_test2}) #other stuffs def test3(request): a_test3=a_test1+a_test2 return render(request,'test3.html',{'a_test3': a_test3}) #other stuffs -
Django - show an image when a submit button is clicked
I would like to show an image when a user clicks a submit button. I want to just change the image, not render the whole page. What is the best way to do this? -
In django-taggit, is there a way to get all tags assoicated to a model?
I know how to get all tags, but let's say the tags are connected to lots of different models. Somehow I just want to extra the tags that is attached to a model not ALL tags. Is this possible? I know that I can do it in reverse, get the model then get all the tags, but I have LOTS rows in that model and if I try it this way, I have to get all rows then loop through all rows to get queryset of the tags But all I want is get all the tags attached to the model and count the tags. I do not require to know which row of the model is using this tag. Thanks in advance for any help. -
Digital Ocean: One Click Django Won't Route My Domain, Bad Gateway
The one click django with ubuntu 16, nginx, and gunicorn is not routing my domain name. When I type the IP address into the address bar it works but when when I use the domain I get 502 Bad Gateway nginx/1.10.3 (Ubuntu). Looking at the nginx error log I see: 2017/10/16 19:05:18 [error] 23017#23017: *80 upstream prematurely closed connection while reading response header from upstream, client: redacted server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/" I followed the steps here: https://www.digitalocean.com/community/tutorials/how-to-point-to-digitalocean-nameservers-from-common-domain-registrars#registrar-godaddy and here: https://www.digitalocean.com/community/tutorials/how-to-set-up-a-host-name-with-digitalocean But I must have done something wrong. Anyone have any ideas how to solve this. I am brand new to DO, Django, and really web dev. -
search autocomplete with django haystack
I use haystack like search engine in my django application. My search engine only with solid word. Example: I store pictures with different informations. In author_full_name field, I have 'serenmovan'. If I put 'serenmovan' in the search engine it works but I put 'ser' or 'mov' no results. Same thind for the other fields. here is my search_indexes.py : class PictureIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) author = indexes.CharField(model_attr='author', boost=1.5) author_full_name = indexes.CharField(boost=1.5) artist_location = indexes.CharField() uid = indexes.CharField(model_attr='uid') name = indexes.CharField(model_attr='name') slug = indexes.CharField(model_attr='slug') description = indexes.CharField(model_attr='description') orientation = indexes.CharField(model_attr='orientation') price_range = indexes.CharField(model_attr='price_range') thumbnail = indexes.CharField(model_attr='thumbnail') thumbnail_landscape = indexes.CharField(model_attr='thumbnail_landscape') thumbnail_portrait = indexes.CharField(model_attr='thumbnail_portrait') preview_large = indexes.CharField(model_attr='preview_large') created = indexes.DateTimeField(model_attr='created') tags = indexes.MultiValueField() admin_tags = indexes.MultiValueField(boost=2) google_tags = indexes.MultiValueField(boost=2) def get_model(self): return Picture def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().active_objects.filter(created__lte=datetime.datetime.now()).select_related() def prepare_tags(self, obj): return [tag.name for tag in obj.tags.all()] def prepare_admin_tags(self, obj): return [tag.name for tag in obj.admin_tags.all()] def prepare_google_tags(self, obj): return [tag.name for tag in obj.google_tags.all()] def prepare_author_full_name(self, obj): return obj.author_full_name def prepare_artist_location(self, obj): try: return obj.author.artistprofile.address.city except: pass` -
Setting Django model primary key field for translation with django-modeltranslation
I've searched in readthedocs.io but didn't find a solution. I'm using django-modeltranslation to translate my models in my Django project. Now, I'm trying to translate a model that has only one field, that is a primary key. models.py: class Gender(models.Model): name = models.CharField(max_length=50, primary_key=True) def __str__(self): return self.name translation.py: class GenderTranslationOptions(TranslationOptions): fields = ('name',) translator.register(Gender, GenderTranslationOptions) Running python manage.py makemigrations I'm having the following error: SystemCheckError: System check identified some issues: ERRORS: experiments.Gender.name_en: (fields.E007) Primary keys must not have null=True. HINT: Set null=False on the field, or remove primary_key=True argument. experiments.Gender.name_pt_br: (fields.E007) Primary keys must not have null=True. HINT: Set null=False on the field, or remove primary_key=True argument. It looks like it's trying to create name_en and name_pt_br fields as primary keys, what it's not the case because only name field is supposed to be primary key. What can we do in a case like this. The docs don't refer to creating that fields manually, nor a way of defining fields attributes in translation.py, at least until I know from them. -
Django and mod_wsgi installation suddenly stopped working
I have a script which I use to install my application on a virtual machine using django 1.9.6 and mod_wsgi. It use to work fine for at least a year and then after a few months I didn't use it - it's suddenly not working. I am always installing on a clean ubuntu trusty image and I didn't make any changes. So my guess is that apt-get is installing a different version of libapache2-mod-wsgi now. sudo apt-get update sudo apt-get install -y python-pip sudo pip install django=1.9.6 sudo apt-get -y install apache2 libapache2-mod-wsgi ... When I try to run the application the apache server gives the error: mod_wsgi (pid=8486): Target WSGI script '/root/geosearch_app/geosearch_project/geosearch_project/wsgi.py' cannot be loaded as Python module. I hope to solve this without actually changing anything except the installation script and that should work since it worked before. Any advice? -
How to send an email with excel file as attachment using django
I have an excel file in a specific folder and would like to send it via email. To do this, was trying to use openpyxl My code : fileToAttach = load_workbook(pathToFile) msg = EmailMultiAlternatives(subject, text_content, from_email, ['myMail@gmail.com']) msg.attach_alternative(html_content, "text/html") msg.attach("Report.xlsx", fileToAttach, "application/vnd.ms-excel") msg.send() But it returns an error: 'Worksheet -1 does not exist.' Could you tell me what I am doing wrong ? Thanks, -
Get data from two django models
My models look like this: class UserDevice(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=False) device = models.ForeignKey(Device, on_delete=models.PROTECT, null=False) activation_date = models.DateTimeField(default=timezone.now, null=False) friendly_name = models.CharField(max_length=20, null=True, blank=True) is_owner = models.BooleanField(null=False, default=False) is_admin = models.BooleanField(null=False, default=True) is_alerts_enabled = models.BooleanField(null=False, default=True) timeStamp = models.DateTimeField(auto_now = True, null=False) class UserProfile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=False) token = models.TextField(null=False, blank=True) first_name = models.TextField(null=True, blank=True) last_name = models.TextField(null=True, blank=True) timeStamp = models.DateTimeField(auto_now = True, null=False) I need to get device, user, is_alerts_enabled, is_admin, is_owner from UserDevice and first_name, last_name, token from userProfile. This is what I have so far and it gives me what I need from userdevice but I can't figure out how to add the userprofile stuff. nonOwners = UserDevice.objects.filter(device=device, is_owner=False) if nonOwners is None: return errormsg('non nonOwners found for this device') nonOwnersArray=[] for nonOwner in nonOwners: nonOwner_data = model_to_dict(nonOwner, fieldlist=( 'device.serial', 'user.email', 'is_alerts_enabled', 'is_admin', 'is_owner', ), rename={ 'device.serial': 'serial', 'user.email': 'email'}) nonOwnersArray.append(nonOwner_data) Any help would be greatly appreciated. Thanks! -
Django - usage of redirect_to_login
I want to use redirect_to_login in my view. For some reason, I get redirected to login twice (and therefore the URL is malformed). My TestView(View) looks like this (relevant part): def dispatch(self, request, *args, **kwargs): if not self.test_func(): if self.redirect_to_login: return redirect_to_login(self.request.get_full_path()) else: return HttpResponseForbidden() My urls.py (relevant part): url(r'^test/$', TestView.as_view()), When I type localhost:8000/test/ into my browser, I end up at http://localhost:8000/login/?next=/%3Fnext%3D/test/ instead of expected http://localhost:8000/login/?next=/test/ Any ideas what the problem might be? In case you need more files, just please ask. -
Django ManyToMany Through model inline in ModelForm
I'm trying to figure out the simpiest way to add through model into the modelform. class UserProfile(models.Model): user = models.OneToOneField('auth.User',related_name='userprofile') profile_picture = models.ImageField() #TODO: povinne ale moze vybrat z defaultov languages = models.ManyToManyField('userprofiles.Language',through='UserProfileLanguage') class UserProfileLanguage(models.Model): userprofile = models.ForeignKey('UserProfile',related_name='userprofile_languages') language = models.ForeignKey('Language') level = models.CharField(max_length=50,choices=settings.USERPROFILE_LANGUAGE_LEVEL_CHOICES) class Language(models.Model): english_name = models.CharField(max_length=100, unique=True) native_name = models.CharField(max_length=100,null=True, blank=True) As you can see userprofile can have multiple languages, but there is a level of this knowledge required. I can't add 'languages' field into a ModelForm fields because I need to specify level for any language. I'm curious if there is some built in way to do this or should I create manualy ModelFormset and override UserProfile save(..) method. -
How do I host a Django project on a host that already exists?
I have a project in Django and I have a host that was sent to me where my project should appear, but I do not know how I will do it. I uploaded the project folder with a Filezilla, but I do not know if it is possible to run the Django commands in SSH or SFTP. I've watched some related videos, but they all teach how to host them in Heroku and PythonAnyWhere, but I need to host it on my university website. What should I do? -
Django makemigrations wonkyness
I am experience two, probably related, odd issues that have just recently began plaguing me. Issue One: When I run python makemigrations myapp --settings=mysettings it detects a change in one of my models that I did not make. Namely, it detects an 'id' field added to my model without a default. It therefore wants me to provide a one-off default. When I do this, it then fails to migrate giving me generic error messages such as the in() argument must be a string or a number, not (whatever I entered, an integer, a string, a datetime, anything as a one-off). The annoying thing about this is that there is no ID field added and I am not sure why it is detected this change. Issue Two: Makemigrations is not detecting changes. I recently added a new model to a django app that has been working fine for quite some time. It does indeed exist in the installed apps, however it will not detect that a new model is being added to my models.py of this app. There is really no reason I can see this happening. I have been working around this issue by writing my own migration files, but … -
Auto-generated field 'user_ptr' clashes with declared field of the same name
I have a Django app that has CustomUser. My model looks something like class CustomUser(AbstractBaseUser): def get_short_name(self): pass def get_full_name(self): pass firstName = models.CharField(max_length=300) middleName = models.CharField(max_length=300, blank=True) lastName = models.CharField(max_length=300, blank=True) username = models.CharField(unique=True, max_length=50) businessName = models.CharField(max_length=500, default=None) mobileNumber = models.CharField(max_length=20) contactNumber = models.CharField(max_length=20) addressLine1 = models.CharField(max_length=300) addressLine2 = models.CharField(max_length=300) city = models.CharField(max_length=300) state = models.CharField(max_length=300) role = models.CharField(max_length=20) email_id = models.CharField(max_length=300, unique=True) aadharNumber = models.BigIntegerField(default=0) panNumber = models.CharField(max_length=20, default=None) registrationDate = models.BigIntegerField(default=0) bankDetail = models.ManyToManyField('BankDetail', related_name="bankDetail") dateCreated = models.DateTimeField(auto_now_add=True) dateModified = models.DateTimeField(auto_now=True) objects = AccountManager() USERNAME_FIELD = 'email_id' REQUIRED_FIELDS = ['username'] I was following the example in this blog https://afropolymath.svbtle.com/authentication-using-django-rest-framework to implement User authentication. I get the following error when I run makemigrations I did look at a few solutions on StackOverflow but those don't seem to solve my problem. Django error message "Add a related_name argument to the definition" AlterField on auto generated _ptr field in migration causes FieldError Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line … -
Django Serializes not outputting to template
I have a local branch and a remote dev branch. These instructions work on the local branch perfectly, but when I push to the remote branch they do not. They're both running the same django version and the files are identical!! $(document).delegate("#btn-generate-note", "click", function(event) { var stringToTransfer = ""; var json = [{"model": "logi.tblpolines", "pk": 2014279, .... etc }); That's the output from the browser: A beautiful JSON for var json, but this is the output from the remote server: $(document).delegate("#btn-generate-note", "click", function(event) { var stringToTransfer = ""; var json = ; ... It's nothing. I can't for the life of me reason why. Here's the template.html code: var stringToTransfer = ""; var json = {{ json_list_items|safe }}; And the view.py code: json_list_items = serializers.serialize('json', items_query.objects.all()) ... return render(request, 'some/address/in/space.html', context={ 'po_id': po_id, ... 'json_list_items': json_list_items }) The imports are identical everything is the same, but I'm not getting a json back in the remote. I've been on this for hours. -
Django Channels websocket connection handshake failing
I've been trying to follow this tutorial on using Django Channels for a WebSocket-enabled web app. When I get to the part where I'm supposed to test if the server is accepting sockets, I get the following error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "E:\Python\django\multichat\venv\lib\site-packages\websocket\_core.py", line 214, in connect self.handshake_response = handshake(self.sock, *addrs, **options) File "E:\Python\django\multichat\venv\lib\site-packages\websocket\_handshake.py", line 69, in handshake status, resp = _get_resp_headers(sock) File "E:\Python\django\multichat\venv\lib\site-packages\websocket\_handshake.py", line 129, in _get_resp_headers raise WebSocketBadStatusException("Handshake status %d", status) websocket._exceptions.WebSocketBadStatusException: Handshake status 200 Also, according to the tutorial, I'm supposed to see something akin to this in the server console: WebSocket CONNECT / [127.0.0.1:55905] But instead I am getting this: "GET / HTTP/1.1" 200 1716 It's looking like either my python shell script is sending an HTTP request when its supposed to be sending a WebSocket request, or my server is interpreting the WebSocket request as an HTTP request. I have no idea what would cause either of those things to happen. My settings.py file is a freshly generated one with only the following added to it: redis_host = os.environ.get('REDIS_HOST', 'localhost') # Channel layer definitions # http://channels.readthedocs.org/en/latest/deploying.html#setting-up-a-channel-backend CHANNEL_LAYERS = { "default": { # This example app uses the … -
Django page not found, ajax request not working correctly
Trying to send an ajax request to a django server and get a response containing some random data. The homepage works, but the ajax request gives a 404 error as follows: Using the URLconf defined in bms_project.urls, Django tried these URL patterns, in this order: ^headstation/ ^admin/ The current path, chart_data/, didn't match any of these. You're seeing this error because you have <code>DEBUG = True</code> in your Django settings file. Change that to <code>False</code>, and Django will display a standard 404 page. The url pattern is listen in a urls.py file inside the "headstation directory, then included by the normal urls.py script. It works for the home page: project urls.py urlpatterns = [ url(r'^headstation/', include('headstation.urls')), url(r'^admin/', admin.site.urls), ] headstation urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^chart_data/$', views.chart_data, name='chart_data') ] views.py def index(request): # get context of request from client context = RequestContext(request) # construct dictionary to pass template + context context_dict = {'buildingName': 'The Building', 'boldmessage': 'Put a message here'} #render and return to client return render_to_response('headstation/home.html', context_dict, context) def chart_data(request): if (request.method == 'POST'): dataX = [0,10,20,30,40,50,60] dataY = [25.0,24.2,25,24.0,24.5,25.1,25.5] response = {"x": dataX, "y": dataY} return JsonResponse(response) and finally, home.html where the ajax request is coming …