Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Combine DjangoObjectType and ObjectType
I have a simple django model with a calculated property field clicks. The model looks like this: class Link(models.Model): url = models.URLField() @property def clicks(self): """ Property does some calculations and returns a list of dictionaries: """ # removed calculation for simplicity return [{'dt': 1, 'clicks': 100}, {'dt': 2, 'clicks': 201}] I want to make this model accesible in my graphql endpoint. So I created the following Types and Query: class Stats(graphene.ObjectType): clicks = graphene.String() dt = graphene.String() class LinkType(DjangoObjectType): clicks = graphene.List(Stats, source='clicks') class Meta: model = Link class Query(object): link = graphene.Field(LinkType, id=graphene.Int()) def resolve_link(self, info, **kwargs): id = kwargs.get('id') url = kwargs.get('url') if id is not None: return Link.objects.get(pk=id) return None Now I should be able to use the following query in my graphql explorer: { link(id: 3) { id, url, clicks{ clicks, dt } } } My expected result would be like this: { id: 3, url: "www.google.de", clicks: [ dt: 1, clicks: 100}, dt: 2, clicks: 201} ] } But the nested values of clicks and dt are null: { id: 3, url: "www.google.de", clicks: [ dt: null, clicks: null}, dt: null, clicks: null} ] } So what am I doing wrong here? How can … -
Django: Custom manager method VS model method to override create?
I'm not sure to understand the actual purpose of using a create_object() method in a custom manager, rather than directly in the model, when I need to override the default Class.objects.create() method. The only difference I see is how I would call it: Class.create_object() if the create_object() method is in the model Class.objects.create_object() if the create_object is a custom manager method. However, I suppose the latter is the right thing to do, based on examples I can see from Django (with create_user for example). I just would like to understand why. Thanks! -
Django Crispy forms with ModelForm, none type has no attribute fields, wrap_together
Im new to crispy forms and am trying to add some layout to the forms, by putting them in three groups, then id like to put them in some panels (im using boostrap3) this is my forms.py class EditSiteForm(forms.ModelForm): class Meta: model = SiteData fields = ['location', 'site_type', 'bgp_as', 'opening_date','last_hw_refresh_date','is_live', 'tel','address','town','postcode', 'regional_manager','regional_manager_tel','assistant_manager','assistant_manager_tel' ,'duty_manager','duty_manager_tel'] helper = FormHelper() helper.form_method = 'POST' helper.add_input(Submit('Save', 'Save', css_class='btn-primary')) helper[0:5].wrap_together(Field, 'Details') helper[6:9].wrap_together(Field, 'Address') helper[10:15].wrap_together(Field, 'Showroom Contacts') when I load the page I get Exception Value: 'NoneType' object has no attribute 'fields' Exception Location: /usr/local/lib/python3.6/site-packages/crispy_forms/layout_slice.py in wrap_together, line 107 is modelform not support in crispy? do I need to issue each field manually first? Thanks -
Django FormTools Dynamic Form Not Saving Data
I am using Django Formtools for the forms: https://django-formtools.readthedocs.io/en/latest/ Currently Happening: Dynamically generated form and form fields are being displayed. Enter some data into the said fields, but self.get_all_cleaned_data() returns nothing. Form returns to page 0 instead of submitting the form and using done() What I want to happen: - Data in fields to be retained and displayed when going back, or to the confirmation page - Form to actually submit and use done() to process and save The following the my forms.py class OrderForm(forms.Form): class Meta: localized_fields = ('__all__',) def __init__(self, *args, **kwargs): self.fields = kwargs.pop('fields') fields = self.fields super(OrderForm, self).__init__(*args, **kwargs) if not isinstance(fields, str): for i in fields.fields.all(): widget = forms.TextInput() _type = forms.CharField if i.field_type == Field.TEXTAREA_FIELD: widget = forms.Textarea ... self.fields[i.name] = _type(**fields) This is supposed to get Database created forms and field data and generate fields accordingly. For example: Form A has fields: Name (Regular Text Field) Address (Textarea) The above code will then generate fields for those. The next block of code is from my views.py file FORM_TEMPLATES = { "0": 'order/details.html', "1": 'order/details.html', "2": 'order/details.html', "3": 'order/details.html', "4": 'order/details.html', "confirm": 'order/confirm.html', } class Order(SessionWizardView): form_list = [OrderForm] def get_current_step_form(self, company, *args, **kwargs): … -
DRF: Validate nested serializer data when creating, but not when updating
When using writable nested serializers in DRF there is the known problem with validating eventual unique fields and preventing the updating of the parent serializer. This issues has been asked many times in questions like these: Unique validation on nested serializer on Django Rest Framework Django rest framework not creating object with FK to a model with unique=True field For simplicity let's take the example from the first question: class GenreSerializer(serializers.ModelSerializer): class Meta: fields = ('name',) #This field is unique model = Genre extra_kwargs = { 'name': {'validators': []}, } class BookSerializer(serializers.ModelSerializer): genre = GenreSerializer() class Meta: model = Book fields = ('name', 'genre') def create(self, validated_data): # implement creating def update(self, instance, validated_data): # implement updating Now the problem is that the uniqueness validation is dropped out also for creating. This could be intercepted in the view, for example: class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer = BookSerializer def perform_create(self): # implement logic and raise ValidationError However this doesn't feel really right because we're validating the uniqueness of Genre in BookViewSet. The other option is to implement the validation in the create() method of BookSerializer as explained in the second question (see list above). What I really miss in both … -
2018 Django Internationalization for 3 languages site
i have tried to use different sources from StackOverflow in order to make my site to accept by default my language and not EN. During the research over the Internet I couldn't find a real solution that can help me to use my own language. I've tried until now, which is my source code: LANGUAGE_CODE = 'ro' from django.utils.translation import ugettext_lazy as _ LANGUAGES = ( ('ro', _('Romanian')), ('en', _('English')),) DEFAULT_LANGUAGE = 1 Middleware like this post:\https://gist.github.com/vstoykov/1366794\ or Django default language but they don't really work in django 2.0. Can someone please help me with my issue? Thank you! -
Modify models field via view doesn't work
In my Django application, I want to subtract 1 "free_places" field in the "Event" model using the "EventDetailView" view where the form is located. Each time the form is OK (when the user subscribes to the event), the "free_places" field should decrease by 1. I do not know why my code does not work. My view: class EventDetailView(DetailView, ModelFormMixin): model = models.Event form_class = forms.RegisterForm context_object_name = 'event' def get_success_url(self): return reverse('events:list') def get_initial(self): return {'event': self.kwargs['pk']} def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): self.object = self.get_object() self.object.free_places - 1 self.object.save() return self.form_valid(form) else: return self.form_invalid(form) Models: class Event(models.Model): title = models.CharField(max_length=500) date = models.DateField() text = models.TextField() image = FilerImageField(null=True, blank=True) flag = models.ForeignKey(Flag) free_places = models.IntegerField() class Meta: ordering = ['-date'] def __str__(self): return self.title @property def slug(self): return slugify(self.title) def get_absolute_url(self): return reverse('events:detail', args=[self.slug, self.id]) def get_model_id(self): return self.id class Register(models.Model): event = models.ForeignKey(Event) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) company = models.CharField(max_length=30, blank=True) street = models.CharField(max_length=50, blank=True) post_code = models.CharField(max_length=30, blank=True) city = models.CharField(max_length=30, blank=True) email = models.EmailField() phone_number = models.IntegerField() def __str__(self): return self.first_name def get_event_name(self): return self.event -
Testing circular reference models in Django
I have two tables/models with a circular reference one to another. When I run my tests, Django tries to flush the database (delete all tables, one by one) and then recreate it again for the next test. The problem is that when Django gets to one of those two tables, it crashes, saying that "can't truncate a table referenced in a foreign key constraint". This behaviour is actually quite logical, but unfortunately for me, not very helpful in my case. Is there any way I can make Django not try to commit after each DELETE, or maybe just delete all tables at once? -
How to dispay django auth user list in django suit dashboaard
I have used django suit dashboard. And customize admin side. Its working but default django auth user list not display. So, How to display auth user list with django suit dashboard. -
Django Restframework _ update user model with special custom token?
in DRF i have a some custom action that will do something to user model.user instances are all in state of is_active = False.Im trying to make something that turns the user to is_active = True. i made some a token model that has OneToOne to my user model.the function im trying to make is : if token that user put in the form equals to user.token then set user.is_active = True.im confused how to do that. I made my own serializer class : class ActivateUserSerializer(serializers.ModelSerializer): phonenumber = serializers.CharField() token = serializers.CharField() class Meta: model = UserProfile fields = ['phonenumber','token'] def get_token(self, obj): request = self.context.get('request') x = request.data['phonenumber'] obj = UserProfile.objects.get(phonenumber=x) if request.data['token'] == obj.first_token: obj.is_active = True obj.save() i know this is not .create() .or update() function.so this is how I reach so far.I dont know what view i should use for this functionality. -
Does heroku app have to share the same name as django project?
I'm trying to deploy an app that I started with django-admin startproject workout. Months later, it was time to deploy, workout was not an available name for heroku apps. Thus, I decided on shworkout. Now, I'm having problems with the deployment. Take a look at this traceback: 2018-01-15T13:50:49.922410+00:00 heroku[web.1]: Starting process with command `gunicorn shworkout.wsgi --log-file -` 2018-01-15T13:50:52.274803+00:00 app[web.1]: [2018-01-15 13:50:52 +0000] [4] [INFO] Starting gunicorn 19.7.1 2018-01-15T13:50:52.275393+00:00 app[web.1]: [2018-01-15 13:50:52 +0000] [4] [INFO] Listening at: http://0.0.0.0:57296 (4) 2018-01-15T13:50:52.275484+00:00 app[web.1]: [2018-01-15 13:50:52 +0000] [4] [INFO] Using worker: sync 2018-01-15T13:50:52.278566+00:00 app[web.1]: [2018-01-15 13:50:52 +0000] [8] [INFO] Booting worker with pid: 8 2018-01-15T13:50:52.283407+00:00 app[web.1]: [2018-01-15 13:50:52 +0000] [8] [ERROR] Exception in worker process 2018-01-15T13:50:52.283421+00:00 app[web.1]: Traceback (most recent call last): 2018-01-15T13:50:52.283428+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 578, in spawn_worker 2018-01-15T13:50:52.283430+00:00 app[web.1]: worker.init_process() 2018-01-15T13:50:52.283431+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 126, in init_process 2018-01-15T13:50:52.283433+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 135, in load_wsgi 2018-01-15T13:50:52.283432+00:00 app[web.1]: self.load_wsgi() 2018-01-15T13:50:52.283434+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2018-01-15T13:50:52.283443+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 65, in load 2018-01-15T13:50:52.283441+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2018-01-15T13:50:52.283442+00:00 app[web.1]: self.callable = self.load() 2018-01-15T13:50:52.283446+00:00 app[web.1]: return util.import_app(self.app_uri) 2018-01-15T13:50:52.283448+00:00 app[web.1]: __import__(module) 2018-01-15T13:50:52.283444+00:00 app[web.1]: return self.load_wsgiapp() 2018-01-15T13:50:52.283445+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp 2018-01-15T13:50:52.283449+00:00 app[web.1]: ModuleNotFoundError: No module named 'shworkout' … -
Django - Liste index in template
i have a probleme with my template. I know how to use list.index to get a value from a list, but now my index value is container.id (=1) so i have supidly try list.container.id and is not working like list.1 -
inAttributeError: module 'reportlab.pdfgen.canvas' has no attribute 'acroform'
I want to create an acroform on PDF in Django by using reportLab. I have already installed the package for reportLab. But when implementing acroform im getting inAttributeError: module 'reportlab.pdfgen.canvas' has no attribute 'acroform' from django.shortcuts import render from django.http import HttpResponse from io import BytesIO from reportlab.pdfgen import canvas from django.http import HttpResponse def index(request): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"' buffer = BytesIO() # Create the PDF object, using the BytesIO object as its "file." p = canvas.Canvas(buffer) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(100, 100, "Hello world.") canvas.acroform.checkbox(name='CB0',tooltip='Field CB0',checked=True,x=72,y=72+4*36,buttonStyle='diamond',borderStyle='bevelled',borderWidth=2,borderColor=red,fillColor=green,textColor=blue,forceBorder=True) # Close the PDF object cleanly. p.showPage() p.save() # Get the value of the BytesIO buffer and write it to the response. pdf = buffer.getvalue() buffer.close() response.write(pdf) return response -
Django ordering by random when using annotate
If I order my queryset randomly and print it out, like this:- [p for p in Player.objects.order_by('?')] it works as you'd expect. The players appear in a random order. And if I order them by the number of games they've played, like this:- [p for p in Player.objects.annotate('games').order_by('games__count')] it also works as you'd expect. The players appear in order of the number of games they've played. But I want to randomise the players that have played the same number of games. So I do this:- [p for p in Player.objects.annotate('games').order_by('games__count', '?')] and it completely breaks it. The query takes a second or two to run, I get the same player over and over, and they're all over the place in terms of order. What have I done wrong? -
Why my Django project in heroku (free) resets database automatically? and loosing my info
I have Deployed my Django project in heroku (free) and add information to model from admin page. But after around 1h it resets PostgreSQL automatically and I'm loosing my information! -
Django cannot load JS files from HTML templates
I am new to Django and Web development. I am stuck at a point. I need to make a graph using Javascript and I successfully done that in file located in app/templates/graphs/BarGraph.js and my HTML template file analysis.html is also in the same folder. It is running fine using Web server Chrome but when I am trying to run my HTML file using my app it does not find my BarGraph.js analysis.html {% extends "header.html" %} {% block content %} <h3 style="text-align:center;">Graph</h3> <script type="text/javascript" src= "templates/graphs/BarGraph.js" ></script> {% endblock %} I also tried to put all the JS code in my HTML, then it does process the code but then does not find frequent_words.tsv file and says BarGraph.js // See D3 margin convention: http://bl.ocks.org/mbostock/3019563 var margin = {top: 20, right: 10, bottom: 100, left:50}, width = 700 - margin.right - margin.left, height = 500 - margin.top - margin.bottom; var svg = d3.select("body") .append("svg") .attr ({ "width": width + margin.right + margin.left, "height": height + margin.top + margin.bottom }) .append("g") .attr("transform","translate(" + margin.left + "," + margin.right + ")"); // define x and y scales var xScale = d3.scale.ordinal() .rangeRoundBands([0,width], 0.2, 0.2); var yScale = d3.scale.linear() .range([height, 0]); // define x … -
Django: Modify User in LDAP
I have a webapp which contains a login and a profile page. I can log-in as a user from the LDAP but I don't know how to modify specific attributes i.e. first_name, last_name or email. I do have some code from another user: class SynchronisingUserAdapter(object): """ This adapts an _LDAPUser object that has been initialised with a correct User object. The layers and layers of wrapping allow this to sit on top of the existing code, but is kind of confusing. The recommended incantation to go from a Django User object to a correctly set up adapter is:: ldap_user = backend.get_user(user.id) sync = SynchronisingUserAdapter(ldap_user) """ group_type = settings.ldap_settings.AUTH_LDAP_GROUP_TYPE group_template = settings.ldap_settings.LDAP_PIXIEDUST_GROUP_DN_TEMPLATE def __init__(self, original): self.original = original self.bound = False def reset_ldap_password(self): """ Set the LDAP Password to an impossible value """ self.connection.modify_s(self.dn, [(self.ldap.MOD_REPLACE, 'userPassword', '{SSHA}!')]) @property def dn(self): dn = self.original.ldap_user.dn if type(dn) == type(u''): return unicode.encode(dn, 'UTF-8') else: return dn @property def connection(self): conn = self.original.ldap_user._get_connection() if not self.bound: self.original.ldap_user._bind() self.bound = True return conn @property def ldap(self): return self.original.ldap_user.ldap def user_attrs(self): """ Create a set of user attributes based on the state of the django user object. """ attrs = generate_attrs(self.original, settings.ldap_settings.AUTH_LDAP_USER_ATTR_MAP) for name, value in settings.ldap_settings.LDAP_PIXIEDUST_DEFAULT_ATTR_MAP.items(): … -
error: [Errno 10053] while submitting ajax form in Django
I saw a similar error already posted here but that did not help to solve my problem. Besides the OP did not provided any information about what he was doing when he encountered that error (as other have said in the comments). What I am trying to do ? I am just trying to register the user to Django with ajax. What is the problem ? I get the following error the movement I submit the form: [15/Jan/2018 17:49:37] "POST /authenticate/register/ HTTP/1.1" 200 14 Traceback (most recent call last): File "C:\Python27\lib\wsgiref\handlers.py", line 86, in run self.finish_response() File "C:\Python27\lib\wsgiref\handlers.py", line 128, in finish_response self.write(data) File "C:\Python27\lib\wsgiref\handlers.py", line 212, in write self.send_headers() File "C:\Python27\lib\wsgiref\handlers.py", line 270, in send_headers self.send_preamble() File "C:\Python27\lib\wsgiref\handlers.py", line 194, in send_preamble 'Date: %s\r\n' % format_date_time(time.time()) File "C:\Python27\lib\socket.py", line 328, in write self.flush() File "C:\Python27\lib\socket.py", line 307, in flush self._sock.sendall(view[write_offset:write_offset+buffer_size]) error: [Errno 10053] An established connection was aborted by the software in your host machine [15/Jan/2018 17:49:37] "POST /authenticate/register/ HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 54896) Traceback (most recent call last): File "C:\Python27\lib\SocketServer.py", line 596, in process_request_thread self.finish_request(request, client_address) File "C:\Python27\lib\SocketServer.py", line 331, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Python27\lib\SocketServer.py", line 654, in … -
django template tag with value from from loop [duplicate]
This question is an exact duplicate of: django template tag using for loop value i have django tags as {{ ques.0 }},{{ ques.1 }},{{ ques.2 }} and i wan't to display them using for loop something like this {% for i in ques %} document.getElementById("opt1").innerHTML="{{ ques.i }}"; {% end for %} Its not displaying the data but when i put a value like {{ ques.0 }} it gives the result ,but how can i use it with for loop to display the data Basically i want to pass a value in tags using for loop The main problem to to get value using tags that is generated using for loop in django x=5; for(var i=0;i<x;i++){ document.getElementById("question").innerHTML="{{ ques.i }}"; } -
Problems caused by changing the name of my app when deploying to heroku
The name of my django app was always workout. Then, when I started to deploy it, I thought it'd be a good idea to change the name to workoutcalendar. So I started a new git repo and put my project files in there (not starting a new django project). The only things I changed were the name of the folder workout (the first one of the django project where settings.py is located) to workoutcalendar as well as changing the DJANGO_SETTINGS_MODULE environment variable. Now, I'm running into problems. It seems that parts of my app are looking for a workout module, which they can't find. Example: 2018-01-15T13:06:40.615612+00:00 app[web.1]: Traceback (most recent call last): 2018-01-15T13:06:40.615613+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 135, in handle 2018-01-15T13:06:40.615614+00:00 app[web.1]: self.handle_request(listener, req, client, addr) 2018-01-15T13:06:40.615615+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 176, in handle_request 2018-01-15T13:06:40.615616+00:00 app[web.1]: respiter = self.wsgi(environ, resp.start_response) 2018-01-15T13:06:40.615617+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 146, in __call__ 2018-01-15T13:06:40.615618+00:00 app[web.1]: response = self.get_response(request) 2018-01-15T13:06:40.615619+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 81, in get_response 2018-01-15T13:06:40.615620+00:00 app[web.1]: response = self._middleware_chain(request) 2018-01-15T13:06:40.615621+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 37, in inner 2018-01-15T13:06:40.615622+00:00 app[web.1]: response = response_for_exception(request, exc) 2018-01-15T13:06:40.615623+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 87, in response_for_exception 2018-01-15T13:06:40.615624+00:00 app[web.1]: response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) 2018-01-15T13:06:40.615626+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line … -
How to make sure a form field remains not required after set to required in is_valid?
I have a form, where I have set description as not required. class LeaveApprovalForm(forms.ModelForm): class Meta: model = LeaveRequest description = forms.CharField( widget=forms.Textarea, label='Reason', required=False ) def is_valid(self): '''A description is not required when approving''' self.fields['description'].required = False if self.data.get('reject', None): self.fields['description'].required = True return super().is_valid() However when the form is validated and shows the This field is required. error. The html has the required attribute so if it is not rejected and approved the jquery popup requiring data entry is triggered. How do I ensure when the formis initialises again it is not required? -
Join sql queries for Django
I have two related models: class Category(models.Model): pass class Entry(models.Model): category = models.ForeignKey(Category) is_published = models.BooleanField(default=True) I need to get categories with published entries. I ended up with two queries: published = Entry.objects.filter(is_published=True) categories = Category.objects.filter(entries__in=published) Can I do this in one query? -
installation fixture django-municipios
I am getting the following error when executing the command python manage.py loaddata municipios_geo_2013_4674.json.bz2. how to solve attribute error? Package and json in: https://github.com/znc-sistemas/django-municipios Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 69, in handle self.loaddata(fixture_labels) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 109, in loaddata self.load_label(fixture_label) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 175, in load_label obj.save(using=self.using) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/serializers/base.py", line 205, in save models.Model.save_base(self.object, using=using, raw=True, **kwargs) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/db/models/base.py", line 837, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/db/models/base.py", line 904, in _save_table forced_update) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/db/models/base.py", line 954, in _do_update return filtered._update(values) > 0 File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/db/models/query.py", line 664, in _update return query.get_compiler(self.db).execute_sql(CURSOR) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1191, in execute_sql cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 863, in execute_sql sql, params = self.as_sql() File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1157, in as_sql val = field.get_db_prep_save(val, connection=self.connection) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/contrib/gis/db/models/fields.py", line 182, in get_db_prep_save return connection.ops.Adapter(self.get_prep_value(value)) AttributeError: Problem installing fixture '/Users/lidiane/Developer/django/integra-fundaj/municipios_geo_2013_4674.json': 'DatabaseOperations' object has no attribute 'Adapter' -
Recursion error calling a function using a post-save signal
I have a Category model, where the ForeignKey is to self. class Category(SEO, MetaData): parent = models.ForeignKey('self', blank=True, null=True, verbose_name='parent category', on_delete=models.CASCADE) path = ArrayField(models.IntegerField(), blank=True, null=True) I introduced the path field, to avoid recursion in widget, and do it model, because is not often done. I use a post_save signal to ssave the path: def _recurse_for_parent(cat_obj, path=None): # path at the beginning don't exist and need to be initialized if not path: path = [] if cat_obj.parent is not None: _recurse_for_parent(cat_obj.parent, path) return path def save_path(sender, instance, **kwargs): if instance.parent_id: instance.children = _recurse_for_parent(instance.parent) instance.save() post_save.connect(save_path, sender=Category) My issue is that I get the "maximum recursion depth error" and I don't see why, because I use the condition: cat_obj.parent is not None: -
Heroku app crashes upon first deployment attempt
I've been trying to deploy my workoutcalendar app on heroku. After a lot of progress I finally successfully pushed to heroku master and ran makemigrations and migrate. Unfortunately, when it was time to go to the page and see my beautiful website, I was instead greeted by this: As instructed by the message in my browser, I checked the logs in the hope of finding further information of the error. But all I found was this: 2018-01-15T12:22:54.915142+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=workoutcalendar.herokuapp.com request_id=46d30e9c-d76c-451b-bbb6-ccbfef5efa72 fwd="130.229.155.250" dyno= connect= service= status=503 bytes= protocol=https This doesn't tell me much. The only thing I wonder is why path=/favicon.ico. That's not a url that I've defined on my site. I don't know if that's the reason for the crash. In any case, I wonder if you could tell me how to solve this error, or how to find more information on how to solve it. PS: Some additional info... My requirements.txt: dj-database-url==0.4.2 Django==2.0.1 django-secure==1.0.1 djangorestframework==3.7.1 gunicorn==19.7.1 psycopg2==2.7.3.2 python2==1.2 pytz==2017.2 six==1.10.0 whitenoise==3.3.1 My Procfile: web: gunicorn workoutcalendar.wsgi --log-file - My runtime.txt: python-3.6.4