Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Scheduled POST with django and ajax
Okay guys, I'm pretty stumped with this one! So, I am trying to routinely post the contents of a txt file onto a website. (IE update the file daily and post the new one) I am using django as the framework and have everything working..... almost. Following this question: Periodically fetch data and display it with Django I set up the views, templates, and urls so that $.ajax is called whenever I load the page. And that part works! If I manually load the page into a browser, the data is updated and displayed correctly. However, automating it has been problematic. If I had to guess, I would say that.. for some reason, $.ajax is not being called when there is not a browser. Here is the requests.py code: import requests login_url = "http://127.0.0.1:8000/login/" soup_url = "http://127.0.0.1:8000/soups/pull/" test_url = "http://127.0.0.1:8000/profiles/myusername" UN = 'myusername' PW = 'mypassword' with requests.session() as client: # get the login page client.get(login_url) # save session credentials csrftoken = client.cookies['csrftoken'] login_data = {'username':UN,'password':PW,'csrfmiddlewaretoken': csrftoken} # login client.post(login_url, data=login_data) client.get(test_url) # get the page that loads $.ajax client.get(soup_url) And, the $.ajax request comes from: {% extends "base.html" %} {% block script %} <script> $(document).ready(function(){ function pullSoup(){ var token … -
Python Bots plugins stop working after unzipping and zipping back
Python Bots plugins stop working after unzipping and zipping back on Linux. I checked original zip file and zip after unzipping/zipping and they have different size and look different in DIFF. Python gets stuck trying to read same plugin after simply zipping and unzipping it. It has probably something to do with character encoding (author of bots edi lives in Europe), but I am new to python and don't know how you Python guys deal with this issue.Google search did not produce any results for me. Please help. -
can it be possible to use autheticate method in django with only one parameter as email?
As mentioned above that I want to use django "authenticate" method with one parameter as email because I use mastodon api for authenticating user and I already got access token from mastodon. After this I just want to check that whether that email is present in django's user table or not with the help of any django method. I used authenticate method but it fails in the use case of password reset. Is there any method in django which can authenticate user with only email. I mention my code below if any modification in the code make that code runs would be appreciable. Django Code: CHECKING CLIENT CREDENTIALS########## mastodon_var = mastodon.Mastodon( client_id='gnowsys_ndf/ndf/NROER-client_cred.secret', api_base_url='https://member.metastudio.org' ) access_token = None ####GET ACCESS FROM MASTODON HERE####### try: access_token = mastodon_var.log_in( Username, Password, to_file='gnowsys_ndf/ndf/NROER-access_token.secret', ) except Exception as e: print e pass name = Username email = Username password = Password # userna = mastodon_var.u"username" # print userna #######IF USER GETS ACCESS TOKEN THEN FOLLOWING CODE WILL BE EXECUTED########## if access_token: if User.objects.filter(username=name).exists(): ####SECOND AND BY-DEFAULT LAYER FOR AUTHENTICATION user = authenticate(username=name,password=password) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect( reverse('landing_page') ) else: HttpResponse("Error1") return HttpResponseRedirect( reverse('landing_page') ) else: member = User.objects.create_user(name,email,password) … -
PostgreSQL ALTER SEQUENCE using psycopg2 in django
I am trying to alter sequence of id field in my table using psycopg. This is works fine on my local server, but not working on production. I am not getting exceptions, the sequence is just not restarting. def alter_sequence(last_id): try: dbname = settings.DATABASES['default']['NAME'] user = settings.DATABASES['default']['USER'] host = settings.DATABASES['default']['HOST'] password = settings.DATABASES['default']['PASSWORD'] port = settings.DATABASES['default']['PORT'] connection = psycopg2.connect( dbname=dbname, user=user, password=password, host=host, port=port, ) cursor = connection.cursor() cursor.execute('ALTER SEQUENCE "gs_requests_id_seq" RESTART WITH {}'.format(last_id)) connection.close() except Exception as e: print(e) pass I double-checked the database settings - its correct. Other database operations, performed by django ORM with this settings is works fine. I think, this is not enough information about my project settings but dont know what information I need to specify. I have postgres 9.6 on my local computer and 10.1 on production. -
haystack index_queryset returning empty objects
I have this search index class ProductCreateModelIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True,template_name='search/indexes/catalogue/product_text.txt') title = indexes.EdgeNgramField(model_attr='title') description = indexes.CharField(model_attr='description',null = True) category = indexes.CharField(model_attr='category',faceted=True ) brand = indexes.CharField(model_attr='brand_name',faceted=True ) model = indexes.EdgeNgramField(model_attr='model_name',null = True) # for auto complete content_auto = indexes.EdgeNgramField(model_attr='title') # Spelling suggestions suggestions = indexes.FacetCharField() def prepare_availability_regions(self, obj): return [ availability_region.region_str for availability_region in obj.availability_regions.all()] def prepare(self, obj): prepared_data = super(ProductCreateModelIndex, self).prepare(obj) prepared_data['suggestions'] = prepared_data['text'] return prepared_data def index_queryset(self, using=None): q_set = self.get_model().objects.filter(is_active=True) print('this is query set',q_set) return q_set for non active objects its returning empty objects like this is query set <QuerySet [<ProductCreateModel: new>]> this is query set <QuerySet [<ProductCreateModel: new>]> Object could not be found in database for SearchResult '<SearchResult: products.productcreatemodel (pk='37')>'. What the heck problem is I have a task for every object in html but, for loop in template tag is also true for empty objects !!! and I don't want this ! -
Tag suggestion system using Django
I'm trying to develop a tag system similar to StackExchange. Since I'm using Django, I can think in two ways to suggest tags while a user is typing: Pass all tags in the context to the template and handle using JS or similar Query the database while user is typing I expect to have around 500 tags, which way would be faster? Is there a better way to do this? Thank you. -
Django REST y android (response template)
I'm doing a project that requires connecting android and django rest and everything worked fine but there is a problem when visiting the url of the view generates a template that I do not want to show. I need you to return the answer for the android application and then redirect to another page or always show the blank page. restapp/view.py class postList(APIView): def get(self, request): allpost = Post.objects.all() serializer = postSerializer(allpost, many=True) return JsonResponse({"message":"get all","state":"1","control":serializer.data}) project/urls.py from restapp import views urlpatterns = [ url(r'^admin/', admin.site.urls), url('post/', views.postList.as_view()), ] -
AttributeError: 'WSGIRequest' object has no attribute 'status_code'
I got an error,AttributeError: 'WSGIRequest' object has no attribute 'status_code'.I wrote test code, def test_user(self): obj = { "username": "tom", "email": "tom@gmail.com", "password": "" } factory = APIRequestFactory() response = factory.post('http://127.0.0.1:8000/polls/data/', obj) self.assertEquals(response.status_code, 400) but when I run this code,the error happens.I followed this web site http://www.django-rest-framework.org/api-guide/testing/ to write the test code,I think why this error happens.Of course,type of response is different from my ideal one,but what should I do?How can I fix this? -
Deploying Django on Daphne to Heroku: Heroku won't read my ENVs
I've deployed my app onto Heroku using Daphne as my server. The Daphne process will start, read through my config.production settings, output indication that it's searching for my ENV vars as listed in settings, then exit with status 0. This is the Daphne command I'm running: daphne -b 0.0.0.0:$PORT config.asgi:application -v2 Here's some of the relevant output: 2018-03-28T04:36:00.894609+00:00 heroku[web.1]: Starting process with command `/bin/sh -c daphne\ -b\ 0.0.0.0:\19859\ config.asgi:application\ -v2` 2018-03-28T04:36:02.946809+00:00 app[web.1]: 2018-03-28 04:36:02,946 DEBUG Importing BmpImagePlugin 2018-03-28T04:36:02.950317+00:00 app[web.1]: 2018-03-28 04:36:02,950 DEBUG Importing BufrStubImagePlugin ... 2018-03-28T04:36:03.092570+00:00 app[web.1]: 2018-03-28 04:36:03,092 DEBUG get 'DJANGO_READ_DOT_ENV_FILE' casted as '<class 'bool'>' with default 'False' 2018-03-28T04:36:03.092881+00:00 app[web.1]: 2018-03-28 04:36:03,092 DEBUG Read environment variables from: /usr/src/app/.env 2018-03-28T04:36:03.094088+00:00 app[web.1]: 2018-03-28 04:36:03,093 DEBUG get 'DJANGO_DEBUG' casted as '<class 'bool'>' with default 'False' 2018-03-28T04:36:03.096322+00:00 app[web.1]: 2018-03-28 04:36:03,094 DEBUG get 'DATABASE_URL' casted as 'None' with default '<NoValue>' 2018-03-28T04:36:03.096324+00:00 app[web.1]: 2018-03-28 04:36:03,094 DEBUG get 'DJANGO_EMAIL_BACKEND' casted as 'None' with default 'django.core.mail.backends.smtp.EmailBackend' I've set "config vars" using Heroku's console for most of these. When it didn't work, I simply uploaded my entire .env file to Heroku as well, which allowed for this: 2018-03-28T04:36:03.092881+00:00 app[web.1]: 2018-03-28 04:36:03,092 DEBUG Read environment variables from: /usr/src/app/.env Still, it's not reading any of the vars that I set … -
Django trouble collecting static using Whitenoise and pushing to Heroku - Getting UnicodeDecodeError
Before Installing Whitenoise, I could collect static and everything works perfect locally, but after installing Whitenoise and attempting to push my files to heroku for production, I got the following error: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/static/static' I then attempted to collect static through my terminal to troubleshoot and got this error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte I'm new, and it's tough to understand where to start to troubleshoot this. I tried messing around with my static directory settings with no luck, but it seems that the location is fine, but whitenoise is failing to collect anything because of this Unicode error and that's why I can't push it to Heroku. I'm unsure of how to figure out where this error is located from the traceback, or how to fix it. Here is the full traceback: execute_from_command_line(sys.argv) File "C:\Users\Jup\PycharmProjects\Landing\Gas\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\Jup\PycharmProjects\Landing\Gas\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Jup\PycharmProjects\Landing\Gas\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Jup\PycharmProjects\Landing\Gas\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Users\Jup\PycharmProjects\Landing\Gas\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 189, in handle collected = self.collect() File "C:\Users\Jup\PycharmProjects\Landing\Gas\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 129, in collect for original_path, processed_path, processed in … -
WSGI Segmentation Fault After Upgrade from Apache 2.2 to 2.4 on Debian Linux with Django
After running a dist-upgrade from debian 7.1 to 8.10, WSI seg faults with the following errors in the Apache logs: [Tue Mar 27 21:06:34.843952 2018] [core:notice] [pid 117022] AH00052: child pid 128687 exit signal Segmentation fault (11) [Tue Mar 27 21:06:34.844011 2018] [wsgi:info] [pid 117022] mod_wsgi (pid=128687): Process 'icmlcc' has died, deregister and restart it. [Tue Mar 27 21:06:34.844021 2018] [wsgi:info] [pid 117022] mod_wsgi (pid=128687): Process 'icmlcc' terminated by signal 11 [Tue Mar 27 21:06:34.844030 2018] [wsgi:info] [pid 117022] mod_wsgi (pid=128687): Process 'icmlcc' has been deregistered and will no longer be monitored. [Tue Mar 27 21:06:53.989780 2018] [ssl:debug] [pid 128282] ssl_engine_io.c(1213): (70014)End of file found: [client 183.11.70.193:19265] AH02007: SSL handshake interrupted by system [Hint: Stop button pressed in browser?!] I'm looking for any help I can get troubleshooting this. Thanks in advance. More info... When I view the website in my browser, I'm presented with Django's Internal Server Error page, but the SSL certificate is correctly presented and trusted. I occasionally receive, "Truncated or oversized response headers received from daemon process" in my site error.log I'm using packages supplied by Debian for everything: libapache2-mod-wsgi/oldstable,now **4.3.0-1** amd64 [installed] apache2-bin/oldstable,now 2.4.10-10+deb8u11 amd64 [installed,automatic] python2.7/oldstable,now 2.7.9-2+deb8u1 amd64 [installed] The code works correctly with … -
How can I declare a Multiselectfield from a separate model on a Django form so that it can be processed as an editable form in HTML?
I was able to declare a nullbooleanfield using the following method, but my attempts at doing the same for Multiselectfield have not succeeded. Python code: def __init__(self, *args, **kwargs): super(EasementForm, self).__init__(*args, **kwargs) #if not self.instance: # self.fields['location'].initial = self.organizer.default_location for field in self.fields: if type(self.fields[field]) == type(self.fields['recreation_or_education']):#<class 'django.db.models.fields.NullBooleanField'>: self.fields[field].widget = forms.widgets.CheckboxInput(attrs={'onclick': 'return true;'}) if type(self.fields[field]) == type(self.fields['agricultural_construction']): #CheckboxSelectMultiple #self.max_length = kwargs.pop('max_length', None) #self.fields[field] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=construction_choices) #.widget = forms.widgets.CheckboxSelectMultiple() self.fields[field] = forms.MultipleChoiceField(widget=forms.SelectMultiple, choices=construction_choices) #forms.ModelChoiceField(queryset=Posts.objects.all(), empty_label="Choose a countries",) HTML: <div class="card"> <form method='POST' action=''>{% csrf_token %} {{form.as_table}} -
Django: How is a RelatedManager object instantiated?
Suppose I have two models: Book and Author. If I now added a ForeignKey field to Book connecting it to Author, and instantiated a Book object - then I also have access to that Book object through the Author object it is connected to (via .book_set, if no related_name specified). From what I have understood reading the documentation, this access is provided through a Related Manager object on the Author object. When is that RelatedManager-object created? Or is it already an object on each Author object, but gets connected to each Book object upon instantiation of a new Book? If so, how does it get connected to the Book object? This is not mentioned in the documentation to my knowledge. In the documentation: If a model has a ForeignKey, instances of the foreign-key model will have access to a Manager that returns all instances of the first model. -
Django Middleware that redirects to https
I'm trying to build some middleware in my Django project that redirects the user to a 'https' link if their request isn't initially to https. The code below is not redirecting the user under any of the tests that I've run (i.e. user enters 'www.example.com', 'http://example.com,', http://www.example.com', etc. Can any of you spot the problem with this code? Normally, I'd use print statements to see what the path is being set to, but I can't do that on my live server (or at least I don't know how to): from django.http import HttpResponseRedirect from django.utils.deprecation import MiddlewareMixin class RedirectMiddleware(MiddlewareMixin): def process_request(self, request): host = request.get_host() if host == 'www.example.com' or 'example.com': path = request.build_absolute_uri() domain_parts = path.split('.') if domain_parts[0] == 'http://www': path = path.replace("http://www","https://www") return HttpResponseRedirect(path) elif domain_parts[0] == 'www': path = path.replace("www","https://www") return HttpResponseRedirect(path) elif domain_parts[0] == 'http': path = path.replace("http","https") return HttpResponseRedirect(path) elif domain_parts[0] == 'example': path = path.replace("example","https://www.example") return HttpResponseRedirect(path) else: pass else: pass Thanks again guys -
Need Help Uploading django to Digital Ocean Droplet
I have all of my files in a folder on digitalocean, but I am currently getting stuck with a "No module named urls" Here is what my urls.py and views.py look like: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] views.py from django.shortcuts import render def index(request): return render(request, 'webapp/home.html') html pretty sure the only line that is wrong in it is <form class="form-signin" method="post" action="{% url 'Displayquest' %}"> -
KeyError 'image' formsets
It's my first time with formsets / images and this is my error: KeyError at /houses/new/ 'image' This is my code: models.py class House(models.Model): user = models.ForeignKey(User, related_name='houses', on_delete=models.CASCADE) address = models.CharField(max_length=500) type = models.CharField(default='House', max_length=100) stories = models.IntegerField() square_feet = models.IntegerField() description = models.TextField() # Class is for the houses images class Image(models.Model): house = models.ForeignKey(House, default=None, related_name="images", on_delete=models.CASCADE) image = models.ImageField(verbose_name='image') forms.py # This is the blueprint for House forms class AlbumForm(forms.ModelForm): address = forms.CharField(label="Address:") type = forms.CharField(label="Type of House (House, Condo, Cottage):") stories = forms.IntegerField(label="House Stories:") square_feet = forms.IntegerField(label='Square Feet:') class Meta: model = House fields = ['address', 'type', 'stories', 'square_feet', 'description'] # This is the form for images class ImageForm(forms.ModelForm): image = forms.ImageField(label='Image') class Meta: model = Image fields = ('image',) views.py def post_house(request): ImageFormSet = modelformset_factory(Image, form=ImageForm, extra=10) if request.method == 'POST': house_form = AlbumForm(request.POST) formset = ImageFormSet(request.POST, request.FILES, queryset=Image.objects.none()) if house_form.is_valid() and formset.is_valid(): post_form = house_form.save(commit=False) post_form.user = request.user post_form.save() for form in formset.cleaned_data: image = form['image'] photo = Image(house=post_form, image=image) photo.save() messages.success(request, "New house listing success") house = post_form return redirect('houses:details', house_id=house.pk) else: return render(request, 'login.html') else: house_form = AlbumForm() formset = ImageFormSet(queryset=Image.objects.none()) return render(request, 'houses/house_form.html', {'house_form': house_form, 'formset': formset}) house_form.html {% extends … -
I want to validate data of model in tests.py
I want to validate data of model in tests.py.I wrote codes in models.py, class UserData(models.Model): username = custom_fields.NotEmptyCharField(max_length=100, unique=True) email = models.EmailField() password = custom_fields.NotEmptyCharField(max_length=100) in tests.py class TestUserDataSet(TestCase): user = UserData() username = "john" email = "john@gmail.com" password = "john12" def test0(self): self.user.username = self.username self.user.email = self.email self.user.password = self.password #What should I write here? I wanna test if username&email&password have correct value,test codes does not cause any problem.I wanna write a codes like self.assertEquals,but how should I write it? -
Django is not seeing my MySQLdb module on CentOS 7 with mysqlclient installed and database working
I've seen many posts telling what is likely the problem, but I've been down each road. I have a database server and want to create a Django website to connect to it. I use mysql5.6 on the server, installed the community edition on both client and server. I followed the instructions on the django site: tested mysql, tested that django is installed, tested its version in python (2.0.3), tested python version (3.6), test connection to server from client with specified user to test database (ok, can select data at mysql> prompt). as root, have done pip install mysqlclient, have done yum install mysql-community-client, etc. I get to this point: $ cd /my/site/directory $ python manage.py newserver >Traceback (most recent call last): > File "/usr/lib/python3.6/site-packages/Django-2.0.3 py3.6.egg/django/db/backends/mysql/base.py", line 15, in <module> > import MySQLdb as Database > File "/usr/lib/python3.6/site-packages/MySQLdb/__init__.py", line 19, in <module> >import _mysql >ImportError: dynamic module does not define module export function (PyInit__mysql) >The above exception was the direct cause of the following exception: >Traceback (most recent call last): > File "manage.py", line 15, in <module> > execute_from_command_line(sys.argv) > File "/usr/lib/python3.6/site-packages/Django-2.0.3-py3.6.egg/django/core/management/__init__.py", line 371, in >execute_from_command_line utility.execute() > File "/usr/lib/python3.6/site-packages/Django-2.0.3-py3.6.egg/django/core/management/__init__.py", line 347, in execute django.setup() > File "/usr/lib/python3.6/site-packages/Django-2.0.3-py3.6.egg/django/__init__.py", line 24, in … -
Passing parameters through django url error
I have been trying to load my localhost:8000/streamers/1234 however there is a bug in my urls that I cannot seem to fix. Iv tried both patterns below and I keep getting the error: Django tried these URL patterns, in this order: ^streamers/(?P[0-9]+)/$ [name='streamer'] The current path, streamers/34/, didn't match any of these. urlpatterns = [ #path(r'^streamers/<int:id>/', views.streamer, name='streamer'), url(r'^streamers/(?P<id>[0-9]+)/$', views.streamer, name='streamer'), ] -
I would like to process them in Django with objects.raw (). When you call url from ajax, you get an error when trying to get processed results
InvalidQuery at /crms/cust/cust_popup/ Raw query must include the primary key An error occurs. How do you handle it? Request Method: POST Request URL: http://192.168.91.170:55555/crms/cust/cust_popup/ Django Version: 1.11.1 Python Executable: /home/sweetyxyz/dev/web/myvenv/bin/python Python Version: 3.4.3 my Source code is ..... models.py class Cu_00(models.Model): cu_code = models.CharField(primary_key=True, unique=True, max_length=50) cu_nm = models.CharField(db_index=True, max_length=100) cu_addr = models.CharField(max_length=200,null=True) cu_memo = models.TextField(max_length=2000,null=True) cu_comp_yn = models.CharField(max_length=2,null=True) cu_use_yn = models.CharField(max_length=2, null=True) cu_del_yn = models.CharField(max_length=2, default='N' ) createDate = models.DateTimeField(auto_now_add=True) def __str__(self): return self.cu_nm urls.py .... url(r'^cust/cust_popup/$' , views_cu.isCustData, name='isCustData' ) , ..... views.py def isCustData(req): if req.method == 'POST': cCust_nm = req.POST['cust_nm'] else: cCust_nm = req.GET.get['cust_nm'] cCust_nm = '%'+cCust_nm+'%' cDel_yn = 'N' cQuery = "select exists( select * from crmtotal_cu_00 where cu_nm like %s and cu_del_yn = %s )" events = Cu_00.objects.raw(cQuery, [cCust_nm, cDel_yn]) context = {} events = serializers.serialize('json', events) context['is_taken'] = events return JsonResponse(data=serializers.serialize('json', events)) html source code .... <script> $("#cust_nm").change(function(){ var cust_nm = $("#cust_nm").val() ; console.log(cust_nm) ; $.ajaxSetup({ data: {csrfmiddlewaretoken: '{{ csrf_token }}' }, }); $.ajax({ url: "{% url 'isCustData' %}", type : 'POST' , data: { 'cust_nm': cust_nm }, dataType: 'json', success: function (data) { if (data.is_taken) { alert("Cust Name is Found"); } } }); }) </script> -
Why table shows no data using a custom table template in django-tables2?
I am using django-tables to create a table from my model to display it on a page. I have created the folowing tables.py file: class OpenBetsTable(tables.Table): class Meta: model = Bet fields = ("date", "time", "competition", "home", "visitor", "bookie", "bet", "stake", "odds") attrs = {"class": "table table-striped table-sm table-bordered"} empty_text = "Nothing to display" I have a class-based view that contains the following: queryset = user_bets.filter(status__name="New").order_by("-timestamp") table = OpenBetsTable(queryset) RequestConfig(self.request, paginate={'per_page': 10}).configure(table) context["table"] = table In the page's template I have added {% load django_tables2 %} and {% render_table table %} to render the table. Everything works correctly until this point. I want to use a custom template for the table so I added template_name in OpenBetsTable, using one of the templates provided with django-tables2: class OpenBetsTable(tables.Table): class Meta: model = Bet template_name = "django_tables2/table.html" fields = ("date", "time", "competition", "home", "visitor", "bookie", "bet", "stake", "odds") attrs = {"class": "table table-striped table-sm table-bordered"} empty_text = "Nothing to display" Everything still works correctly. As a sidenote, there are a few ways to use a custom table template as shown in Is it possible to custom django-tables2 template for a specific page in this case?. Because I wanted to use my own … -
How do I mock a third party library inside a Django Rest Framework endpoint while testing?
The user creation endpoint in my app creates a firebase user (I have a chat room inside the app, powered by firebase) with the same id as my django user. from django.contrib.auth.models import User from rest_framework import generics from rest_framework import permissions from apps.core.services import firebase_chat class UserCreate(generics.GenericAPIView): permission_classes = [permissions.AllowAny] @transaction.atomic def put(self, request): user = User.objects.create(**request.data) firebase_chat.create_user(user) firebase_chat is a wrapper I created around the standard firebase library. I'm writing my tests like recommended in DRF's guide: from django.urls import reverse from django.test import TestCase from rest_framework.test import APIClient class UserCreateTest(TestCase): def test_user_create__all_valid__user_created(self): client = APIClient() client.force_authenticate(user=User.objects.create(username='test')) response = client.put(reverse('user-create')) self.assertTrue(response.data['something']) However, this leads to creating an actual user in Firebase. Not only this fails the test (the firebase library throws an exception), it also hits the actual firebase server, filling it with test data. How can I either mock or disable the firebase library during my tests? -
Django admin custom inline fails with "Please Correct the Error Below"
I have a model class where i am using the django admin and it has a few inline forms. I cannot save the change form for this model. It always complains with "Please correct the error below" even though there is no error highlighted on the page. I have narrowed it down to the inline that is causing problems: HorizontalInline When i remove this one everything works. Here are the relevant fields of my model: class Equipment(models.Model): name = models.CharField(max_length=14) description = models.CharField(max_length=100) class HorizontalInterface(models.Model): name = models.CharField(max_length=100, blank=True,) us_equip = models.ForeignKey(Equipment, related_name='upstream') ds_equip = models.ForeignKey(Equipment, related_name='downstream') Here are the relevant fields of my admin.py: class HorizontalInlineFormSet(BaseInlineFormSet): def __init__(self, *args, **kwargs): super(HorizontalInlineFormSet, self).__init__(*args, **kwargs) self.queryset = HorizontalInterface.objects.filter(Q(us_equip=self.instance) | Q(ds_equip=self.instance)) class HorizontalInline(admin.TabularInline): model = HorizontalInterface formset = HorizontalInlineFormSet show_change_link = True extra = 0 fk_name = 'us_equip' class EquipmentAdmin(admin.ModelAdmin): list_display = ('name', 'description') inlines = [ HorizontalInline ] I believe the complexity that it cannot handle is related to the fact that my horizontal interface model has two Equipment foreign keys and i would like to display all interfaces both upstream and downstream related to the equipment in question but also be able to edit them and save the equipment. Any … -
Filling a text area element with specific data from Django Models
I have a system with channels which is a chat client. I have currently two models Room and Message and I have all the outgoing messages from the channels saving themselves to the Message DB which looks like this: id | handle | message | timestamp | room_id ----+--------+-----------------------------+-------------------------------+--------- 1 | Finlay | Hello | 2018-03-27 21:39:50.0062+00 | 12 2 | Finlay | Hi! | 2018-03-27 21:56:41.355652+00 | 12 3 | Finlay | Hello! | 2018-03-27 21:57:04.8768+00 | 11 4 | Finlay | I am using Django Live Chat | 2018-03-27 21:57:25.931886+00 | 11 And Room which looks like: id | name | uniquelab ----+------+----------- 10 | | Hello 11 | | Test 12 | | New How can I fill a text area on one of my templates which with all the messages with, say room id=12, and have them come up in chronological order. Please ask for any further code or Database structures as I am happy to give them. Thank you. -
DJANGO 2.0 Displaying Data from the database
i am new to django and i am unable to get to print to the html page.How do you display the information retrieved from the database into a blank html page? blank.hml <body> <h1>Classes Added</h1> {% for i in classInfo %} <h1>{{ i.username }}</h1> {% endfor %} </body> models.py class EventType(models.Model): ''' Simple ``Event`` classifcation. ''' objects = models.Manager() abbr = models.CharField(_('abbreviation'), max_length=4, unique=False) label = models.CharField(_('label'), max_length=50) class Meta: verbose_name = _('event type') verbose_name_plural = _('event types') def __str__(self): return self.label views.py def displayClass(TemplateView): templateName = 'blank.html' def get(self,request): form = ClassCreationForm() classInfo = EventType.objects.all() print(classInfo) args = {'form' : form, 'classInfo' : classInfo} return render(request,self,templateName,{'form':form}) forms.py class ClassCreationForm(forms.Form): classroom = forms.CharField(label = 'Class Name',max_length=50)