Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix 500 Internal Server Error in Django application?
I want to deploy a Django application but I have got an 500 Internal Server Error. I have divided deployment process of this app to following parts: local (on my computer), devel (testing behaviour of this app on alive server) and production (final version that can be published for everyone). Here is my settings.py file: """ Django settings for autistic_story project. Generated by 'django-admin startproject' using Django 2.0.4. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import environ import os root = environ.Path(__file__) - 3 # three folder back (/a/b/c/ - 3 = /) env = environ.Env(DEBUG=(bool, False), SECRET_KEY=str, ALLOWED_HOSTS=(list, ['127.0.0.1:8000']), DATABASE_URL=str, ) # set default values and casting environ.Env.read_env() # reading .env file SITE_ROOT = root() # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('SECRET_KEY') # Raises ImproperlyConfigured exception if SECRET_KEY not in os.environ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env('DEBUG') # False if not in os.environ TEMPLATE_DEBUG = DEBUG ALLOWED_HOSTS … -
Custom save method in model form
I have a discussion about this code. I think it works, but someone else says it doesn't work. Actually I can't test it but I don't understand why this should not work. The discussion: Person A: "I'm not sure what your question is, but your custom save logic will never be called, because you always pass commit=False" Me: "I think this should work or did i misunderstood something? Because after t = transaction_profile.save(commit=False) he is calling t.save() and the save() method has commit=True as a default value" Person A: "No. Look at what your save method returns: obj, which is an instance of the model. So t.save() calls the model save, not the form one." views.py def checkout_page(request): session_order_id = request.session['order_id'] if request.POST: transaction_profile = TransactionProfileModelForm(request, request.POST) if transaction_profile.is_valid(): t = transaction_profile.save(commit=False) t.save() else: transaction_profile = TransactionProfileModelForm(request) forms.py from orders.models import Order class TransactionProfileModelForm(forms.ModelForm): email_confirm = forms.EmailField() class Meta: model=TransactionProfile fields = [ 'email', 'email_confirm', 'address_line_1', 'address_line_2', 'city', 'country', 'postal_code', 'state' ] def __init__(self, request, *args, **kwargs): self.request = request super(TransactionProfileModelForm, self).__init__(*args, **kwargs) def save(self, commit=True): obj = super(TransactionProfileModelForm, self).save(commit=False) if commit: obj.save() request = self.request session_order_id = request.session['order_id'] o = Order.objects.get(order_id=session_order_id) o.transaction_profile = obj o.save() return obj -
how to get field type in forms.py (not in template) Django
I want to get a specific field type in the forms.py, so I can add to that fields group a specific CSS class. In my models.py I have multiple CharField, DateField and others like BigIntegerField, etc., and I want to ask for that. Here's my code: forms.py class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) for field in self.fields: if type(field) == CharField: #Here's the problem self.fields[field].widget.attrs.update({ 'class': 'form-control'}) class Meta: model = MyModel fields = '__all__' I can't do it one by one because I have many fields in my model. Any ideas how can I do that? Thanks a lot. -
Add Font Awesome icon with label_tag
How do I add a Font Awesome icon like <i class="fa fa-calendar"></i> to the following {{form.date.label_tag}} which uses widget_tweaks? I know generally you'd just do it like this <h2><span>Add<i class="fa fa-plus"></i></span></h2> but I haven't had any luck. -
iterating over a queryset and replacing foreign keys with their related objects django rest framework
I have the following models: class STUser(AbstractBaseUser): email = models.EmailField(unique=True) name = models.CharField(max_length=255) ... class VenuePermissions(models.Model): user = models.ForeignKey(STUser, on_delete=models.CASCADE) venue = models.ForeignKey(Venue, on_delete=models.CASCADE, blank=True, null=True) ... class Venue(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=1500, null=True, blank=True) ... I am then prefetching the related venuepermission objects to a STUser object in a view class VenueUserList(APIView): def get(self, request, *args, **kwargs): objects = STUser.objects.prefetch_related('venuepermissions_set').all() ... Then I want to take the returned query set and replace the venue FKs with their objects. for item in objects: for permission in item_venuepermissions_set: permission_venue = Venue.objects.get(pk=permission_venue) print(repr(objects)) ... return Response({}) but my approach is clearly wrong. how do I properly access a field of a queryset and change its value? As you can see I need to do it twice. Once to access the current objects permission_set and again to access that permission_set venue field and override it. I do not want any of this changing the database. This is just to return the values. -
How to sum only selected rows from a list
I have a grid with some itens and i´d like to sum val_itemservico column from selected rows. My template sum all rows. I´d like to sum val_itemservico column only for selected rows when I click on "Calcular" button. In this case, I need to know if ind_selecionado column is checked. So, how can i do that? HTML: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ORÇAMENTO</title> </head> <h2>ORÇAMENTO</h2> <form class=" bd-form-20 " action="#" name="form-name" method="GET"> {% csrf_token %} <label>Serviço: </label>{{filter.form.servico}} <button type = "submit" >OK</button> <br><br> </form> <tbody> <div class=" bd-customhtml-29 bd-tagstyles bd-custom-table"> <div class="bd-container-inner bd-content-element"> <table id="table" border="1" rules="all" cellspacing="0" cellpadding="10"> <!--width="100%" border="0" cellspacing="0" cellpadding="2">--> <tr> <th>Selecionar</th> <th>ID Item Serviço</th> <th>Item Serviço</th> <th>Valor Serviço</th> <th>Serviço</th> </tr> {% for item in response.object_list %} <tr> <td> <input type="checkbox" id="item.ind_selecionado"></td> <td>{{ item.id }}</td> <td>{{ item.desc_itemservico }}</td> <td>{{ item.val_itemservico }}</td> <td>{{ item.servico_id}}</td> </tr> {% endfor %} {% if response.object_list %} Total: {{ response.object_list|length }} {% endif %} <br><br> </table> <br><br> Valores:<br> {% for item in response.object_list %} {{item.val_itemservico}}<br> {% endfor %} <br><br> <span id="sumV"></span> <script> var table = document.getElementById("table"); getSum(); function getSum() { var sumVal = 0; for (var i = 1; i < table.rows.length; i++){ sumVal = sumVal + parseInt(table.rows[i].cells[3].innerHTML); } console.log("Sum: " … -
Django makemigrations gives exception after I changed the type of a field to a custom type
I had something like this class modelEmployee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) employee_image = models.ImageField(upload_to='images/',null=True,blank=True,default='images/') Then I replaced the employee_image with this type instead class modelEmployee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) employee_image = Base64Field() I got the Base64Field from here.Thats what it looks like class Base64Field(models.TextField): def contribute_to_class(self, cls, name): if self.db_column is None: self.db_column = name self.field_name = name + '_base64' super(Base64Field, self).contribute_to_class(cls, self.field_name) setattr(cls, name, property(self.get_data, self.set_data)) def get_data(self, obj): return base64.decodestring(getattr(obj, self.field_name)) def set_data(self, obj, data): setattr(obj, self.field_name, base64.encodestring(data)) However after changing the type and running makemigrations. I get the error Traceback (most recent call last): File "/Users/admin/Development/foo/virtual/lib/python3.5/site-packages/django/db/models/options.py", line 566, in get_field return self.fields_map[field_name] KeyError: 'employee_image_base64' Any suggestions on how I can fix this ? -
Sessions Django: Daphne + Uwgsi
I am currently deploying a django project using channel 2.x with uwgsi for http requests and daphne for background tasks. Daphne by itself is running correctly as well as uwgsi. Configuration for both is the following: location /stream { # daphne server running on port 8001 so we set a proxy to that url proxy_pass http://0.0.0.0:8001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } # These requests are handled by uwsgi location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/app/project/socket; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # Make the following two variables accessible to the application: uwsgi_param SSL_CLIENT_VERIFY $ssl_client_verify; uwsgi_param SSL_CLIENT_RAW_CERT $ssl_client_raw_cert; } All background workers are preceded by /stream. All endpoints server via / and /stream are protected. When login in and accesing endpoints such as /api/v1/resource it correctly returns the data but when triggering tasks via /stream I get permission denied (403). Debugging this behavior I have come to the conclusion that sessions are not persisted among Daphne and Uwsgi. How can I achieve sessions to be shared between them? -
Group by select related objects django, django rest framework
I have the following models: class STUser(AbstractBaseUser): email = models.EmailField(unique=True) name = models.CharField(max_length=255) companyname = models.CharField(max_length=200, blank=True, null=True) ... class VenuePermissions(models.Model): user = models.ForeignKey(STUser, on_delete=models.CASCADE) venue = models.ForeignKey(Venue, on_delete=models.CASCADE) signupvaildatestring = models.CharField(max_length=200, blank=True, null=True) ... And I wanted to create a query that gets all the venuepermissions but instead of a user pk and a venue pk it returns the user and venue objects. here is the view and serializer I am using a generic class VenueUserList(ListAPIView): serializer_class = VenueUserListSerializer queryset = VenuePermissions.objects.select_related('user').select_related('venue').filter(signupvaildatestring=None) class VenueUserListSerializer(serializers.ModelSerializer): user = UserSerializer() venue = VenueSerializer() class Meta: model = VenuePermissions fields = ('user', 'venue', 'isvenueviewer', 'isvenueeventplanner', 'isvenueadministrator') now this returns all the venue permissions but if a user has multiple venues they have a permission on the view will return multiple objects of that user. so user with pk of 1 has three venues they have permissions on. You will see a 3 full venuepermission objects with user of pk 1 I would like to group these venuepermissions by user. I know the django ORM command is annotate https://simpleisbetterthancomplex.com/tutorial/2016/12/06/how-to-create-group-by-queries.html https://docs.djangoproject.com/en/1.11/topics/db/aggregation/#aggregating-annotations but I am not sure how to add that to my query. -
Summernote to save images in folders - Django Project
I have summer note setup in Django 2.0 and images are saved in a base64 format in the database.My Django project is set up to save my images in AWS S3 bucket. I would like to set up summer note uploaded images to be saved into S3 bucket or file system. Any tips or ideas on how I can achieve this? $(document).ready(function(){ $('#summernote').summernote({ placeholder: 'Hello bootstrap 4', tabsize: 2, height: 600 }); }); -
Django server in a Docker
I'm starting to develop an application with a Django back-end, and I wish to do it inside a Docker. I almost managed to do it, but I'm still having an issue. Currently I have two containers running : The first one contains my django app and the complete command is python3 manage.py runserver 0.0.0.0:8000 and the second one is hosting my database. My docker-compose.yml file is this one : version: '3' services: db: image: mysql:5.7 environment: MYSQL_ROOT_PASSWORD : root MYSQL_DATABASE : ml_gui back: build: ./back/ command: python3 manage.py runserver ports: - "8000:8000" depends_on: - db and my django settings concerning the database is : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'ml_gui', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'db', 'PORT': '3306', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", }, 'TEST': { 'CHARSET': 'utf8', 'COLLATION': 'utf8_general_ci', }, }, } The probleme is, when I do requests outside of the container (I've tried in my browser, with curl and with POSTMAN) on localhost:8000, I have no answer. But, when I do the same request inside the container with curl, it works. So my question is, how could I make those requests work from outside of the containers ? Thanks in advance -
django exception: Reverse for 'comment_new' with keyword arguments '{'pk': ''}' not found
im quite new to python/Django and i currently want to implement that every of my blogposts can have a comment. but i dont get the trick. i created everything the same way as for my post model expect that i Exception Type: NoReverseMatch Exception Value: Reverse for 'comment_new' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['comment/new/$'] urls.py: from django.conf.urls import url from django.contrib import admin from . import views urlpatterns = [ url(r'^admin/', (admin.site.urls)), url(r'^$', views.post_list, name='post_list'), url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'), url(r'^post/new/$', views.post_new, name='post_new'), url(r'^post/(?P<pk>\d+)/edit/$', views.post_edit, name='post_edit'), url(r'^comment/new/$', views.comment_new, name='comment_new'), url(r'^comment/(?P<pk>\d+)/edit/$', views.comment_edit, name='comment_edit'), ] views.py: def comment_edit(request, pk): comment = get_object_or_404(Comment, pk=pk) if request.method == "POST": form = PostForm(request.POST, instance=comment) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.published_date = timezone.now() comment.save() return redirect('post_detail', pk=comment.pk) else: form = PostForm(instance=comment) return render(request, 'quickblog/comment_edit.html', {'form': form}) def comment_new(request): if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.published_date = timezone.now() comment.save() return redirect('post_detail', pk=comment.pk) else: form = CommentForm() return render(request, 'quickblog/comment_new.html', {'form': form}) post_detail.html: {% block comment %} <div class="comment"> <p>{{ comment.text|linebreaksbr }}</p> {% if comment.published_date %} <div class="date"> <a>Published at: {{ comment.published_date }}</a> </div> {% endif %} {% if user.is_authenticated %} <a class="btn … -
CSS config in statisc folder django in beanstalk
I have created and deployed my project locally and then migrated to AWS under the service beanstalk. Everything goes well regarding the web server running. However, the style files CSS in my HTML are not being binded. This is my folder structure for the web project with the application course: I call the CSS configurations in my HTML like : <!DOCTYPE html> <{% load static %}> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="{% static 'course/signup.css' %}" type="text/css" /> <!link rel="stylesheet" href="signup.css" type="text/css" /> <title>English for Kinds</title> </head> The current reference to static files in my manage.py is: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' I would like to know how to handle the references to my static folder with CSS in Beanstalk. thanks so much -
Register and login api with django rest
How to make register and login api with one to one model user detail with django rest? -
Error Running Django tutorial : Page not found
I am facing trouble while running the tutorial for Django. I have attached the error details and the complete code. I am using python 3.x, django 2.0.x with anaconda distribution on python. error details -
How do I set up a development environment that is identical to the pythonanywhere production environment?
I'm trying to set up a development environment that is identical to the pythonanywhere live (production) environment. I uploaded a basic test site an discovered I have to change a few settings when I upload which I would definitely forget to do sometime. Ideally what i'd like to do is run a script from my command line that would create a fresh development environment for me to work with that completes all the setup tasks in one go, for example; set up a virtual environment, install all dependencies. My questions are: What do I need to set up? I'm working with django, so far I would have; set up virtual environment, install all dependencies (django and all the other things i would normally work with), potentially create all my project files and set up databases (if i didn't want a blank slate) Can someone point me in the right direction to find out how to do this? Thanks in advance. -
Trying to allow users to edit Django
I'm trying to make it so users can edit articles that they created. I feel like I'm close, but can't quite bridge the gap of what I've done and what I need to do. template on the article detail page: {% if request.user == article.author %} <p> <a href="{% url 'articles:edit_article' %}" Edit article </a> </p> {% endif %} This seems to work okay. urls.py: url(r'^(?P<slug>[\w-]+)/$', views.article_detail, name="detail"), url(r'^(?P<slug>[\w-]+)/edit/$', views.edit_article, name="edit_article"), views.py: def edit_article(request): if request.method == 'POST': form = forms.EditArticle(request.POST, slug=request.slug) if form.is_valid(): form.save() return redirect('articles:list') else: form = forms.EditArticle(slug=request.slug) args = {'form': form} return render(request, 'articles/edit_article.html', args) forms.py class EditArticle(forms.ModelForm): class Meta: model = models.Article fields = ( 'title', 'body', 'slug', 'thumb' ) And edit_article.html: {% extends 'base_layout.html' %} {% block content %} <h1>Edit Article {{ article.title }}</h1> <div class="profile"> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Update Profile</button> </form> </div> {% endblock %} Here's the traceback: Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users.........\articles\views.py" in article_detail 18. return render(request, "articles/article_detail.html", {'article':article}) File "C:\Python27\lib\site-packages\django\shortcuts.py" in render 30. content = loader.render_to_string(template_name, context, request, using=using) File … -
Prod server serving files only when debug turned on- Django
I am trying to serve dynamically created files on my Django server. The code works fine and serves the image file in my local server. It also works and serves the image file in Production server but only when I set debug to True in Prod server. But when I set debug to False in Prod Server, I get file not found error (in console): GET http://thesitename/media/imgs/img.png 404 (Not Found) my settings.py looks like this: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "frontend/media/") urls.py looks like this: app_name = 'frontend' urlpatterns = [ ###urls### ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Views.py looks like this: def template_page(request, loation, par, date): ### generating image using pil here ### pil_image.save("frontend/media/imgs/img.png”) path_to_image_passing_to_template = “/media/imgs/img.png” params = { 'path_to_image_passing_to_template' : path_to_image_passing_to_template } return render(request, 'frontend/template_page.html', params) html looks like this: <img src="{{path_to_image_passing_to_template}}" /> and file structure is like this: /backend urls.py views.py /frontend /static /media /imgs /templates /frontend urls.py views.py /thesite settings.py urls.py wsgi.py /static I don't understand why it should work with debug turned on in prod server and not otherwise!!! I have looked at several questions but did not find any query close to this kind of issue. I took … -
How to setup django-celery-beat with multi tenant (django-tenant-schemas) Django application.
I am trying to run celery beat along with celery. Celery works fine with my multitenant Django application (using django-tenant-schemas) with the help of tenant_schemas_celery. But I am not able to run the celery beat as all the scheduled task/periodic task related tables are tenant-specific hence not able to start the celery beat. Error trace: celery@Amits-iMac.local v4.0.2 (latentcall) Darwin-17.5.0-x86_64-i386-64bit 2018-05-04 18:20:22 [config] .> app: __main__:0x102ef9f28 .> transport: amqp://guest:**@localhost:5672// .> results: .> concurrency: 4 (prefork) .> task events: ON [queues] .> celery exchange=celery(direct) key=celery [tasks] . dataflow.tasks.launch_dataflow . datasession.tasks.launch_copy [2018-05-04 18:20:23,035: INFO/Beat] beat: Starting... [2018-05-04 18:20:23,166: ERROR/Beat] Process Beat Traceback (most recent call last): File "/Users/amit/koolanch-dev/dev-1/lib/python3.6/site-packages/kombu/utils/objects.py", line 42, in __get__ return obj.__dict__[self.__name__] KeyError: 'scheduler' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/amit/koolanch-dev/dev-1/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "django_celery_beat_periodictask" does not exist LINE 1: ...ango_celery_beat_periodictask"."description" FROM "django_ce... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/amit/koolanch-dev/dev-1/lib/python3.6/site-packages/billiard/process.py", line 306, in _bootstrap self.run() File "/Users/amit/koolanch-dev/dev-1/lib/python3.6/site-packages/celery/beat.py", line 613, in run self.service.start(embedded_process=True) File "/Users/amit/koolanch-dev/dev-1/lib/python3.6/site-packages/celery/beat.py", line 528, in start humanize_seconds(self.scheduler.max_interval)) File "/Users/amit/koolanch-dev/dev-1/lib/python3.6/site-packages/kombu/utils/objects.py", line 44, in __get__ value = obj.__dict__[self.__name__] = self.__get(obj) File "/Users/amit/koolanch-dev/dev-1/lib/python3.6/site-packages/celery/beat.py", line 572, … -
Django: Passing request to my modely.py
in order to generate the full url in the email I send to the ticket purchaser, I have to access get_current_site in my models.py. To do so I pass request like this: get_absolute_url(request) Is there anything wrong in doing it that way, or would you consider this as good code/approach? def checkout_page(request): [...] #Send email subject = render_to_string('checkout/email/your_ticket_subject.txt', {}) to_email = [transaction_profile.cleaned_data['email'],] email_ticket_link = t.get_absolute_url(request, email=True) content = render_to_string('checkout/email/your_ticket_message.txt', {'email_ticket_link': email_ticket_link,}) send_mail(subject, content, settings.DEFAULT_FROM_EMAIL, to_email) ticket_link = t.get_absolute_url(request) return redirect(ticket_link) models.py class TicketPurchase(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) #change CASCADE ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) #change CASCADE ticketpurchase_id = models.CharField(max_length=10, unique=True) refunded = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) def get_absolute_url(self, request, email=False): ticket_link = reverse("ticketsgenerator:show_tickets", kwargs={"order_id": self.order.order_id, "customer_key": self.order.customer_key} ) if email: current_site = get_current_site(request) return 'https://{}{}'.format(current_site, ticket_link) return ticket_link -
Filtering LogsEntry
Im trying to run this Queryset in Django to the model LogEntry. logs_entry = LogEntry.objects.filter(content_type_id = ContentType.objects.get_for_model(Regime).pk, object_id__in = user_regimes.values_list('id', flat = True)) But throws this error : You might need to add explicit type casts. What kind of cast can i use? to make it works. Thanks C; -
print a python function that takes arguments
How do I print out a function that takes arguments? This is my function but it takes args and I tried to call the function with market and items as my params but it says market is not defined def parse_runners(market , items): """Parses runners from MarketCatalogue object""" runners = [] for runner_item in items: num = runner_item['metadata'].get('CLOTH_NUMBER') if not num: matches = re.match(r'^(\d+)' , runner_item['runnerName']) if matches: num = matches.groups(0)[0] else: logger.error(f'Could not match number for {runner_item}') runner , created = Runner.objects.update_or_create( selection_id=runner_item['selectionId'] , defaults={ 'market': market , # default 'name': runner_item['runnerName'].upper() , 'sort_priority': runner_item['sortPriority'] , 'handicap': runner_item['handicap'] , # metadata 'cloth_number': num , 'stall_draw': runner_item['metadata'].get('STALL_DRAW') , 'runner_id': runner_item['metadata']['runnerId'] , } ) if created: logger.info(f'Created {runner}') else: logger.debug(f'Updated {runner}') runners.append(runner) return runners parse_runners(market, items) -
Django Models: Attribute name assignment for names that differ only by a number
I have this model (whose purpose is to hold data): class UserPhraseDatum(models.Model): result_from = models.ForeignKey(Results, related_name="data") phrase = models.ForeignKey(Sound) score = models.DecimalField(max_digits=5, decimal_places=4) snr = models.PositiveSmallIntegerField() m_energy_1 = models.PositiveSmallIntegerField() m_energy_2 = models.PositiveSmallIntegerField() m_energy_3 = models.PositiveSmallIntegerField() m_energy_4 = models.PositiveSmallIntegerField() m_energy_5 = models.PositiveSmallIntegerField() m_energy_6 = models.PositiveSmallIntegerField() m_energy_7 = models.PositiveSmallIntegerField() u_energy_1 = models.PositiveSmallIntegerField() u_energy_2 = models.PositiveSmallIntegerField() u_energy_3 = models.PositiveSmallIntegerField() u_energy_4 = models.PositiveSmallIntegerField() u_energy_5 = models.PositiveSmallIntegerField() u_energy_6 = models.PositiveSmallIntegerField() u_energy_7 = models.PositiveSmallIntegerField() Eventually the info in these instances will be analyzed in R, and possibly spat out to a CSV. There will always be 6 entries for m_energy and 6 entries for u_energy. Is there a nicer way to assign these? -
Django: how to use fk on reverse inline
I have the following models: models.py class Tipo_mundo(models.Model): nome_tipo_mundo = models.CharField(max_length=80) descricao_tipo_mundo = models.TextField(max_length=600) class Mundo(models.Model): nome_mundo = models.CharField(max_length=80) descricao_mundo = models.CharField(max_length=200) atividades = models.ManyToManyField(Atividade, through='Jornada', related_name='mundos') tipo_mundo = models.ForeignKey(Tipo_mundo, on_delete=models.DO_NOTHING, related_name='mundos') and i want to put Mundo inside the Tipo_mundo admin edit page. As an inline to add as many Mundo's as i want. Refering to the list of Mundos already created. I want to create and edit just like a normal inline when i put admins like: admin.py class MundoInline(admin.StackedInline): model = Mundo extra = 1 class TipoMundoAdmin(admin.ModelAdmin): form = TipoMundoModelForm list_display = ('nome_tipo_mundo', 'descricao_tipo_mundo') inlines = [MundoInline,] i get: do not want it i want: something like this how can i do this??? -
ReactJS is no Rendering Component
I took this all from this example. Creating a React Login Page So I cannot take any credit. However, this page works fine. I am trying to retro fit it to pushing a React Video Player page. My code is as follows (Snippet from Axios Post): if (response.status == 200) { console.log("Login successfull"); var videoPlayer = []; this.setState( {isLoggedIn : true }); videoPlayer.push(<Videoplayer appContext={self.props.appContext} parentContext={this} />); self.props.appContext.setState({loginPage: [], videoPlayer: videoPlayer}); The existing code was this: var uploadScreen=[]; uploadScreen.push(<UploadScreen appContext={self.props.appContext}/>); self.props.appContext.setState({loginPage: [], uploadScreen: uploadScreen}) My code does not render the VideoPlayer Page and that code is from the standard example at this github ReactJS Video Player I have a feeling that it has to do with Context but I don't know enough about React or how to debug this using the Chrome tools. My backend is Django. I'm almost thinking of going back to using Jquery so I can get pages at least functioning but wanted to try and learn React. Any help would be great. The code above is just testing code so I could get some thing functional.