Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What's the issue this log is indicating?
I have a Python/Django/Wagtail project running in Heroku. We just pushed a big change, but then we get a Application Error, supposedly an issue somewhere in the code. The app works fine locally. This issue happens when pushing Heroku. So I check the logs, it is not saying exactly what the issue is, just indicating a list of files. It starts like this: from wagtail.wagtailadmin.edit_handlers import ( app_config = apps.get_containing_app_config(module) worker.init_process() return util.import_app(self.app_uri) from imports import * The logs are actually longer, but I think that's the important part. The file and line it lists looks partially like this: from wagtail.wagtailadmin.edit_handlers import ( FieldPanel, FieldRowPanel, InlinePanel, MultiFieldPanel, PageChooserPanel, StreamFieldPanel ) So, what is Heroku complaining about? Why is it so obscure about the issue here? Dependencies seem not to be the problem, I already tested that. -
JSON Material UI Select DropDown
I cannot get a material ui Drop down to populate with JSON Data. Can someone see what I'm doing wrong? Here is the code that has the JSON and the code itself. ` const json = { ResponseMetadata: { RequestId: "1B29B45E145594A7", HostId: "fNB6fQZ8LQrK53j9lIOMSKy49mA8xrAMiwVh05/fKcBB5/gjYF6qUdxLFw4/zR5mRNHg2ge6t3w=", HTTPStatusCode: 200, HTTPHeaders: { "x-amz-id-2": "fNB6fQZ8LQrK53j9lIOMSKy49mA8xrAMiwVh05/fKcBB5/gjYF6qUdxLFw4/zR5mRNHg2ge6t3w=", "x-amz-request-id": "1B29B45E145594A7", date: "Sun, 13 May 2018 20:36:02 GMT", "content-type": "application/xml", "transfer-encoding": "chunked", server: "AmazonS3" }, RetryAttempts: 0 }, Buckets: [ { Name: "eladft-1-653237860766", CreationDate: "2014-09-01T16:58:41Z" }, { Name: "elasticdf37860766", CreationDate: "2015-10-06T00:24:57Z" }, { Name: "elasticdf0766", CreationDate: "2015-10-02T17:37:19Z" } ], Owner: { DisplayName: "dfdf", ID: "b4bf8bde7571756284e067071dfe442c7b014a09f012a1179" } }; ` <form className={classes.root} autoComplete="off"> <FormControl className={classes.formControl}> <InputLabel htmlFor="bucketName-simple">Buckets</InputLabel> <Select native="true" value={this.state.json.Buckets.Name} onChange={this.handleChange} inputProps={{ name: "v_bucketName", id: "age-simple" }} > {this.state.json.Buckets.map((Buckets, i) => ( <MenuItem native="true" key={i} value={Buckets.Name}> {Buckets.Name} </MenuItem> ))} )} </Select> </FormControl> </form> ); } } The data from AWS S3. But this is using Material-UI and React JS Code Sanbox -
How to mock super method in Django from multiple level deep mixin
I am working on some simple Unit Tests in Django==1.11 and python==2.7.12. All of the similar tests the execution time of the test is around 0.0040 seconds, for example the custom suspend action which is included with test at the bottom of the post. All of the used classes, forms, called functions are mocked in all tests. Though, the test of the unsuspend action consumes 10 times as much time to execute with an average of 0.0400 seconds which I do not understand why, since it is even a simpler then the suspend action. # The custom unsuspend DRF action being tested @action(methods=['get'], detail=True, permission_classes=[OrganizationBasePermissions]) def unsuspend(self, request, uuid): organization = self.get_object() start = datetime.datetime.now() mc_organization.services.organization.unsuspend(organization=organization) end = datetime.datetime.now() print('service call duration:', end - start) # ('service call duration:', datetime.timedelta(0, 0, 143)) serializer = self.get_serializer(instance=organization) return Response(data=serializer.data, status=status.HTTP_200_OK) # The unittest of the unsuspend action above @mock.patch('mc_organization.api.viewsets.organization.Response') @mock.patch('mc_organization.api.viewsets.organization.ModelViewSet.get_serializer') @mock.patch('mc_organization.api.viewsets.organization.' 'mc_organization.services.organization.unsuspend') @mock.patch('mc_organization.api.viewsets.organization.ModelViewSet.get_object') def test_viewset_unsuspend_action(self, get_object_mock, unsuspend_service_mock, get_serializer_mock, response_mock): get_object_mock.return_value = self.organization get_serializer_mock.return_value = self.serialized_organization self.viewset.unsuspend(request=self.request, uuid=self.organization.uuid) self.assertEqual(get_object_mock.call_count, 1) unsuspend_service_mock.assert_called_once_with(organization=self.organization) get_serializer_mock.assert_called_once_with(instance=self.organization) response_mock.assert_called_once_with(data=self.serialized_organization.data, status=status.HTTP_200_OK) When printing the called methods to see if they are properly mocked, the results show the expected mocked values: print('mocked get object?:', self.get_object()) print('mocked service?:', mc_organization.services.organization.unsuspend) print('mocked get_serializer?:', self.get_serializer()) … -
Issue with Django, Apache, mod_wsgi, and caching CSS files
Alright, so I've got a setup which consists of Apache 2.4, Django 2.0.5, Python3.5, mod_wsgi, all running on Debian. When I go to edit a CSS file on my production server, the file doesn't update until I entirely reboot the server it's on. As you can imagine this is tedious and time consuming, so I'd like to find a solution. Here are some config files: Apache configuration: <IfModule mod_ssl.c> <VirtualHost *:80> ServerName 7aptget.com Redirect permanent / https://7aptget.com/ </VirtualHost> <VirtualHost _default_:443> RewriteEngine On RewriteCond %{SERVER_PORT} !^443$ ServerAdmin w@w.com ServerName 7aptget.com ServerAlias 7aptget.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined SSLEngine on SSLCertificateFile /etc/letsencrypt/live/7aptget.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/7aptget.com/privkey.pem <FilesMatch "\.(cgi|shtml|phtml|php)$"> SSLOptions +StdEnvVars </FilesMatch> <Directory /usr/lib/cgi-bin> SSLOptions +StdEnvVars </Directory> BrowserMatch "MSIE [2-6]" \ nokeepalive ssl-unclean-shutdown \ downgrade-1.0 force-response-1.0 BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown\ LoadModule wsgi_module "/home/kaden/development/websites/homepage/env/lib/python3.5/site-packages/mod_wsgi/server/mod_wsgi-py35.cpython-35m-x86_64-linux-gnu.so" #Django Application Alias /media /home/kaden/development/websites/homepage/media Alias /static /home/kaden/development/websites/homepage/static <Directory /home/kaden/development/websites/homepage/media> Require all granted </Directory> <Directory /home/kaden/development/websites/homepage/static> Require all granted </Directory> <Directory /home/kaden/development/websites/homepage/website> <Files wsgi.py> Require all granted </Files> </Directory> LogLevel info WSGIDaemonProcess 7aptget.com python-path=/home/kaden/development/websites/homepage python-home=/home/kaden/development/websites/homepage/env WSGIProcessGroup 7aptget.com WSGIScriptAlias / /home/kaden/development/websites/homepage/website/wsgi.py </VirtualHost> Django wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "website.settings") application = get_wsgi_application() Django settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # … -
Changing postgres password for enduser
is it possible to change an encrypted password with a sql query? I have a user who for some reason can't log in and can't make her reset password recredentialing work. -
Best way to set cookies in a Django view?
I'm working on modifying a Django view that is similar to the following: class ListBase(DashboardAccessMixin, OrderingMixin, FilterMixin, SearchMixin): def get(self, request, *args, **kwargs): if should_delete_filter_cookie(request, path=reverse('dashboard:families')): request.COOKIES.pop('filters', None) self.query_dict = query_dict_from_params_or_cookies(request) return super().get(request, *args, **kwargs) def render_to_response(self, context, **response_kwargs): response = super().render_to_response(context, **response_kwargs) path = reverse('dashboard:families') if should_delete_filter_cookie(self.request, path=path): response.delete_cookie('filters', path=path) elif list(self.request.GET.items()): response.set_cookie('filters', self.request.GET.urlencode(), path=path) return response where the auxiliary functions should_delete_filter_cookie and query_dict_from_params_or_cookies are defined as def query_dict_from_params_or_cookies(request): query_dict = request.GET cookie_filters = request.COOKIES.get('filters') if cookie_filters and not list(query_dict.items()): query_dict = QueryDict(cookie_filters) return query_dict def should_delete_filter_cookie(request, path): referer_path = urlparse(request.META.get('HTTP_REFERER')).path if referer_path and path not in referer_path: return True else: return False The view has a filter_form and a search_form (through the corresponding mixins) which are bound with self.query_dict. Further, we follow the naming convention that the URLs for the UpdateView and CreateView are simply 'extensions' of that for the ListView's URL: for example, the former is /dashboard/families and the latter is simply dashboard/families/1 (but not dashboard/family/1). The ListView is now such that when you return to it from an UpdateView, it persists the filters that were previously applied by getting the self.query_dict from the cookies. What I'm wondering is why should_delete_filter_cookie is invoked twice, in the get() … -
How to use regular expression to match a string include transverse line?
I want to use dynamic url in Django to match my dynamic href in template, which is assembled from addresses, such as below: ../details/0-TIFFANY-CRES ../details/1-Airport-PKY I am a layman of regular expression, the current url I want to match is : path('details/[-\w]', details), it didn't work(of course). In addition, I want to use the address in the urls in my views, how can I convert this address to my new views function? How can I match the urls? If there is any unclear parts, please tell me and I will try to explain more. -
POST to more than one view with two buttons?
I'm a beginner developer and i'm struggling to get my form(s) to POST partially the same information to two different locations. I'm looking to POST the user information in this first form to an additional view called update and then POST the user information and the remaining information to another view called Submitted. My second submit button is working correctly, it's the first input button that i'm having trouble with. It's just posting to the submitted view instead of update. I have two different buttons in my form. The one with only the user information is defined as: <button type="input" class="btn btn-primary"> <span class="glyphicon glyphicon-edit"></span> Update </button> Then second for the submit is: <button class="btn btn-primary my_select" type="submit">Request Access</button> My entire code set is the following: {% extends 'base.html' %} {% load static %} {% block head %} <title> Profile </title> {% endblock %} {% block content %} <form action = "{% url 'submitted' %}" form method = "POST"> <form action = "{% url 'update' %}" form method = "POST"> {% csrf_token %} <div class="well"> <h4 style="margin-top: 0"><strong> User Details </strong></h4> <div class="row"> <div class="form-group col-md-4"> <label/> 3-4 User ID <input class="form-control" type="text" name = "userpost" value= "{{employee.employeentname}}" readonly> </div> … -
How to handle DenyConnection error raised by Django Channels in frontend
Is there a way I can deny a websocket connection in Django Channels and let the frontend know why the connection was refused. The channels documentation mention the channels.exceptions.DenyConnection error. When I raise it, I get a 1006 close event in the frontend, which is an abnormal closure and could be raised in other circumstances, I guess. I am looking for a way to indicate that the connection was refused. -
Creating a "simple" dictionary in a Django model?
Apologies for the vague title, but I'm really having trouble describing this concept. Basically what I want is to import some json data I've created into some Django models. My data looks like this, basically: [ { name: "Bingfordshire" results: { 'LIB' : 23, 'PC': 25 }, more dictionaries here.... }, more objects here.... ] I've setup a model for the the outer object, but I'm struggling with how to represent those interior dictionaries. My first idea was to just use fields like this: class Riding: lib_result = models.DecimalField() pc_result = models.DecimalField() But I have three such dictionaries and about 4 entries for each, making this a lot of typing, and a massive pain to change if I ever want to add a new entry or something. My next idea was to use database relations: class PartyResult: party = models.CharField() result = models.DecimalField() class Riding: results = models.ManyToManyField(PartyResult) But this adds some complexity to using it, and makes the admin site a lot less usable, and I don't want to have to do a bunch of database queries just to read one Riding. Right now, I've realized I can use a ForeignKey in the PartyResult that leads to the riding, … -
How to return custom JSON from model?
I have a model with multiple fields but I only want to expose some or a combination of them. For example the model has opening_time=12:00 and closing_time=18:00 and I want to return the field opening_hours=[12:00, 18:00] in the JSON. This is just an example, but I have also some other fields to combine into one in the return JSON. How can I do this? Is there a way to modify my ModelSerializer? -
Password authentication failed for user in Docker postgres image
I am trying to dockerize my Django project. For this purpose, I am trying to divide the whole project into 2 parts The whole web related things in one container. Database i.e Postgres in another This is my Dockerfile for the first container. FROM alpine # Initialize RUN mkdir -p /data/web WORKDIR /data/web COPY /requirements/* /data/web/ # Setup RUN apk update RUN apk upgrade RUN apk add --update python3 python3-dev postgresql-client postgresql-dev build-base gettext RUN apk add libffi-dev zlib-dev RUN apk add build-base python-dev py-pip jpeg-dev ENV LIBRARY_PATH=/lib:/usr/lib RUN pip3 install --upgrade pip RUN pip3 install -r production.txt RUN pip3 install gunicorn # Clean RUN apk del -r python3-dev postgresql # Prepare COPY . /data/web/ RUN mkdir -p mydjango/static/admin RUN chmod u+x docker-entrypoint.sh # Copy entrypoint script into the image COPY ./docker-entrypoint.sh / ENTRYPOINT ["/docker-entrypoint.sh"] I created a postgres database instance using command docker run --name postgres -it -e POSTGRES_USER=mannu -e POSTGRES_PASSWORD=mysecretpassword postgres When this postgres instance started running I entered the shell postgres instance usint docker exec -it postgres /bin/bash root@ae052fbce400:/# psql -U psql In Psql shell opened, I created the Database named db_name and granted all the privileges to the postgreuser named mannu; After doing all the above … -
error in python migrations
I have a problem when migrating, cloning project and configuring on my computer but when I perform the first migration so that all the tables grow, I get the error. It is the first migration is a project in which the step dare has several tables but as I comment when making the first migration the error is created Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying seguridad.0001_initial... OK Applying activos.0001_initial...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/gyanezc/Documents/Proyectos/corem-alher/envosx/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/gyanezc/Documents/Proyectos/corem-alher/envosx/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/gyanezc/Documents/Proyectos/corem-alher/envosx/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/gyanezc/Documents/Proyectos/corem-alher/envosx/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/gyanezc/Documents/Proyectos/corem-alher/envosx/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/Users/gyanezc/Documents/Proyectos/corem-alher/envosx/lib/python2.7/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/gyanezc/Documents/Proyectos/corem-alher/envosx/lib/python2.7/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Users/gyanezc/Documents/Proyectos/corem-alher/envosx/lib/python2.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/Users/gyanezc/Documents/Proyectos/corem-alher/envosx/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 93, in __exit__ self.execute(sql) File "/Users/gyanezc/Documents/Proyectos/corem-alher/envosx/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File "/Users/gyanezc/Documents/Proyectos/corem-alher/envosx/lib/python2.7/site-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/Users/gyanezc/Documents/Proyectos/corem-alher/envosx/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/Users/gyanezc/Documents/Proyectos/corem-alher/envosx/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) … -
Django grab updated values from another model
I have a Model: class Subject(models.Model): name = models.CharField(max_length=150) dob = models.DateField() and another Model class Procedure(models.Model): subs = models.CharField(max_length=150) type = models.CharField(max_length=50) In my Procedure's forms.py, I call the following: subs = forms.ChoiceField(choices=SUBJECTS) where SUBJECTS is pulled from via Subject.objects.all() and contains an array of all the values name When Subject is updated, I have to restart the server to get the updated values for my Procedure model. Is there anyway I can pull the updated values without restarting the server? I tried to incorporate refresh_from_db() but was unable how to figure out how to get it working. -
Can Django ORM join on something other than pk?
Django writes a query containing this automatically: LEFT OUTER JOIN "object" T4 ON ("start_table"."object_type_2_id" = T4."id") LEFT OUTER JOIN "destination_table" ON (T4."id" = "destination_table"."object_id") Is there a way to have Django make this more efficient by writing this instead?: JOIN destination_table ON destination_table.object_id = start_table.object_type_2_id Some context to keep in mind; the start_table has several foreign key fields that all refer to the same object table, but for different reasons, which is why I've given object_type_2_id as the column name. -
Using ProFTPD for SFTP access for Django users
I'm using MySQL database credentials to log in users to a Linux folder with ProFTPD. So far, I'm able to log in a database user if I use no auth, but when I use the pkbdf2 as the auth type, it fails to log in giving the error: sftp.log 2018-05-14 14:59:16,639 mod_sftp/0.9.9[1616]: sending acceptable userauth methods: password 2018-05-14 14:59:16,648 mod_sftp/0.9.9[1616]: password authentication for user 'user_1' failed: No such user 2018-05-14 14:59:16,648 mod_sftp/0.9.9[1616]: sending userauth failure; remaining userauth methods: password 2018-05-14 14:59:16,649 mod_sftp/0.9.9[1616]: client sent SSH_MSG_IGNORE message (160 bytes) 2018-05-14 14:59:16,650 mod_sftp/0.9.9[1616]: disconnecting client (received EOF) These are the conf files which I have edited: sql.conf <IfModule mod_sql.c> SQLBackend mysql SQLEngine on AuthOrder mod_sql.c SQLAuthenticate on CreateHome on 777 SQLAuthTypes pbkdf2 SQLPasswordPBKDF2 SHA256 36000 32 SQLPasswordEncoding base64 SQLPasswordUserSalt sql:/GetUserSalt SQLNamedQuery GetUserSalt SELECT "SUBSTRING(password, 21, 12) AS salt FROM user_management_userprofile WHERE username='%u'" SQLConnectInfo db_name@127.0.0.1:3306 db_user db_password SQLUserInfo db_table_userprofile username password id group_id home NULL SQLGroupInfo db_table_group name id NULL SqlLogFile /var/log/proftpd/sql.log </IfModule> proftpd.conf Include /etc/proftpd/modules.conf UseIPv6 off IdentLookups off ServerName "192.168.146.147" ServerType standalone DeferWelcome off MultilineRFC2228 on DefaultServer on ShowSymlinks on TimeoutNoTransfer 600 TimeoutStalled 600 TimeoutIdle 1200 DisplayLogin welcome.msg DisplayChdir .message true ListOptions "-l" DenyFilter \*.*/ DefaultRoot /custom/home/folder/%u RequireValidShell off Port 2223 … -
Django 1.11.7 - Django Compressor - argument 5: <class 'TypeError'>: expected LP_OVERLAPPED instance instead of pointer to OVERLAPPED
I'm trying to get an existing Django 1.11.7 (Python 3.5) project up and running on my Windows 10 box. After getting my environment set up, I'm now seeing the home page after running the application, but any internal page I visit I get the following error: argument 5: <class 'TypeError'>: expected LP_OVERLAPPED instance instead of pointer to OVERLAPPED I have traced this to a call from compress.py (Django compressor) for some compressed CSS files, to some win32 file locking code in the internals of django.core, specifically this line: https://github.com/django/django/blob/master/django/core/files/locks.py#L86 (UnlockFileEx in the snip below). class OVERLAPPED(Structure): _anonymous_ = ['_offset_union'] _fields_ = [ ('Internal', ULONG_PTR), ('InternalHigh', ULONG_PTR), ('_offset_union', _OFFSET_UNION), ('hEvent', HANDLE)] LPOVERLAPPED = POINTER(OVERLAPPED) .... def lock(f, flags): hfile = msvcrt.get_osfhandle(_fd(f)) overlapped = OVERLAPPED() ret = LockFileEx(hfile, flags, 0, 0, 0xFFFF0000, byref(overlapped)) return bool(ret) def unlock(f): hfile = msvcrt.get_osfhandle(_fd(f)) overlapped = OVERLAPPED() ret = UnlockFileEx(hfile, 0, 0, 0xFFFF0000, byref(overlapped)) return bool(ret) The strange thing is that both the LockFileEx and UnlockFileEx methods are called on the home page without error. Inspecting the locals in both the successful and unsuccessful calls turned up nothing. Stack trace in case it helps (higher stack redacted): File "C:\x\env\lib\site-packages\compressor\templatetags\compress.py", line 127, in render return self.render_compressed(context, self.kind, … -
why node express sees django's boolean as string?
Due to some reasons, I have a django backend that needs to make another request to a express nodejs's api call but somehow the express is seeing boolean field django passed as string how can I fix this issue? example of django part payload = { "verified": True } e = requests.post('http://api', payload).json() as for express part, I just used console.log(res.body) and also checked the typeof for example console.log(req.body); // {verified: 'True'} console.log(typeof(req.body.verified)); // string This is causing mongoose not able to query the boolean field wanted Does anyone have any idea about this? Thanks in advance for any help. -
Getting KeyError in request.session
Here is my code for using session in Django. Everything seems fine but getting KeyError at /addfixeddeposit/ views.py def anotherpage(request, account_number): form = FixedDepositForm() context = {'form' : form} request.session['account_number'] = account_number return render(request, 'bankmanagement/another_page.html', context) def addfixeddeposit(request): if request.method == "POST": var = request.session['account_number'] print(var) form = FixedDepositForm(request.POST) if form.is_valid: acc = Account.objects.get(pk = var) tenure = request.POST['tenure'] rate = reuquest.POST['rate'] new_fixed = FixedDeposit(account_number = acc, tenure = tenure, rate = rate) new_fixed.save() del request.session['account_number'] return redirect('behome') return redirect('behome') -
How to access a variable in a function from another function in Django
So, I'm trying to access the variable store in get_queryset() from get_context_data(). I though I can deal with that by using a global variable. But it didn't work too. Is there any other way to do that? def get_queryset(self): print(store) # an error happens ... def get_context_data(self, **kwargs): context = super(StoreDetailView, self).get_context_data(**kwargs) context['store'] = Store.objects.filter(domainKey=self.kwargs['store_domainKey']) context['store'] = get_object_or_404(Store, domainKey=self.kwargs['store_domainKey']) store = context['store'] ... -
Pass DetailView Django Multiple Model in single template
How can I pass multiple model using DetailView in single template. py views file views.py from .models import EventDetail, EventTrainer, EventParticipant class EventDetailView(DetailView): # model = EventDetail # template_name = 'event_templates/single_event.html' def get_context_data(self, *args, **kwargs): context = super(EventDetailView, self).get_context_data(*args, **kwargs) return context -
Django: Load production settings for celery
My Django project has multiple settings file for development, production and testing. And I am using supervisor to manage the celery worker. My question how to load the settings file for celery based on the environment I am in. -
Django template display different models fields
I'm trying to list fields from few models in a table in template. The models are joined by different fields as in below snippet: models.py: class Client(models.Model): clientID = models.IntegerField(primary_key=True) firstName = models.CharField(max_length=30) lastName = models.CharField(max_length=50) class Loan(models.Model): clientID = models.ForeignKey(Client, on_delete=models.CASCADE) loanNo = models.CharField(max_length=10) class Case(models.Model): loanID = models.ForeignKey(Loan, on_delete=models.CASCADE) caseID = models.CharField(max_length=30, primary_key=True) callForPaymentDate = models.DateField(default=None) class Phase(models.Model): caseID = models.ForeignKey(Case, on_delete=models.CASCADE) phaseTypeID = models.ForeignKey(PhaseType, on_delete=models.CASCADE) courtID = models.TextField(max_length=200) class PhaseDetail(models.Model): caseID = models.ForeignKey(Case, on_delete=models.CASCADE) phaseTypeID = models.ForeignKey(PhaseType, on_delete=models.CASCADE) dismissalDate = models.DateField(default=None, blank=True, null=True) As you see above models are connected by ForeignKey. How do I pass those models in a view (views.py below): def index(request): clients = Client.objects.all() cases = Case.objects.all() phasedetails = PhaseDetail.objects.all() phases = Phase.objects.all() loans = Loan.objects.all() return render(request, 'erepertorium/index.html', {'clients': clients, 'cases': cases, 'phasedetails': phasedetails, 'phases': phases, 'loans': loans}) So that I can display different models fields but matched by this ForeignKey? See below html template: <table id="case_list" class="display"> <thead> <tr> <td>Sygnatura wg Powoda</td> <td>Sygnatura EPU</td> <td>PESEL</td> <td>Numer pożyczki</td> <td>Imię i nazwisko</td> </tr> </thead> <tbody> <tr></tr> {% for c in clients %} <tr> <td>1</td> <td>2</td> <td>{{ c.pesel }}</td> <!--<td>{{ loan.loanNo }}</td>--> <td>{{ c.firstName }}&nbsp;{{ c.lastName }}</td> </tr> {% endfor %} </tbody> </table> I've … -
How to pass variable from Django to Scrapy?
I have just started integrating Django with Scrapy. Upon receiving the variable(that is Website url) on the Django side, I want to pass it to the scrapy part so as to crawl it. This is the code snippet I wrote on the backend. def post(self, request, format=None): ... serializer = self.serializer_class(data=data) if serializer.is_valid(): site = serializer.create(data) domain = urlparse(site.url).netloc site_id = site.id settings = { 'unique_id': unique_id, 'USER_AGENT': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' } task = scrapyd.schedule('default', 'icrawler', settings=settings, url=url, domain=domain) task = { 'task_id': task, 'unique_id': target_id, 'status': 'started' } resp = { 'task': task, 'data': serializer.data, 'status': status.HTTP_201_CREATED } return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I have created spider on the Django project called icrawler.py. class IcrawlerSpider(CrawlSpider): name = 'icrawler' allowed_domains = ['https://google.com'] start_urls = ['http://https://google.com/'] rules = ( Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True), ) def parse_item(self, response): i = {} return i As you can see, there is allowed_domains = ['https://google.com'] and start_urls = ['http://https://google.com/'] in the spider. But I want to replace it with variable passed from Django and start running crawler, upon receiving the variable on the django side. I am not sure how I can implement it. -
Return variables to web server from PayPal Express Checkout Client REST API
I am using PayPal Express Checkout Client sided REST API javascript and Django 2.0.x/Python views for an ecommerce site. I have been able to implement Express Checkout and have the customer redirected to a success page on my server through the onAuthorize function. I need to access the paypal old IPN style listener variables or equivalent ... custom, mc_fee, email, first_name, last_name from paypal. I have no idea how to do this with the new REST API. Is this processed through a webhook and if so how? Example code? I just need the above variables returned back to my server preferably in my views.py checkout_complete function. Thanks mmbella