Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST Swagger: List and Retrieve functions are not detected by Swagger
I'm using django-rest-swagger version: 2.0.5 and django-rest-framework version: 3.4.6. I realiased that when I use list or retrieve functions the Swagger can not detect them as new endpoints. I have the following code in my views.py file: from rest_framework.viewsets import ViewSet class OrdersViewSet(ViewSet): lookup_field = 'uuid' def list(self, request: Request, *args, **kwargs): try: changeset = OrderSyncHelper().get_order_list_data() return Response(status=HTTP_200_OK, data=changeset) except (KeyError, ValueError) as e: return Response(status=HTTP_400_BAD_REQUEST, data=e.args) def retrieve(self, request: Request, uuid: str, *args, **kwargs): try: changeset = OrderSyncHelper().get_order_data(uuid) return Response(status=HTTP_200_OK, data=changeset) except (KeyError, ValueError) as e: return Response(status=HTTP_400_BAD_REQUEST, data=e.args) I was expecting to see in the openapi.json file the following endpoints: orders/ orders/{uuid}/ But they are not presented. Should I add something specific to these functions in order to be detected by Swagger? -
Looking for a specific Django app
I am currently in the middle of bulding a blog using the Django framework. Many Django apps are avalaible online with a large community. I was wonderinf if there is an app that allows me to enter images between text? or is is it better for me to just use Django CMS? -
Excel exports Django Pandas. My code below only downloads/export CSV. How do i make it download the excel
Here are my imports How will i get the Excel file to export/download Im using Pandas but it only downloads CSV from rest_pandas import PandasViewSet import pandas as pd **Here is the views The code below only allows download/export to CSV** class CategoryViewSet(views.SilBaseViewSet, PandasViewSet): queryset = models.Category.objects.all() serializer_class = serializers.CategorySerializer filter_class = filters.CategoryFilter ordering_fields = ('name', ) parser_classes = (JSONParser, MultiPartParser) How will i get the Excel file to export/download Im using Pandas but it only downloads CSV def get_paginated_response(self, data): resp = super(CategoryViewSet, self).get_paginated_response(data) category_draft_counts = [] for category in self.queryset: category_draft_counts.append( { 'category': category.name, 'draft': models.ChargeMasterEntry.objects.filter( entry_categories__entry_category=category, status='DRAFT' ).count() } ) resp.data['category_draft_counts'] = category_draft_counts return resp How will i get the Excel file to export/download -
Django - add a form into a fieldset in django admin?
is it possible to add a form to a fieldset view in django Admin? admin.py class ConfigTemplateAdmin(admin.ModelAdmin): form = VariableForm list_display = ('device_name', 'date_modified') fieldsets = ( ('Switch Details',{ 'fields' : ( ('device_name',), ('config','remote_config'), (form) ) }), ) the above gives me the error: sequence item 0: expected string or Unicode, ModelFormMetaclass found -
Trouble with FedEx Web Service 'Open Ship'
I'm a bit at a loss with FedEx's "Create Open Shipment" web service. It's supposed to send the shipper an email where they can print off a shipping label, or a code that they can bring into a nearby FedEx store. I successfully sent a request to FedEx, and got back a success response, but I have received no email. I attempted to use a test server, and a live server, but in either case I don't get the email. Also it should be known that I am using a Python wrapper for FedEx's web services. View where I create the FedEx request object that plugs in XML values def Fedex(request): CONFIG_OBJ = FedexConfig(key=settings.FEDEX_KEY, password=settings.FEDEX_PASSWORD, account_number=settings.FEDEX_ACCOUNT, meter_number=settings.FEDEX_METER, integrator_id=settings.FEDEX_OFFICE_INTEGRATOR_ID, use_test_server=True) logging.basicConfig(stream=sys.stdout, level=logging.INFO) # customer_transaction_id = "*** LocationService Request v3 using Python ***" # Optional transaction_id open_ship_request = FedexCreateOpenShipRequest(CONFIG_OBJ) open_ship_request.RequestedShipment.ShipTimestamp = datetime.datetime.now() open_ship_request.RequestedShipment.ServiceType = 'INTERNATIONAL_PRIORITY' open_ship_request.RequestedShipment.PackagingType = 'FEDEX_10KG_BOX' # Person Sending the Package "Person Trading In Their Phone" open_ship_request.RequestedShipment.Shipper.AccountNumber = settings.FEDEX_ACCOUNT open_ship_request.RequestedShipment.Shipper.Contact.PersonName = 'Tim Baney' open_ship_request.RequestedShipment.Shipper.Contact.CompanyName = 'Baney Co.' open_ship_request.RequestedShipment.Shipper.Contact.PhoneNumber = 'xxxxxxxxxx' open_ship_request.RequestedShipment.Shipper.Contact.EMailAddress = 'xxxxxxxxx@gmail.com' open_ship_request.RequestedShipment.Shipper.Address.StreetLines = '1000 S C. St.' open_ship_request.RequestedShipment.Shipper.Address.City = 'Chandler' open_ship_request.RequestedShipment.Shipper.Address.StateOrProvinceCode = 'AZ' open_ship_request.RequestedShipment.Shipper.Address.PostalCode = '85226' open_ship_request.RequestedShipment.Shipper.Address.CountryCode = 'US' # Person Receiving the Package open_ship_request.RequestedShipment.Recipient.AccountNumber = settings.FEDEX_ACCOUNT open_ship_request.RequestedShipment.Recipient.Contact.PersonName … -
Class decorator to apply method decorator on all inherited class method
I have several classes that inherit the same class. What I want is to have a class decorator on the base class who add an other decorator on all method of all inherited classes. Is it possible ? Is it a good pratice ? -
Set or change the default language dynamically according to the user - Django
Is there any way to change the value of LANGUAGE_CODE variable in settings.py dynamically on clicking a button (sending a request)? I want the user to have their own "default language" set for their account. Right now the user can select their preferred language using a drop-down list, and the website gets translated perfectly, and because Django picks up the browser's language, the user need not to re-select their language after they reopen the website from the same browser. But when they open the website from a different browser, the default language is again "English" because of the LANGUAGE_CODE variable set to en-us in settings.py. So what I want to do is make each user have an option to select their desired language as default for them. I want to do this by making an another(similar) drop-down and ask user to select a language they want as "default" and hit the save button, and on saving, I want to change LANGUAGE_CODE's value to the one selected by the user (i.e change it dynamically). But I don't know how to change the value of LANGUAGE_CODE dynamically. Also, there is one more problem with this approach. Say even if I was able … -
Django - value from database not appearing in dropdown list
I have a calendar which is suppose to be connected to the current admins-association. When admin picks a date in the calendar and need to fill the form. Association-dropdown-list won't show any data from database. I only want it to show association name of the current admins-association. Is there something i'm missing? Still a newbie so appreciate all your help, folks! models.py class Administrator(AbstractUser): ... association = models.ForeignKey(Association) class Event(models.Model): ... association = models.ForeignKey(Association) class Association(models.Model): asoc_name = models.CharField(max_length=50, null=True, blank=True) views.py def event_add_edit(request): if request.method == 'POST': form = CalForm(request.user, request.POST) res = {'success': False} if paramMissing(request.POST, 'name', res) \ or paramMissing(request.POST, 'location', res) \ or paramMissing(request.POST, 'start', res) \ or paramMissing(request.POST, 'end', res) \ or paramMissing(request.POST, 'allday', res) \ or paramMissing(request.POST, 'description', res) \ or paramMissing(request.POST, 'action', res) \ or paramMissing(request.POST, 'association', res) \ or paramMissing(request.POST, 'synced', res): return JsonResponse(res) action = request.POST['action'] name = request.POST['name'] location = request.POST['location'] start = request.POST['start'] end = request.POST['end'] allday = request.POST['allday'] == 'true' description = request.POST['description'] synced = request.POST['synced'] == 'true' asoc_id = form.request.POST['association'] association = Association.objects.get(pk=asoc_id.pk) if action == 'add': Event.objects.create( name=name, location=location, start=start, end=end, allday=allday, description=description, synced=synced, association=asoc ) res['success'] = True res['message'] = 'added' eid = Event.objects.latest('id').id res['eid'] … -
Schema Django Rest Framework for custom action
I am using django rest framework 3.6. The problem I am having is that I have a modelviewset with a detailroute action. The detailroute action requires POST fields that are different than the corresponding model fields. When the schema is generated for the API documentation it will say that no parameters are needed. How would I go about documenting the parameters needed. I know that somehow I have to edit the schema but I am not sure the best approach to do this. -
100% CPU utilization when running nginx with gunicorn(4 workers) and some static files
I have ubuntu server machine with 2 core. My django REST APIs are running by gunicorn /usr/local/bin/gunicorn --workers 4 --bind 0.0.0.0:8234 company.wsgi:application and have my front end code in angular.js both Django API(Backend) and Angular.js(front End) serving via nginx. I may have max 50 requests at a time. Problem is after some time my server's CPU utilization becomes 100% and API response slow. what could be the problem? -
invitation not accepted user are also registered
The feature in my app is a user should first request for invitation and if his invitation is accepted by admin(from admin), a message should be sent that you can signup. Flow of the feature User submits the form with his/her email address and mail will be sent saying thank you. Now if admin accepts his/her request, i.e request_accepted will be True now and a mail will be sent saying now you can signup. Finally when user go to signup page and submit the form, it should check if the email that he has filled and submitted during signup has been accepted or not. If accepted, signup is complete with success otherwise display an error stating this email address has not been invited. class Invitation(models.Model): email = models.EmailField(unique=True, verbose_name=_("e-mail Address")) request_approved = models.BooleanField(default=False, verbose_name=_('request accepted')) @receiver(post_save, sender=Invitation) def send_email_when_invite_is_accepted_by_admin(sender, instance, *args, **kwargs): request_approved = instance.request_approved if request_approved: subject = "Request Approved" message = "Hello {0}! Your request has been approved. You can now signup".format(instance.email) from_email = None to_email = [instance.email] send_mail(subject, message, from_email, to_email, fail_silently=True) def requestInvitation(request): form = InviteForm(request.POST or None) if form.is_valid(): join = form.save(commit=False) email = form.cleaned_data.get('email') already_join, created = Invitation.objects.get_or_create(email=email) if created: already_join.save() subject = "Thank … -
Update another model's object after a form submit
I am attempting to update another model's object after a form submit. I would like the single object, already in existence within the Savings model, updated to reflect the most recent Entry submission. That Savings object has a pk=1. Currently, I have to open the Savings object in admin and save it every time I want current numbers. models.py class Entry(models.Model): date = models.DateField(blank=True, null=True,) euros = models.CharField(max_length=500, blank=True, null=True) comments = models.CharField(max_length=900, blank=True, null=True) euros_sum = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) xrate = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) dollars_sum = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) daily_savings_dollars = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) daily_savings_display = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) def get_absolute_url(self): return reverse('argent:detail', kwargs={'pk': self.pk}) class Savings(models.Model): total_spent_euros = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) total_spent_dollars = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) total_savings = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) total_savings_display = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) Am I assuming correctly that my command must be entered within these two views? (I could be wrong): views.py class EntryCreate(CreateView): form_class = EntryForm template_name = 'argent/entry_form.html' def form_valid(self, form): Savings.objects.update(id=1) return super(EntryCreate, self).form_valid(form) class EntryUpdate(UpdateView): model = Entry form_class = EntryForm template_name = 'argent/entry_form.html' def form_valid(self, form): Savings.objects.update(id=1) return super(EntryUpdate, self).form_valid(form) However, whenever I use Savings.objects.update(id=1) or Savings.objects.filter(id=1).update(), nothing happens. What am … -
How to fetch profile picture from social networking sites in django?
I have written the following code, the url is being fetched and is in the local host admin 127.0.0.1:8080/admin , but it is not displaying the profile picture on my website. My code is as follows In models.py class UserProfile(models.Model): user = models.OneToOneField(User, related_name="profile") name = models.CharField(max_length=250, null=True, blank=True) profile_image = models.ImageField(upload_to = get_upload_file_name, null=True, blank=True) url=models.CharField(max_length=500,null=True,blank=True) def __str__(self): return u'%s profile' % self.user.username In views.py def home(request): context ={'request': request, 'user': request.user} return render(request,'home.html',context) The question is what should I add in html and how can I call the model object. -
Divide the table on the next page, with reportlab?
I'm using reportlab to generate a pdf document that generates a table, the problem is that when it contains a large amount of data, the table exits the coordinates and I think dividing the table to another page can solve this. Could you help me? Thanks in advance! from reportlab.pdfgen import canvas from io import BytesIO from django.views.generic import View from reportlab.platypus import SimpleDocTemplate, Table, TableStyle from reportlab.lib.units import cm from reportlab.lib import colors from reportlab.lib.pagesizes import letter,A4,A5, A3, A2 from reportlab.platypus import (BaseDocTemplate, Frame, Paragraph, NextPageTemplate, PageBreak, PageTemplate) from reportlab.platypus.tables import Table, TableStyle import datetime mylist = [] today = datetime.date.today() mylist.append(today) class ReportePedidosPDF(View): def cabecera(self,pdf, id_especialidad): especialidad = Especialidad.objects.get(id=id_especialidad) #Establecemos el tamaño de letra en 16 y el tipo de letra Helvetica pdf.setFont("Helvetica", 16) #Dibujamos una cadena en la ubicación X,Y especificada pdf.drawString(370, 1125, u"REPORTE CAE") pdf.setFont("Helvetica", 14) pdf.drawString(330, 1100, u"PEDIDO POR ESPECIALIDAD") pdf.setFont("Helvetica", 10) pdf.drawString(625, 1000, u"FECHA: " + str(datetime.date.today())) pdf.setFont("Helvetica", 10) pdf.drawString(100, 1000, u"Solicitado por: " + str(especialidad.encargado.nombre)) def tabla(self,pdf,y,t, id_especialidad): especialidad = Especialidad.objects.get(id=id_especialidad) #Creamos una tupla de encabezados para neustra tabla encabezados = ('Especialidad', 'Codigo Experto', 'Nombre Articulo', 'Cantidad', 'Total') #Creamos una lista de tuplas que van a contener a las personas detalles = [(pedido.especialidad.nombre, … -
How do I get Django to correctly parameterise sqlite query?
When I passed a wildcard into the query it was still treated as a wildcard. I can see why this error is occurring, but is there a way to get all inputs passed into the query to be treated as raw text. Also, will this mean other inputs could lead to a form with this query running in the back end being SQL injectable? -
oscarcommerce catalogue import
I have a magento2 project. I want to import product catalog in magento 2 into django oscarcommerce. The official documentaion explains an importer (http://django-oscar.readthedocs.io/en/releases-1.1/howto/importing_a_catalogue.html). But that they are not supporting because its buggy. I tried to figure out how it works. But I couldn't find the source csv file to test with. Is there any module/scripts which convert data in magento2 to oscar commerce? I checked This thread, but didn't get any idea about it. -
How do I save data to a mongo database from a formset in Django?
I'm new to this application and still familiarizing myself with the architecture. What I have is a page made of multiple forms that needs to take input and save that to multiple collections (classes, items, personnel) in a Mongo database linked by _id (item_id and personnel_id). I have the following: forms.py: class DataGenerationForm(forms.Form): number_of_items = forms.IntegerField( widget=forms.NumberInput(attrs={'class' : 'form-control'})) label = forms.CharField( widget=forms.TextInput(attrs={'class' : 'form-control'})) def save_to_mongo(self): pass #placeholder statement urls.py urlpatterns = [ url(r'^class/$', DataGenerationFormView.as_view()), ... I'm not entirely sure how to proceed from here as this is new territory for me -- specifically, I can't figure out exactly how to implement the save_to_mongo() function here. I'm at a bit of a loss on how to proceed since I'm not entirely sure I am framing the problem correctly. It seems like I'll have to process each of the formsets individually and make a connection separately -- but I've never seen that done this way. -
django formwizard save locally on form navigation
I am using Django formwizard and at the moment I save the data to the model everytime the user navigates the forms. This way the data persists between the forms. However, I was wondering if there was a way to save the data locally using javascript instead of on the server during form navigation for user experience. At the moment, my django form-wizard lies in a jquery bootstrap dialog and I perform a submit operation to save form data as follows: $("#dialog").submit(function(e) { var the_url = "/reviewrecord/" + sessionStorage.getItem("pk") + "/"; var postData = $("#review-form").serializeArray(); $.ajax( { url: the_url, type: "POST", data: postData, success: function (data, textStatus, jqXHR) { $('.modal-body').html(data); }, error: function (jqXHR, textStatus, errorThrown) { alert(errorThrown); } }); $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); e.preventDefault(); e.unbind(); //unbind. to stop multiple form submit. }); return false; } This triggers the done method in my SessionWizardView and saves the data. This method is defined as; def done(self, form_list, **kwargs): print "Saving data" if 'pk' not in self.kwargs: return redirect('reviewrecord') pk = self.kwargs['pk'] # Update the record try: instance = DummyModel.objects.get(pk=pk) for form in form_list: for field, value in form.cleaned_data.iteritems(): setattr(instance, field, … -
get all actions that taken by user using signals in djang rest framework
I am very new to Python. I have created a model with all the data of User and creating the signals for registering user, logging in application, deleting an user and creating a group of users. I have to get all the action performed by the user for particular domain. Please help me out. Thanks in advance... Here is the code written below class User(models.Model): MALE = '1' FEMALE = '2' GENDER = ( (MALE, _("Male")), (FEMALE, _("Female")) ) ADMIN = "1" ADVERTISER = "2" USER = "3" ROLE = ( (ADMIN, _("Admin")), (ADVERTISER, _("Advertiser")), (USER, _("User")) ) email = models.EmailField(_('Email address'), max_length=254, unique=True) name = models.CharField(_('Name'), max_length=30, null=True, blank=True) screen_name = models.CharField(max_length=255, null=True, blank=True) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) dob = models.DateField(null=True, blank=True) gender = models.CharField( verbose_name=_("select gender."), max_length=1, choices=GENDER ) role = models.CharField( max_length=1, choices=ROLE, verbose_name=_("Select Role.") ) @receiver(post_save, sender=User) def create_profile_for_new_user(sender, created, instance, **kwargs): if created: instance = User actions = action.send(instance, verb='user created') profile = User(user=instance, actions=actions, object_id=instance.id, object_repr=instance.name) profile.save() @receiver(post_delete, sender=User) def delete_profile_for_new_user(sender, deleted, instance, **kwargs): if deleted: instance = User actions = action.send(instance, verb='user_deleted') profile = (user=instance,actions=actions) profile.delete() @receiver(user_logged_in) def sig_user_logged_in(sender, user, request, **kwargs): logger = logging.getLogger(__name__) logger.info("user logged in: %s at %s" % … -
django 1.9.9 cannot import name HAS_GEOIP
I am using django 1.9.9. I would like to use django-tracking module in my project. However, when I try to use django-tracking I encounter the following error message: File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 327, in execute django.setup() File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/usr/local/lib/python2.7/dist-packages/tracking/models.py", line 5, in <module> from django.contrib.gis.utils import HAS_GEOIP ImportError: cannot import name HAS_GEOIP sTraceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 327, in execute django.setup() File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/usr/local/lib/python2.7/dist-packages/tracking/models.py", line 5, in <module> from django.contrib.gis.utils import HAS_GEOIP ImportError: cannot import name HAS_GEOIP GeoIP module is properly installed. What I can see that django is looking foro HAS_GEOIP in django.contrib.gis.utils, but instead it should look in django.contrib.gis.geoip. How do I tell django 1.9.9 to use django.contrib.gis.geoip ? -
Postgres settings for Django on Google App Engine Flexi
I am trying to setup django with postgres on app engine flexi environment. I followed the instructions from here: https://cloud.google.com/appengine/docs/flexible/python/using-cloud-sql-postgres My django settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '<db-name>', 'USER': '<user-name>', 'PASSWORD': '<password>', 'HOST': '/cloudsql/<instanse-connection-name>, 'PORT': '5432' }, } app.yaml: beta_settings: cloud_sql_instances: <instanse-connection-name> Error I am getting is: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/cloudsql/instanse-connection-name/.s.PGSQL.5432"? Please help with the correct settings. -
django query not return me all fields
I am running a query and want to display all fields. question = Question.objects.get(pk=question_id) In a model class Question(models.Model): #id = models.AutoField(primary_key=True) question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text When I print data in a view it return me only question name, I am also want to display id and date template {{ question }} -
Memory leak in django application
I have app in Django 1.6, I use sqlite3 and I have problem with leak memory. Every hour my app need a lot of memory - yes I have a long running scripts, but they starts twice a day. My debug mode is set on False. I read about db.reset_queries(), it can be solution this kind of problems? -
How to query many to many relationships on django?
I'm writing an app for food recipes. I want it to be able to discriminate recipes avoiding specific food intolerances (i.e. lactose, eggs, gluten, SO2...). I've come up with this model for that: models.py from django.db import models from unittest.util import _MAX_LENGTH class Alimento(models.Model): INTOLERANCIAS = ( ('00', 'Ninguna'), ('GL', 'Gluten'), ('CR', 'Crustáceos'), ('HU', 'Huevos'), ('FS', 'Frutos Secos'), ('AP', 'Apio'), ('MO', 'Mostaza'), ('SE', 'Sésamo'), ('PE', 'Pescado'), ('CA', 'Cacahuetes'), ('SO', 'Sulfitos'), ('SJ', 'Soja'), ('LA', 'Lácteos'), ('AL', 'Altramuz'), ('ML', 'Moluscos'), ('CA', 'Cacao'), ) nombre = models.CharField(max_length=60) intolerancia = models.CharField(max_length=2, choices=INTOLERANCIAS) def __str__(self): return self.nombre class Receta(models.Model): nombre = models.CharField(max_length=100) raciones = models.IntegerField(default=1) preparacion = models.TextField(default='') consejos = models.TextField(blank=True) ingredientes = models.ManyToManyField(Alimento, through='Ingrediente') def __str__(self): return self.nombre class Ingrediente(models.Model): receta = models.ForeignKey('recetas.Receta', on_delete=models.CASCADE) alimento = models.ForeignKey('recetas.Alimento', related_name='ingredientes', on_delete=models.CASCADE) cantidad = models.FloatField(default=0) descripcion = models.CharField(max_length=60, blank=True) def __str__(self): return self.alimento.__str__() I've registered them in admin.py and I can create/update/delete them ok, but I don't see the manytomany field anywhere inb the admin UI. admin.py from django.contrib import admin from .models import Alimento, Receta, Ingrediente admin.site.register(Alimento) admin.site.register(Receta) admin.site.register(Ingrediente) So I went to shell and tried some queries there Alimento.objects.all() , , , , , , ]> Receta.objects.all() ]> gaz = Receta.objects.get(nombre='Gazpacho') Ingrediente.objects.filter(receta=gaz) , , , … -
DjangoQ run manage.py qcluster results in PermissionError: [WinError5] Access is denied
I've just recently started played around with web application development using Django and now got to Django-Q for async tasks. I followed this tutorial up to slide 13. Unfortunately then, when I try to run python manage.py qcluster I get these error messages: (djangoq_tut) D:\Code\Python\DjangoQ_Tutorial\djangoq_demo>python manage.py qcluster Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "D:\Code\Python\DjangoQ_Tutorial\djangoq_tut\lib\site-packages\django\core\management\__init__.py", line 350, in execute_from_command_line utility.execute() File "D:\Code\Python\DjangoQ_Tutorial\djangoq_tut\lib\site-packages\django\core\management\__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Code\Python\DjangoQ_Tutorial\djangoq_tut\lib\site-packages\django\core\management\base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "D:\Code\Python\DjangoQ_Tutorial\djangoq_tut\lib\site-packages\django\core\management\base.py", line 399, in execute output = self.handle(*args, **options) File "D:\Code\Python\DjangoQ_Tutorial\djangoq_tut\lib\site-packages\django_q\management\commands\qcluster.py", line 22, in handle q.start() File "D:\Code\Python\DjangoQ_Tutorial\djangoq_tut\lib\site-packages\django_q\cluster.py", line 57, in start self.sentinel.start() File "c:\program files (x86)\python35-32\Lib\multiprocessing\process.py", line 105, in start self._popen = self._Popen(self) File "c:\program files (x86)\python35-32\Lib\multiprocessing\context.py", line 212, in _Popen return _default_context.get_context().Process._Popen(process_obj) File "c:\program files (x86)\python35-32\Lib\multiprocessing\context.py", line 313, in _Popen return Popen(process_obj) File "c:\program files (x86)\python35-32\Lib\multiprocessing\popen_spawn_win32.py", line 66, in __init__ reduction.dump(process_obj, to_child) File "c:\program files (x86)\python35-32\Lib\multiprocessing\reduction.py", line 59, in dump ForkingPickler(file, protocol).dump(obj) TypeError: can't pickle _thread.lock objects (djangoq_tut) D:\Code\Python\DjangoQ_Tutorial\djangoq_demo>Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\program files (x86)\python35-32\Lib\multiprocessing\spawn.py", line 100, in spawn_main new_handle = steal_handle(parent_pid, pipe_handle) File "c:\program files (x86)\python35-32\Lib\multiprocessing\reduction.py", line 86, in steal_handle _winapi.DUPLICATE_SAME_ACCESS | _winapi.DUPLICATE_CLOSE_SOURCE) PermissionError: [WinError 5] Access …