Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Whats the recommended way to update every instance of a source model when a new target instance is created in a manytomany model?
I have a website where I want to display a basic html table like so: Product_Name | Attribute_1 | Attribute_2 ----------------------------------------- Soap | True | True Shampoo | False | True So I have created the classes Product and Attribute with a ManyToMany relationship. Models.py class Product(models.Model): name = models.CharField(max_length=10) attributes = models.ManyToManyField(on_delete='CASCADE') class Attribute(models.Model): name = models.CharField(max_length=1, default='N') So I have two Attribute instances - Attribute_1 and Attribute_2. When I create a new attribute (Attribute_3), is there a way I can update the relationships of all of my Product instances with a link to the new Attribute? I know that Django creates a through table for m2m relationships. According to the docs, I know I can do something like: for prod_obj in Product.objects.all(): prod_obj.add(new_attribute_object) But how do I ensure this happens automatically/consistently every time I create an attribute object? -
Trying to get location_profile to show location.name in __str__ (django)
I have the following 2 models: class LocationProfile(models.Model): units = models.CharField(max_length=100,blank=True) location_notes = models.TextField(blank=True) is_occupied = models.BooleanField(default=False) def __str__(self): return self.location.name class Location(models.Model): organization = models.ForeignKey(Organization, on_delete=None) location_profile = models.OneToOneField(LocationProfile, on_delete=None) name = models.CharField(max_length=255) address1 = models.CharField(max_length=100) def __str__(self): return self.name And I am trying to get LocationProfile to show the name of the Location but the error is: LocationProfile has no location. Each Location has 1 Location Profile, and if possible, I would like to be able to select the Location Profile from the Location dropdown in the django admin (as opposed to going to Location Profile and selecting the Location.) -
Override imported class variables - django/python
I need to override variables (or pass dynamic data) to imported class. filters.py import django_filters from .models import Gate, Tram, OperationArea, Bogie from distutils.util import strtobool from django import forms class GateFilter(django_filters.FilterSet): # Prepare dynamic lists with choices tram_list = [(id, number) for id, number in Tram.objects.all().values_list('id', 'number')] bogie_list = [(id, number) for id, number in Bogie.objects.all().values_list('id', 'number')] area_list = [(id, area) for id, area in OperationArea.objects.all().values_list('id', 'area')] # Generate fields tram = django_filters.MultipleChoiceFilter(choices=tram_list, label=u'Tramwaj') car = django_filters.MultipleChoiceFilter(choices=Gate.CAR_SYMBOLS, label=u'Człon') bogie = django_filters.MultipleChoiceFilter(choices=bogie_list, label=u'Wózek') bogie_type = django_filters.MultipleChoiceFilter(choices=Gate.BOGIE_TYPES, label=u'Typ wózka') area = django_filters.MultipleChoiceFilter(choices=area_list, label=u'Obszar') operation_no = django_filters.CharFilter(label=u'Numer operacji', widget=forms.TextInput(attrs={'size': '16px'})) status = django_filters.MultipleChoiceFilter(choices=Gate.GATE_STATUSES, label=u'Status') rating = django_filters.MultipleChoiceFilter(choices=Gate.GATE_GRADES, label=u'Ocena') class Meta: pass views.py from .filters import GateFilter class GateListView(generic.ListView): queryset = None gate_type = None template_name = 'qapp/gate/list.html' context_object_name = 'gate_list' paginate_by = 20 def get_queryset(self): # Type is stored in database as big-letter word, so 'bjc' != 'BJC'. if self.gate_type.upper() == 'BJW': ordering = ['bogie', 'bogie_type'] else: ordering = ['tram', 'car'] queryset = Gate.objects.filter(type=self.gate_type.upper()).order_by(*ordering) self.gate_list = GateFilter(self.request.GET, queryset=queryset) return self.gate_list.qs.distinct() def get_context_data(self, **kwargs): context = super(GateListView, self).get_context_data(**kwargs) # Return Gate.type to template. context['gate_type'] = self.gate_type # Return object (for generating form) to template. context['gate_list_filter'] = self.gate_list return context As you can see, … -
How to override Django widget functions (Froala Editor)?
I was wondering how I can override the functions render and trigger_froala in Django. Can I create my own widget which overrides the two functions? from django.forms import widgets, Media from django.utils.safestring import mark_safe from django.conf import settings import json from . import PLUGINS, PLUGINS_WITH_CSS, THIRD_PARTY, THIRD_PARTY_WITH_CSS try: from django.urls import NoReverseMatch, reverse except ImportError: from django.core.urlresolvers import reverse, NoReverseMatch class FroalaEditor(widgets.Textarea): def __init__(self, *args, **kwargs): self.options = kwargs.pop('options', {}) self.plugins = kwargs.pop('plugins', getattr(settings, 'FROALA_EDITOR_PLUGINS', PLUGINS)) self.third_party = kwargs.pop('third_party', getattr(settings, 'FROALA_EDITOR_THIRD_PARTY', THIRD_PARTY)) self.theme = kwargs.pop('theme', getattr(settings, 'FROALA_EDITOR_THEME', None)) self.include_jquery = kwargs.pop('include_jquery', getattr(settings, 'FROALA_INCLUDE_JQUERY', True)) self.image_upload = kwargs.pop('image_upload', True) self.file_upload = kwargs.pop('file_upload', True) self.language = (getattr(settings, 'FROALA_EDITOR_OPTIONS', {})).get('language', '') super(FroalaEditor, self).__init__(*args, **kwargs) def render(self, name, value, attrs=None, renderer=None): html = super(FroalaEditor, self).render(name, value, attrs) el_id = self.build_attrs(attrs).get('id') html += self.trigger_froala(el_id, self.get_options()) return mark_safe(html) def trigger_froala(self, el_id, options): str = """ <script> $(function(){ $('#%s').froalaEditor(%s) }); </script>""" % (el_id, options) return str -
A form field with a models foreign key to another model, showing fields by criteria. Django
I am trying to add a field for my form that will return 'business hours' only on that day. My model has many foreign-key relationships with other models and looks like this: class DayTime(models.Model): day_of_week = models.ForeignKey(WorkTime, on_delete=models.CASCADE) day_name = models.CharField(max_length=30) full_time = models.BooleanField(default=None) def __str__(self): return self.day_name class Time(models.Model): day_time = models.ForeignKey(DayTime, on_delete=models.CASCADE) compartment = models.CharField(max_length=11) free_or_no = models.BooleanField(default=True) time_equivalent = models.IntegerField() def __str__(self): return self.compartment class OrderingMassage(models.Model): massage_product = models.OneToOneField(Product, on_delete=models.CASCADE) masseurs = models.OneToOneField(Masseurs, on_delete=models.CASCADE) day_week = models.CharField(max_length=15, choices=DAY_OF_WEEK, default=date.today, blank=True) time = models.OneToOneField(Time, on_delete=models.CASCADE) place = models.OneToOneField(PlaceMassage, on_delete=models.CASCADE) payment_method = models.CharField(max_length=1, choices=PAYMENT_METHODS, default='G') name = models.CharField(max_length=50) surname = models.CharField(max_length=50) e_mail = models.EmailField() additional_requests = models.TextField() phone_number = models.CharField(max_length=15) reminder_visit = models.BooleanField(default=None) website_rules = models.BooleanField(default=None) In the form I added a field ['time'] which should be searched according to my query. But I'm getting an error: OrderingMassageForm 'object has no attribute' fields '' forms.py class OrderingMassageForm(forms.ModelForm): class Meta: model = OrderingMassage fields = ('massage_product', 'masseurs', 'day_week', 'time', 'place', 'payment_method', 'name', 'surname', ) def __init__(self, *args, **kwargs): super(OrderingMassageForm).__init__(*args, **kwargs) self.fields['time'].queryset = Time.objects.filter(day_time__day_name='Sunday') admin What can I do wrong and how can I fix my mistake? any help will be appreciated. -
Django objects.update_or_create
i have a periodic_task running in celery that query for latest Cryptocurrency prices but for some reason, each time a want to display the data i dont get updated records i just get new ones and the old records are keep for some reason. tasks.py @periodic_task(run_every=(crontab(minute='*/1')), name="Update Crypto rate(s)", ignore_result=True) def get_exchange_rate(): api_url = "https://api.coinmarketcap.com/v1/ticker/" try: exchange_rates = requests.get(api_url).json() for exchange_rate in exchange_rates: CryptoPrices.objects.update_or_create(key=exchange_rate['id'], symbol=exchange_rate['symbol'], market_cap_usd=round(float(exchange_rate['market_cap_usd']), 3), volume_usd_24h=round(float(exchange_rate['24h_volume_usd']), 3), defaults={'value': round(float(exchange_rate['price_usd']), 3)} ) logger.info("Crypto exchange rate(s) updated successfully.") except Exception as e: print(e) models.py class CryptoPrices(models.Model): key = models.CharField(max_length=255) value = models.CharField(max_length=255) symbol = models.CharField(max_length=255) volume_usd_24h = models.CharField(max_length=255) market_cap_usd = models.CharField(max_length=255) views.py def crypto_ticker(request): list_prices = CryptoPrices.objects.get_queryset().order_by('pk') paginator = Paginator(list_prices, 100) # Show 100 prices per page page = request.GET.get('page') price = paginator.get_page(page) return render(request, 'crypto_ticker.html', {'price': price}) template.html: {% extends 'base.html' %} {% load readmore %} {% block breadcrumbs %} {{ block.super }} » <a href="{% url 'post_list' %}">Posts </a> » <a href="{% url 'crypto_ticker' %}">Crypto ticker</a> {% endblock %} {% block content %} <!DOCTYPE html> <html> <head> <title>Crypto ticker</title> </head> <body> <h1 class="center">Crypto ticker</h1> <hr class="hr-style"> <div class="center"> <h4>{{ prices }} Here you can find all frequently asked questions <br> if you still have still have any open … -
Django unsupported language integration
In my django app I want to integrate Armenian language, which is currently unsupported. I have followed all the suggested steps in other links, but I get ValueError: plural forms expression could be dangerous. But for example for supported languages like German everything works fine. Please send me a working example. -
Django REST framework: Token Authentication doesn't work on production
I'm creating API using Django REST framework and trying to connect my mobile app to web API. I didn't have any problems with local environment. However, after I deployed API into elastic beanstalk and tried with production url, I can never successful. API always returns 401. I was successful in registering the user's account and token is correct and also endpoints that doesn't require authentication works as expected but I cannot authenticate the user on production environment. Error log just say 401. What is the cause of error possibly? Anyone who has encountered the similar issue? I have no idea how I can find the cause of this kind of error. -
I can't access to details of my 'products' app
I have two apps on my Django project : products and blog . everything works correctly but in my list of the products : /products/ where the titles of the products are in, when i click on the title i stay on the same page: /products . But when I go directly to products/1 or products/2 it works . product_list.html : {% extends 'base.html' %} {% block content %} {% for instance in object_list %} <p>{{ instance.id }} - <a href="{{ instance.get_absolute_url }}"> {{ instance.title }}</a> </p> {% endfor %} {% endblock %} models.py : from django.db import models from django.urls import reverse class Product(models.Model) : title = models.CharField(max_length=130) description = models.TextField(blank=True,null=True) price = models.DecimalField(max_digits=5,decimal_places=2) summary = models.TextField() Featured = models.BooleanField(default=False) def get_absolute_url(self,id): return reverse("products : product_detail",kwargs={"id":self.id}) urls : from django.contrib import admin from django.urls import path from products.views import ( product_detail_view , product_create_view , product_delete_view , product_list_view , product_update_view , ) app_name = 'products' urlpatterns = [ path('<int:id>/', product_detail_view, name='product_detail'), path('create/', product_create_view, name='product_create'), path('<int:id>/delete/', product_delete_view, name='product_delete'), path('', product_list_view, name='product_list'), path('<int:id>/update/', product_update_view, name='product_update'), ] Any help ? -
Django 2: Multiple slugs in url
I am currently following a django tutorial by sentdex. The tutorial is making a clone of https://pythonprogramming.net/. In the tutorial he uses only one slug in the url, but i think its more convenient to have multiple slugs beacause the urls will be more organized. For example, a link to a tutorial on pythonprogramming.net looks like this: https://pythonprogramming.net/build-supercomputer-raspberry-pi/. What i want it to look like on my project is mydomain.com/data-analsyis/build-supercomputer/1/. The url would be domain/category/series/episode/, instead of domain/episode/. # urls.py from django.urls import path from . import views app_name = "main" urlpatterns = [ path('', views.homepage, name="homepage"), # View categories path("register/", views.register, name="register"), path("logout/", views.logout_request, name="logout"), path("login/", views.login_request, name="login"), path("<slug:series_slug>/", views.slugs, name="series_blocks"), # Views all the series in that category path("<slug:series_slug>/<slug:tutorial_slug>/", views.slugs, name="tutorial_blocks"), # View all tutorials in series path("<slug:series_slug>/<slug:tutorial_slug>/<int:id>/", views.slugs, name="tutorial_blocks"), # View spesific tutorial nr. ] Note: I think it's better to have 3 different functions than the views.slug # Models.py from django.db import models from datetime import datetime class TutorialCategory(models.Model): category = models.CharField(max_length=100) summary = models.CharField(max_length=200) slug = models.CharField(max_length=100) class Meta: verbose_name_plural = "Kategorier" def __str__(self): return self.category class TutorialSeries(models.Model): series = models.CharField(max_length=200) category = models.ForeignKey(TutorialCategory, default=1, verbose_name="Kategori", on_delete=models.SET_DEFAULT) summary = models.CharField(max_length=200) slug = models.CharField(max_length=100) # Not … -
Blogs disappear when post is liked
the code is working without any issues but the problem is that after I like a post instead of the like button changing the entire for loop having the posts stops functioning. ie there is nothing displayed other than the users username. The server doesn't throw any particular error it just doesn't display the for loop. I feel its an issue with the render part but I'm not quite sure what exactly is wrong with it below are my files views.py from django.shortcuts import render,get_object_or_404 from django.views.generic import ListView from .models import Blog from django.http import HttpResponseRedirect class BlogsList(ListView): model=Blog template_name='blog/home.html' context_object_name='blogs' ordering=['-date_posted'] def like_post(request, blog_id): post = get_object_or_404(Blog, id=blog_id) is_liked=False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked=False else: post.likes.add(request.user) is_liked=True context={ 'is_liked':is_liked } return render(request, 'blog/home.html', context) models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Blog(models.Model): title=models.CharField(max_length=100) content=models.TextField() date_posted=models.DateTimeField(default=timezone.now) author=models.ForeignKey(User, on_delete=models.CASCADE) likes=models.ManyToManyField(User,related_name='likes',blank=True) def __str__(self): return self.title def get_absolute_url(): return reverse('blog-home') urls.py from django.urls import path from . import views urlpatterns=[ path('',views.BlogsList.as_view(),name='blog-home'), path('<int:blog_id>/like/', views.like_post, name='like_post') ] and home.html {{ user.username }} {% block content %} {% for post in blogs %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> <div class="media-body"> <div … -
My jinja if condition in my HTML is not working
In my html I have a checkbox. I registered and ticked the checkbox. I can see from admin panel the checkbox is true. But my 'if' condition in my HTML is not working. It should show only 1 item from my database when checkbox condition is True, else it should show several items. I tried to write another if condition in my views.py but still my code is not working. my views.py def address(request, pk): user = User.objects.all() city = Post.objects.get(id=pk).city address = Post.objects.filter(city=city) email = Post.objects.all() context = { 'user': user, 'address': address, 'city': city, } return render(request, 'users/address.html', context) my models.py: class User(AbstractUser): first_name = models.CharField(verbose_name="First name", max_length=255) last_name = models.CharField(verbose_name="First name", max_length=255) country = models.CharField(verbose_name="Country name", max_length=255) city = models.CharField(verbose_name="City name", max_length=255) email = models.EmailField(verbose_name="Email", max_length=255) access_challenge = models.BooleanField(default=False) def __str__(self): return self.username class Post(models.Model): title = models.CharField(max_length=255) country = models.CharField(max_length=255) city = models.CharField(max_length=255) address = models.CharField(max_length=255) email = models.EmailField(max_length=255) phone = models.CharField(max_length=255) website = models.URLField(max_length=255) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('users:blog') my html: {% extends 'shared/base.html' %} {% load staticfiles %} {% block content %} <div class="content-section p-5 mt-5 pl-4"> <h1 class="text-center text-uppercase">{{ city }}</h1> {% for … -
Django Rest Framework - perform Put request by passing a JSON object instead of just ID
I'm working on a Project using Python(3), Django(1.11) and DRF(3.6) in which I have to perform a PUT request by passing a nested nested instead of an ID. Here's What I have tried: models.py: class EventModel(models.Model): id = models.CharField(primary_key=True, max_length=255) type = models.CharField(max_length=255) actor = jsonfield.JSONField() actor_id = models.IntegerField(null=True) repo = jsonfield.JSONField() repo_id = models.IntegerField(null=True) created_at = models.DateTimeField() def save(self, *args, **kwargs): self.repo_id = self.repo.get("id") self.actor_id = self.actor.get("id") return super().save(*args, **kwargs) serializers.py: class EventModelSerializer(serializers.ModelSerializer): actor = serializers.JSONField() repo = serializers.JSONField() class Meta: model = EventModel fields = ('id', 'type', 'actor', 'repo', 'created_at') urls.py: url(r'^actors/$', views.Actor.as_view(), name='actors'), views.py: class Actor(generics.GenericAPIView): serializer_class = EventModelSerializer queryset = EventModel.objects.all() def update(self): actor = EventModel.objects.filter(actor_id=self.request.data('id')) print(actor) return HttpResponse(actor) The Input Object: { "id":3648056, "login":"ysims", "avatar_url":"https://avatars.com/modified2" } The requirements is: Updating the avatar URL of the actor: The service should be able to update the avatar URL of the actor by the PUT request at **/actors**. The actor JSON is sent in the request body. If the actor with the id does not exist then the response code should be 404, or if there are other fields being updated for the actor then the HTTP response code should be 400, otherwise, the response code should be … -
Django + emacs, use django-extensions shell_plus inside emacs
I've run python manage.py shell_plus in a separate iterm tab. I would like to run the shell inside emacs, but failed to do it M-x shell (or eshell) python manage.py shell_plus => prompt messed up . M-x term python manage.py shell_plus . => C-x binding is not recognized any more, can't switch buffer C-u M-x run-python python manage.py -i shell_plus => prompt messed up . ipython --simple-prompt -i shell_plus => autoload of shell_plus doesn't work Has anyone figured out a way to run shell_plus inside emacs? -
How to return id from django rest framework to angular application
I am trying to make a http post from an angular application: var body = {client: 1, quantityItem: 2, price: this.formData.GTotal, profitability: 'profitable'} return this.http.post(environment.apiURL+'/order/', body, {headers: this.httpHeaders}); I'm sending the fields from the application and the djangorestframework backend generates the id for the order, how can i get this id? so I can make another http post with the order items and the order id. models(order): class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=None, blank=True, null=True) client = models.ForeignKey(Client, on_delete=models.CASCADE, default=None) quantityItem = models.BigIntegerField(default=1) grand_total = models.FloatField(default=0) profitability = models.CharField(max_length=50) create_date = models.DateTimeField(default=timezone.now, blank=True, null=True) update_date = models.DateTimeField(auto_now=True, blank=True, null=True) models(orderitem): class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.BigIntegerField(default=0) quantityProduct = models.BigIntegerField(default=1) serializers.py: class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = ('id', 'client', 'quantityItem', 'grand_total', 'profitability', 'create_date', 'update_date') viewsets.py: class OrderViewSet(viewsets.ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer what I have to do get the id back and send another request with the order items? -
Django - how can I save cart items in a session
in my django ecommerce I want to save session data for users not logged in. About saving cart ind DB, updating and retrieving it for logged users it's all ok, but how I can proceed for guest users? I tried in this way, but I think this is not a good solution: I save id cart in session and whole cart in database..Could you help me? This is my views.py: def update_cart(request, slug): if request.user.is_authenticated: #ok here... else: try: the_id = request.session["cart_id"] except: new_cart = Cart() product = Product.objects.get(slug=slug) new_cart.save() request.session["cart_id"] = new_cart.id new_cart.products.add(product) new_cart.save() return HttpResponse("<h1>okkk!</h1>") cart = Cart.objects.get(id = the_id) product = Product.objects.get(slug=slug) if not product in cart.products.all(): cart.products.add(product) cart.save() return HttpResponseRedirect(reverse("cart")) else: cart.products.remove(product) return HttpResponseRedirect(reverse("cart")) and they are my Cart model and Product model: class Cart(models.Model): user = models.OneToOneField(User, on_delete="CASCADE", null=True) products = models.ManyToManyField(Product, blank=True) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) class Product(models.Model): title = models.CharField(max_length=120) description = models.TextField(null=True, blank=True) price = models.DecimalField(decimal_places=2, max_digits=100, default=29.99) image = models.FileField(upload_to="products/images", blank=True, null=True) quantity = models.IntegerField(default=1) slug = models.SlugField(unique=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) class Meta: unique_together = ('title', 'slug') def __str__(self): return self.title -
Django ModelForm widgets and labels
When I have a regular ModelForm field, setting up its widgets and/or labels will look like this: class MyModelForm(models.ModelForm): class Meta: model = MyModel fields = ['field_x', 'field_y'] widgets = { 'field_x': Forms.TextInput(attrs={'class': 'myclass', 'readonly': 'readonly'}), 'field_y': Forms.Select(attrs{'class': 'myclass'}), } labels = { 'field_x': 'Input your X value here', 'field_y': 'Select your Y value here', } And it's all ok so far. But when it comes about more "complicated" fields, widgets will ignore its attrs... and it's getting me sick. Example: class MyComplicatedModelForm(forms.ModelForm): field_z = forms.ModelChoiceField(queryset=AnyClass.objects.all(), empty_label=None, required=True, to_field_name='id') class Meta: model = MyComplicatedModel fields = ['field_z'] widgets = { 'field_z': Forms.ModelChoiceField(attrs={'class': 'myclass'}), } labels = { 'field_z': 'Select your Z value here', } And it will work ok but it will ignore its widgets = {} and labels = {}, it will have a default class and the label will be the name of the field ("field_z"). How can I manage widgets and labels when it is not a "regular" field like this last one? -
Showing display values in form built with a loop
I have a simple model form for adding new objects. The template builds the form with a loop, i.e not every field is placed explicitely. The model has a few choice fields. Normally, if you want to see the the display value of the choice field you'd do something like {{ get_myfieldname_display }}. but I cannot use that because I'm using a loop. Here's the view: def tp_new(request): if request.method == 'POST': form = TestPlanForm(request.POST) if form.is_valid(): plan = form.save(commit=False) plan.save() return redirect('tp_detail', pk=plan.pk) else: form = TestPlanForm() return render(request, 'testman/tp_new.html', {'form': form}) Here's the template: ... {% block content %} <form method="POST" class="post-form">{% csrf_token %} <table class="table"> {% for field in form %} <tr><th>{{ field.label_tag }}</th> <td>{{ field }}</td></tr> {% endfor %} </table> <button type="submit" class="mybutton"> Save </button> </form> {% endblock %} ... How can I get it to show the display values for the choice fields? -
Server Error in deploying Django App to Heroku
I have been receiving a 500 response on heroku deployment but it runs on my machine. This is the log details from heroku 2019-02-18T12:39:05.268852+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=herbalapp.herokuapp.com request_id=f5474d03-ee48-4e7a-9645-1f8b6c696131 fwd="41.58.116.107" dyno=web.1 connect=0ms service=580ms status=500 bytes=210 protocol=http 2019-02-18T12:39:05.271577+00:00 app[web.1]: 10.16.198.175 - - [18/Feb/2019:12:39:05 +0000] "GET /favicon.ico HTTP/1.1" 500 27 "http://herbalapp.herokuapp.com/" "Mozilla/5.0 (Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36 OPR/56.0.3051.99 (Edition 360-1)" 2019-02-18T12:41:17.131682+00:00 app[web.1]: 10.99.245.92 - - [18/Feb/2019:12:41:17 +0000] "GET / HTTP/1.1" 500 27 "-" "Mozilla/5.0 (Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36 OPR/56.0.3051.99 (Edition 360-1)" 2019-02-18T12:41:17.132542+00:00 heroku[router]: at=info method=GET path="/" host=herbalapp.herokuapp.com request_id=031c7018-cda1-4fe5-96e7-fc0ed179375d fwd="41.58.116.107" dyno=web.1 connect=1ms service=23ms status=500 bytes=210 protocol=http 2019-02-18T12:41:17.734286+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=herbalapp.herokuapp.com request_id=7f40e2dd-abcf-4c0a-bbd8-fe3baaf27930 fwd="41.58.116.107" dyno=web.1 connect=1ms service=9ms status=500 bytes=210 protocol=http 2019-02-18T12:41:17.733468+00:00 app[web.1]: 10.99.245.92 - - [18/Feb/2019:12:41:17 +0000] "GET /favicon.ico HTTP/1.1" 500 27 "http://herbalapp.herokuapp.com/" "Mozilla/5.0 (Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36 OPR/56.0.3051.99 (Edition 360-1)" 2019-02-18T12:53:10.714457+00:00 heroku[router]: at=info method=GET path="/" host=herbalapp.herokuapp.com request_id=474c2ceb-89b2-46d8-aa8d-07348e9424cb fwd="41.58.116.107" dyno=web.1 connect=0ms service=91ms status=500 bytes=210 protocol=https 2019-02-18T12:53:10.722014+00:00 app[web.1]: 10.179.231.59 - - [18/Feb/2019:12:53:10 +0000] "GET / HTTP/1.1" 500 27 "https://dashboard.heroku.com/" "Mozilla/5.0 (Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36 OPR/56.0.3051.99 (Edition 360-1)" 2019-02-18T12:53:14.696204+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=herbalapp.herokuapp.com request_id=3fb0f476-4500-456f-a276-3299a43957fd fwd="41.58.116.107" dyno=web.1 connect=1ms service=66ms status=500 bytes=210 protocol=http -
Django manage.py runserver command requested resource was not found on this server error
I have just today started working with django. I tried executing the run server command but I keep encountering the page not found error. I have been trying to debug the problem for almost an hour now. Project rms > myrms (app) I have browsed lots of page not found errors questions and their solutions here but none answer the question i have satisfactorily view.py from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello,World. You're at the polls index.") urls.py from django.contrib import admin from django.urls import include, path from . import views urlpatterns = [ path('',views.index,name = 'index'), ] urlpatterns = [ path('myrms/', include('myrms.urls')), path('admin/', admin.site.urls), ] It's expected to show the hello world statement but keeps on turning up page not found error -
Multiple link in cell with LinkColumn - Django-table2
I am on different case that this post "django-tables2 linkcolumn multiple items in the same cell" In this case the number of link is defined. In my case, i will generate the link cell with a list of value. apps.py for subject in list_of_subject: study_name_list = subject["study_name_list"] data_studies.append({ 'subject': subject 'study_name': ", ".join(study_name_list), }) table_studies = StudiesTable(data=data_studies) tables.py class StudiesTable(tables.Table): """ StudiesTable class """ study_name = tables.LinkColumn('study_wiki', args=[A('study_name')], verbose_name='Study') subject = tables.Column(verbose_name='Subject') class Meta: """ Meta class """ attrs = {'class': 'table table-bordered table-striped table-condensed'} Now I can just make a link for the join string obtained... In example: Subject1 | Study1, Study2 | Subject2 | Study3 | Subject3 | Study1, Study2, Study3 | I want that you can click on Study1 and go the page for Study1 and you can click on Study2 and go the page for Study2. Thanks in advance for any help. -
How to add two inline formset to the form dynamically?
In admin page, It can do done easily, but it seems problem in View Page. I've tried but failed many times. As I am newbie to django. How can I achieve this type of formset in Custom View page?? (Create and Update both) -
How can I render strings with certain characters as value of input tag?
I am passing an array of category names to my template and iterating through this to populate the value of checkbox elements. <input id={{"category"|add:escaped_cat_name}} type="checkbox" name="category" value={{category_name}}> Some of my category names contain spaces and ampersands but Django ignores these so "Fun & Gaming" becomes "Fun": category_name: Fun & Gaming <input id="categoryFun" type="checkbox name="category" value="Fun"> category_name: Business Expenses <input id="categoryBusiness" type="checkbox name="category" value="Business"> In these examples, I would like the interpreted value to read the 'Fun & Gamingand 'Business Expenses If I add a safe tag to the value it renders the value name as "Fun" & gaming, with the second part of the string still outside the value name. I have tried writing a custom tag to deal with this behaviour but it seems as though this is Django's default and I can't figure out how to disable it. Any help with this would be much appreciated. -
Two Serializer CreateAPIView - Django
I have create a view which is bellow. Similar i have to create CreateAPIView. In the follwing EmployeeAddView i have took two forms and added data according. But i am not getting how to do it in REST API. @login_required def EmployeeAddView(request): # Tab Opts Checking if request.user.userprofile.user_company.company_tab_opts: return redirect('admin_employee') if request.method == 'POST': random_password = User.objects.make_random_password() # generate password here ur_form = EmployeeRegisterForm(request.POST, pwd=random_password) pr_form = EmployeeProfileForm(request.POST, request.FILES, user_company=request.user.userprofile.user_company.id) user_role = ACLRoles.objects.get(id=4) if ur_form.is_valid() and pr_form.is_valid(): new_user = ur_form.save(commit=False) new_user.username = new_user.email new_user.set_password(random_password) new_user.save() profile = pr_form.save(commit=False) if profile.user_id is None: profile.user_id = new_user.id profile.user_role_id = user_role.id profile.user_company_id = request.user.userprofile.user_company.id profile.save() for group in request.POST.getlist('user_groups'): # For many to many field profile.user_groups.add(group) email= ur_form.cleaned_data.get('email') messages.success(request, 'Employee Added - %s!' % email) return redirect('admin_employee') else: ur_form = EmployeeRegisterForm(use_required_attribute=False) pr_form = EmployeeProfileForm(user_company=request.user.userprofile.user_company.id, use_required_attribute=False) return render(request, 'employee/employee_form.html', {'ur_form': ur_form, 'pr_form': pr_form}) This is my try but i am not getting how to do it API-views.py class EmployeeAddAPIView(generics.CreateAPIView): queryset = User.objects.all() serializer_class = EmployeeRegisterSerializer permission_classes = [UserIsAuthenticated] def perform_create(self, serializer): serializer.save( userprofile__user_company = self.request.auth.application.company, ) API-Serializer.py class EmployeeProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = [ 'user_employee_id', 'user_phone', 'user_payroll_id', 'user_hire_date', 'user_pay_rate', 'user_salaried', 'user_excempt', 'user_groups', 'user_state', 'user_city', 'user_zipcode', 'user_status', ] class EmployeeRegisterSerializer(serializers.ModelSerializer): userprofile = … -
C# GetAsync Won't Work with Django Rest Framework
This is the function in my HomeController.cs: async Task<Dictionary<Object, Object>> GetSiteWithID(int ID) { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", "94afa9a8b0804e65a53d335dec230478f69b39c5"); HttpResponseMessage responseMessage = await client.GetAsync("http://localhost:8000/site/1"); responseMessage.EnsureSuccessStatusCode(); return await responseMessage.Content.ReadAsAsync<Dictionary<Object, Object>>(); } } The problem is it's sending the header as "Authorization: Token 94afa9a8b0804e65a53d335dec230478f69b39c5" correctly but Django Rest Framework doesn't get it. Anything else I need to send because if I test with Postman, it works but it is also sending other stuff which I don't know if it's necessary.