Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to convert it to django 2.1
How is the new syntax in version 2.1? -
Django FileNotFound Error after Deployment on GCE
I'm working on a Django 2 project in which I have an img folder inside my root directory and I'm saving some images into this folder then create a zip archive from this folder and send to the browser. It was working fine on my local system but when I have deployed it on a Liux Instance on Google Compute Engine using Gunicorn, it returns an error for this repository. Here's my views.py class PerformImgSegmentation(generics.ListAPIView): def get(self, request, *args, **kwargs): img_url = self.kwargs.get('encoded_url') print(img_url) print('get request') def create_pascal_label_colormap(): colormap = np.zeros((256, 3), dtype=int) ind = np.arange(256, dtype=int) for shift in reversed(range(8)): for channel in range(3): colormap[:, channel] |= ((ind >> channel) & 1) << shift ind >>= 3 return colormap def label_to_color_image(label): if label.ndim != 2: raise ValueError('Expect 2-D input label') colormap = create_pascal_label_colormap() if np.max(label) >= len(colormap): raise ValueError('label value too large.') return colormap[label] def vis_segmentation(image, seg_map): seg_image = label_to_color_image(seg_map).astype(np.uint8) # BasicSource Modification in the original Image for segmentation imgOrigin = cv2.imread('originImage.png') seg_image_gray = cv2.cvtColor(seg_image, cv2.COLOR_BGR2GRAY) (thresh, im_bw) = cv2.threshold(seg_image_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) # Creating the Mask of the Image via Segmentation Map cv2.imwrite('MaskedImage.png', seg_image) maskedImage = cv2.bitwise_and(imgOrigin, imgOrigin, mask=im_bw) # Generating the transparent image on the … -
Consuming webservice from multiple sources and save to Db
I am building an application in django that collects hotel information from various sources and format this data to a uniform format. There after I need to expose API to allow hotels access to web apps and devices using django-rest-framework. So For example if I have 4 sources [HotelPlus, xHotelService, HotelSignup, HotelSource] So please let me know the best implementation practice in terms of django. Being a PHP developer, I prefer to do this by writing a custom third party services implementing an interface so adding more sources becomes easy. That way I only need to call execute() method from the cron task and rest is done by the service controller (fetching feed and populating it in database). But I am new to python django, so I dont have much idea of creating services or middleware is a right fit for this task. -
Django aggreagate Many Fields
Hello I want to aggregate all comments in my article and select only 2 of this comment not all comments and put back in article var from django.shortcuts import render_to_response from django.db.models import BooleanField, Count, OuterRef, Subquery from ..models import Article, Like, Bookmark, Comment def feed(request): context = {} articles = Article.objects.all()[:5].select_related('user__profil')\ .prefetch_related('comments__user__profil', 'hashtags')\ .annotate(like_count=Count("likes__sum_rating()"), \ liked=Subquery(Like.objects.filter(user=request.user, content_type=7, object_id=OuterRef('pk')).annotate(cnt=Count('pk')).values('cnt'), output_field=BooleanField()), bookmarked=Subquery(Bookmark.objects.filter(user=request.user, article=OuterRef('pk')).annotate(cnt=Count('pk')).values('cnt'), output_field=BooleanField()), ) ## Here my try articles.comments = articles.values_list('comments').annotate( izi=Count("comments__likes__sum_rating()") ) context['activate'] = "feed" context['articles'] = articles return render_to_response(template_name='feed.html', context=context) -
Django, Store jpg file received as string in http POST
I am receiving an http request from a desktop application with a screenshot. I cannot speak with the developer or see source code, so all I have is the http request I am getting. The file isn't in request.FILES, it is in request.POST. @csrf_exempt def create_contract_event_handler(request, contract_id, event_type): keyboard_events_count = request.POST.get('keyboard_events_count') mouse_events_count = request.POST.get('mouse_events_count') screenshot_file = request.POST.get('screenshot_file') barr2 = bytes(screenshot_file.encode(encoding='utf8')) with open('.test/output.jpeg', 'wb') as f: f.write(barr2) f.close() The file is corrupted. The binary starts like this, I don't know if that helps: ����JFIFHH��C %# , #&')*)-0-(0%()(��C (((((((((((((((((((((((((((((((((((((((((((((((((((�� `"�� Also, if I try to open the image with PIL, I get the following error: from PIL import Image im = Image.open('./test/output.jpg') #OSError: cannot identify image file './test/output.jpg' -
Django wait to finish Selenium def() then returns the page - how to change that?
For practice I have written bot using Selenium for Instagram to do some stuff automatically and now for more practice I would like to create simple web page with which my bot can be controlled(like start/stop and some options) I have written basic code in Django, it works but ... Generally when def runInstabot(request) starts it waits until Selenium functions(bot.login() and bot.search()) finish and then it returns the page. How to make that it will return the page and at the same time Selenium functions will work or even better first it will return the page and then selenium script starts ? i.e. to be more precise: I would like to input some data(for now login and password but later few more) then it will render for next page and at the same time/or next bot.login() and bot.search() starts views.py: from django.shortcuts import render from django.shortcuts import HttpResponse from django.http import HttpResponseRedirect from bott.forms import LoginInstagramForm from django.views.generic.edit import FormView from instagram.bot import Instagram bot = Instagram() class InstabotView(FormView): template_name = 'instabot.html' form_class = LoginInstagramForm success_url = '/runinstabot/' def form_valid(self,form): form.clean_instagram() return super().form_valid(form) def runInstabot(request): print('Welcome here') if request.method == 'POST': runInstabot.login = request.POST.get('login') runInstabot.password = request.POST.get('password') form = LoginInstagramForm(request.POST … -
Django CSV Export Choice Display
I have a working CSV export function in my Django app. It exports all fields but doesn't show the verbose or human readable version of the model choice fields. I am aware of the get_field_display option for templates and views but based on the use of getattr in this function I don't know where to add that bit of code. See code below writer = csv.writer(response) field_names = [f.name for f in model._meta.fields] for instance in queryset: writer.writerow([unicode(getattr(instance, f)).encode('utf-8') for f in field_names]) return response Where can I inject a bit of code to export the full version of model choices. Thanks -
Django Inherited Model: "Cannot resolve keyword 'keyword' into field." (Django 2.1.1)
guys. Same Context Processor, new problem (linked to this question). I have the following model to check for promotions on a website: class PagePromotion(LinkedPromotion): """ A promotion embedded on a particular page. """ page_url = URLField(max_length=128, min_length=0) def __str__(self): return "%s on %s" % (self.content_object, self.page_url) def get_link(self): return reverse('promotions:page-click', kwargs={'page_promotion_id': self.id}) class Meta(LinkedPromotion.Meta): verbose_name = _("Page Promotion") verbose_name_plural = _("Page Promotions") That is inherited from this model: class LinkedPromotion(models.Model): # We use generic foreign key to link to a promotion model content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = fields.GenericForeignKey('content_type', 'object_id') position = models.CharField(_("Position"), max_length=100, help_text="Position on page") display_order = models.PositiveIntegerField(_("Display Order"), default=0) clicks = models.PositiveIntegerField(_("Clicks"), default=0) date_created = models.DateTimeField(_("Date Created"), auto_now_add=True) class Meta: abstract = True app_label = 'promotions' ordering = ['-clicks'] verbose_name = _("Linked Promotion") verbose_name_plural = _("Linked Promotions") def record_click(self): self.clicks += 1 self.save() record_click.alters_data = True On my context processor related to this pages, i've writen a code to request page promotions like this: def get_request_promotions(request): """ Return promotions relevant to this request """ promotions = PagePromotion.objects.filter(page_url=request.path).order_by('display_order') if 'q' in request.GET: keyword_promotions \ = KeywordPromotion.objects.select_related().filter(keyword=request.GET['q']) if keyword_promotions.exists(): promotions = list(chain(promotions, keyword_promotions)) return promotions At first it was like the linked version, but i've tried … -
Syntax Error in urls.py path upgrading to Django 2.1
While manually upgrading to Django 2.1, I have Syntax Error in urls.py. I have removed regex characters the error persists. What's wrong? I have checked that that I didn't miss , or braces, but still no idea what is causing the error. from django.conf.urls import url from django.contrib.auth import views as auth_views from django.views.generic.base import RedirectView from django.conf import settings from django.conf.urls.static import static import app.forms import app.views from django.urls import include,path from django.contrib import admin admin.autodiscover() urlpatterns = [ path('', app.views.gallery, name='gallery'), path('favicon\.ico', RedirectView.as_view(url='/static/icons/favicon.ico', permanent=True)), path('<slug:album_slug>', app.views.AlbumDetail.as_view(), name='album'), #app.views.AlbumView.as_view() # Auth related urls path('accounts/login/', auth_views.LoginView.as_view(template_name='registration\login.html'), name='login'), path('logout', auth_views.LogOutView.as_view(next_page,template_name='registration\logged_out.html', name='logout'), # Uncomment the next line to enable the admin: path('admin/', admin.site.urls), # Uncomment the admin/doc line below to enable admin documentation: path('admin/doc/', include('django.contrib.admindocs.urls')), ] +static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) handler404 = 'app.views.handler404' Error trace: (Django11) C:\Users\Kaleab\Desktop\Photo_Gallery\django-photo-gallery\django_pho to_gallery>py -3.7 manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000000D918D0E268> Traceback (most recent call last): File "C:\Python37\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Python37\lib\site-packages\django\core\management\commands\runserver. py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Python37\lib\site-packages\django\core\management\base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "C:\Python37\lib\site-packages\django\core\management\base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "C:\Python37\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python37\lib\site-packages\django\core\checks\urls.py", line 40, in … -
New features for school management [on hold]
I am going to make a school management system as a final year project I know its classic system but I want to implement some unique features in it. please give me some suggestions. -
Django / Google Cloud: FATAL: database <db> does not exist / Server Error 500
i have a django app that runs fine locally but throws a server error 500 when i deploy it to google cloud it's telling me the database does not exist. (it does.) { insertId: "s=81237568d9204e6081d81087faf41900;i=162cc;b=0ca68bbe363d49a581ec4e2fc6c45487;m=799aa9bfc;t=57529446a6708;x=4f176b686e1cb7ce-0@a1" logName: "projects/rcg-live/logs/cloudsql.googleapis.com%2Fpostgres.log" receiveTimestamp: "2018-09-06T00:49:51.309738251Z" resource: {…} severity: "ALERT" textPayload: "FATAL: database "rcg-live-db" does not exist" timestamp: "2018-09-06T00:49:45.486088Z" } i get the same error when i try to connect the local app with cloud sql proxy tool: Traceback (most recent call last): File "/anaconda3/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/anaconda3/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/anaconda3/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 174, in get_new_connection connection = Database.connect(**conn_params) File "/anaconda3/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: database "rcg-live-db" does not exist i'm not really sure what i can put here to show that a postgres database called 'rcg-live-db' exists on my cloud, so i guess take my word for it. again, everything works locally, including the admin page. all 500 errors when i try to use the remote db. -
Django celery accepts tasks but doesn't process it
I'm using celery to run background tasks in my django project. The user-facing part (django-gunicorn-nginx) is running in one server. RabbitMQ is running in another server (to which the first server is pushing background tasks). and a third server(with the same codebase as the first one) is executing these tasks using celery. My problem is that the celery is receiving the tasks from the rabbitMQ, but it is not getting executed. celery related library versions : amqp==1.4.9 celery==3.1.26.post2 django-celery==3.2.2 kombu==3.0.37 I'm running celery using this command: celery worker -A proj --loglevel=DEBUG --concurrency=4 -n worker1@%%h sudo rabbitmqctl list_connections is listing the connections as running Any pointers on where to look? -
Reverse Foreign Key Lookup
#models.py class Orders(models.Model): orderid = models.IntegerField(db_column='orderID', primary_key=True) createdate = models.DateField(db_column='createDate', blank=True, null=True) pickupdate = models.DateField(db_column='pickupDate', blank=True, null=True) returndate = models.DateField(db_column='returnDate', blank=True, null=True) pickupstore = models.ForeignKey(Branch, models.DO_NOTHING, db_column='pickupStore', blank=True, null=True,related_name = 'pickupstore') returnstore = models.ForeignKey(Branch, models.DO_NOTHING, db_column='returnStore', blank=True, null=True,related_name = 'returnstore') rentedvehicle = models.ForeignKey('Vehicles', models.DO_NOTHING, db_column='rentedVehicle', blank=True, null=True) customer = models.ForeignKey(Customer, models.DO_NOTHING, db_column='customer', blank=True, null=True) class Vehicles(models.Model): vehicleid = models.IntegerField(db_column='vehicleID', primary_key=True) make = models.CharField(max_length=45, blank=True, null=True) model = models.CharField(max_length=45, blank=True, null=True) series = models.CharField(max_length=45, blank=True, null=True) #views.py def topcar(request): topCar = Vehicles.objects.filter(orders__pickupstore__state = request.POST['state']).annotate(num_car =Count('orders')).order_by('-num_car')[:20] return render(request, 'web/topcar.html',{'topCar':topCar, 'state':request.POST['state']) #topcar.html {% for car in topCar %} <tr> <td>{{car.make}} {{car.model}} {{car.series}} {{car.year}}</td> <td>{{car.seatcapacity}}</td> <td>{{the latest car return store}}</td> </tr> {% endfor %} In views.py, topCar variable is the list of top 20 vehicles (in Vehicles model) that have high orders in Orders model.The field rentedvehicle in Orders model is foreign key refers to Vehicles model. I want to get the latest returnstore (a field in Orders model) for each car in topCar variable. I want it to be displayed in {{the latest car return store}} in topCar.html How should I do that? I find out that I can do this : Orders.objects.filter(rentedvehicle = car.vehicleid).latest('returndate').returnstore to get the latest returnstore for a vehicleid. … -
Queries in query set group in to one query using Django
I have a query set like the below. <QuerySet[{'user':'xyz','id':12,'home':'qwe','mobile':1234}, {'user':'xyz','id':12,'home':'qwe','mobile':4321}, {'user':'abc','id':13,'home':'def','mobile':1233}, {'user':'abc','id':13,'home':'def','mobile':1555},]> This QuerySet is returned by django using users.objects.all() For Each query in the query set, I'm drawing a user table which shows the details of users. If the same user registers with two mobile numbers, it is showed as two rows in the table instead of one. My goal is to distable two numbers in the same row instead of creating two rows. I have thought of two possible solutions which are below: Solution 1: I have thought of merging the two queries into one if the 'user' value matches in both the queries. For this we need to make lot of checks using conditional statements which works slowly when lot of users are there. Solution 2: I have searched on Google and came up with Group By Django, but it is not working. I have tried below query = users.objects.all().query query.group_by = ['mobile'] results = QuerySet(query=query, model=users) Please provide a way so that two queries can be clubbed into one based on 'user' and after clubbing 'mobile' should contain two values. -
Django saving modelformset_factory
When saving the formset, it is not validating and respecting the model fields that I have made unique and therefore renders an Integrity Error should I duplicate fields deliberately to test it. Is there something I am missing please? My code: class ClientCreate(LoginRequiredMixin, FormView): def dispatch(self, *args, **kwargs): self.case = Case.objects.get(pk=kwargs['case_pk']) self.num_clients = self.case.number_clients return super().dispatch(*args, **kwargs) template_name = 'clients/client_form.html' form_class = modelformset_factory(Client, ClientForm, min_num=2, max_num=2, extra=0, validate_max=True, validate_min=True, can_delete=False) def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["queryset"] = Client.objects.none() return kwargs def form_valid(self, form_class): form_class.save() return super().form_valid(form) def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) if self.request.POST: ctx['inlines'] = self.form_class(self.request.POST) else: ctx['inlines'] = self.form_class() return ctx def get_success_url(self): return reverse('client-list', kwargs={'case_pk': self.kwargs['case_pk']}) I appreciate that formview is really supposed to be used for single form saving, but this does actually work correctly when not having duplicate unique items. Many thanks -
How to log exceptions and errors into a file when using a Django stand alone script
I have created a stand alone script in Django, but although the logging seems to be correctly configured, it fails to log the stderr and stdout data into a Django log file. I am using Python 3.6 with Django 2.1. The content of the Django script my_script.py: import os import django import logging os.environ['DJANGO_SETTINGS_MODULE'] = 'my_project.settings' django.setup() logger = logging.getLogger('my_script') def main(): logger.debug('This message is logged') raise Exception('Exceptions or errors (stderr) are NOT logged!') if __name__ == "__main__": main() My logging configuration in my_project/settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'my_scrip_file': { 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename': 'logs/my_script.log', 'maxBytes': 1024*1024*5, # 5 MB 'backupCount': 5, 'formatter':'verbose', }, }, 'loggers': { 'my_script': { 'handlers': ['my_scrip_file'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), 'propagate': True }, }, } Does somebody know how to get the stderr messages stored into the log file? -
How do I import an old version of a Django fixture and update it?
I am trying to import a fixture from a previous version of my app. One of the fields in the fixture was changed from a CharField to a ForeignKey and renamed. My plan was to manually run the migrations so that the new version is at the same level as the old version and then finish the migrations to update the data to the new version. I was able to get the migrations to the correct level, but when I try to run ./manage.py loaddata fixture.json, I am told that the old field doesn't exist and Django won't import the fixture. How can I import this fixture and use Django to update it? -
Django modify blank form field sent to template
Here I am again with my daft questions.. I'm creating a blank form but just want the Username field to be filled automatically. should be simple, right? views.py #blank form wswEditUser is the form model in forms.py form = wswEditUser() form.fields["Username"].value = someuser return render(request, 'wswEdit.html', {'form': form }) but instead, the Username input box on the form is still blank am i stupid ? -
Is there a way to collect media files?
I'm trying to switch managing static files and media files from local folder to AWS S3. I was successful collecting static files by python manage.py collectstatic. But I want to collect media files as well. How can I do it? The project structure is like this: project | |___apps | |___config Inside apps folder, there are static folder and media folder. And inside config folder, there's storage_backends.py The configuration is like this: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(APPS_DIR, 'media') STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_DIRS = ( os.path.join(APPS_DIR, 'static'), ) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'config.storage_backends.MediaStorage' -
Django mongo db filter query is not returning any data
When I am trying om = OttMessage.objects.filter() its returning all the documents in the ott_message collections. But when I am trying om = OttMessage.objects.filter(prediction_status = -1) its not returning any data. There are many documents in the ott_message collection having prediction_status field -1 For example { "classification" : null, "message_from" : "XXXXXXXX", "id" : "5b61d4649cdae332bf9151f9", "is_classified" : false, "prediction_status" : -1, "post_disposition" : null, "message" : "XXXXXXXXXXXXXXXXXXXXXX", "channel" : 1, "message_date" : "2018-08-01T15:42:30", "group_name" : "Resale Gurgaon req IC", "req_disposition" : null, "manual_tagged_status" : -1 }, { "prediction_status" : -1, "is_classified" : false, "classification" : null, "message_from" : "XXXXXXXXXXXXX", "id" : "5b61da629cdae343169150cf", "manual_tagged_status" : -1, "req_disposition" : null, "message" : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "post_disposition" : null, "message_date" : "2018-08-01T15:50:19", "group_name" : "XXXXXXXXXXXXXXX", "channel" : 1 } Can anybody tell me where its going wrong ? Thanks -
How to implement hot-reloading in Django+React+Webpack app
There is some way to implement hot-reloading in an app with Django + React, other than the django-webpack-loader -
Configuring django filebrowser
In order to upload images or other media files through admin I installed filebrowser. Moreover I need filebrowser for the Tinymce. But I am having the following problem. By the way I installed filebrowser without grapelli. settings.py: STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") SITE_ROOT = os.path.realpath(os.path.dirname(__file__)) MEDIA_ROOT = os.path.join(SITE_ROOT, "media_cdn") STATICFILES_DIRS =[ os.path.join(BASE_DIR, "static"), ] and the url.py is the following: from django.conf import settings from django.conf.urls.static import static from filebrowser.sites import site urlpatterns = [ path('admin/', admin.site.urls), path('admin/filebrowser/', site.urls), path('tinymce/', include('tinymce.urls')), path('', views.home, name='home'), path('products/', include('insuranceProducts.urls', namespace='insurance')), path('about_us/', include('aboutUs.urls', namespace='about_us')), path('paparazzi/', include('paparazzi.urls', namespace='paparazzi')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) Besides I am using Django 2.0 and django-tinymce4-lite -
Python model.objects.filter return multiple of the same object
I was following this guide, about django search. https://medium.com/@pauloxnet/full-text-search-in-django-with-postgresql-4e3584dee4ae search_value = request.query_params['searchvalue'] documents = Document.objects.filter( raw_text__icontains=search_value ).values_list('doc_id', flat=True) return documents This gets a list of document id's based on a search value. But in some of the document objects the raw_text textfield include the search_value more than once. But I still only get the doc_id once. Is there a way to get the doc_id for every hit in the filter? -
Populate Specific Database With factory_boy Data for testing
I have an application that has some unmanaged models that pull from a table in a different DB. I've created Factories for all my models and in most cases factory_boy has worked great! The problem I'm running into has to do with a specific unmanaged model that uses a manager on one of the fields. class DailyRoll(StaffModel): id = models.IntegerField(db_column='ID', primary_key=True) location_id = models.IntegerField(db_column='locationID') grade = models.CharField(db_column='grade', max_length=10) end_year = models.IntegerField(db_column='endYear') run_date = models.DateField(db_column='runDate') person_count = models.IntegerField(db_column='personCount') contained_count = models.IntegerField(db_column='containedCount') double_count = models.IntegerField(db_column='doubleCount') aide_count = models.IntegerField(db_column='aideCount') one_count = models.IntegerField(db_column='oneCount') bi_count = models.IntegerField(db_column='biCount') last_run_date = managers.DailyRollManager() class Meta(object): managed = False db_table = '[DATA].[position_dailyRoll]' The manager looks like this: class DailyRollManager(models.Manager): def get_queryset(self): last_run_date = super().get_queryset().using('staff').last().run_date return super().get_queryset().using('staff').filter( run_date=last_run_date ) My factory_boy setup looks like this (it's very basic at the moment, because I'm just trying to get it to work): class DailyRollFactory(factory.Factory): class Meta: model = staff.DailyRoll id = 1 location_id = 1 grade = 1 end_year = 2019 run_date = factory.fuzzy.FuzzyDateTime(timezone.now()) person_count = 210 contained_count = 1 double_count = 2 aide_count = 3 one_count = 4 bi_count = 5 last_run_date = managers.DailyRollManager() I'm sure the last_run_date is setup improperly - but I don't know how best to handle using … -
Implementing json requests in django url
I am learning django, and currently trying to make an api for an android app. Suppose the app calls for a 'Register User' url, and passes a json object as the parameters for registering, how am I supposed to receive the object in my url and use it in my view function?