Django Exception Value: 'module' object has no attribute 'ModelsChoiceField' - django

my forms.py
from django import forms
from django.forms import Form
from .models import LedON, Device
class DownlinkForm(forms.Form):
Device_id = forms.ModelChoiceField(queryset = Device.objects.all() )
Time_intervall = forms.IntegerField()
Led1 = forms.ModelsChoiceField(queryset = LedON.objects.all() )
my models.py
from django.db import models
from app.models import *
from django import forms
from django.forms import ModelChoiceField
class LedON(models.Model):
Ledon = models.CharField(max_length = 50)
class Meta:
verbose_name = 'ledon'
def __str__(self):
return "%s" % (self.Ledon)
class DevEUIModelChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return obj.DevEUI
class LedonModelChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return obj.Ledon
The Device object is working and show me the ModelChoiceField.
But I don't understand why the Ledon isn't working.

If that's your actual code, you have a typo, it's ModelChoiceField, but you had ModelsChoiceField.

Related

How to link to URL of related object in DRF

I’m making a music player with a DRF backend.
I have two models, one is Song and the other is TrackQueue
In the browser, the “nowplaying” instance of TrackQueue shows the meta of the queued song with a link to the file in its meta.
What I need now is a url that always produces that instance of the “nowplaying” TrackQueue (id=1)
What would that url be and how can I create it?
Thank you
models.py
class Song(models.Model):
title = models.CharField(max_length=24)
file = models.FileField()
def __str__(self):
return self.title
class TrackQueue(models.Model):
title = models.CharField(max_length=64)
is_song = models.OneToOneField(Song, on_delete=models.CASCADE)
def __str__(self):
return self.title
Serializers.py
from rest_framework import serializers
from .models import Song, TrackQueue
class SongSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Song
fields = ('id' ,'title', 'file')
class TrackQueueSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = TrackQueue
fields = ('id' , 'title', 'is_song')
views.py
from django.shortcuts import render
from .serializers import SongSerializer
from rest_framework import viewsets
from .models import Song, TrackQueue
from music.serializers import SongSerializer, TrackQueueSerializer
class SongView(viewsets.ModelViewSet):
serializer_class = SongSerializer
queryset = Song.objects.all()
class TrackQueueView(viewsets.ModelViewSet):
serializer_class = TrackQueueSerializer
queryset = TrackQueue.objects.all()

How to POST multiple data in DRF and React with Axios

I have 2 models named Recipe and Step..
I have serialized both to make an API for GET request.. I want to know is there a way to create for POST request so that I can send both the data (steps and recipe) in the same request?
models.py:
from django.db import models
class Recipe(models.Model):
title = models.CharField( max_length=50)
uuid = models.CharField( max_length=100)
def __str__(self):
return f'{self.uuid}'
class Step(models.Model):
step = models.CharField(max_length=300)
uuid = models.ForeignKey(Recipe, on_delete=models.CASCADE)
def __str__(self):
return f'{self.step} - {self.uuid}'
serializers.py:
from rest_framework import serializers
from .models import *
class RecipeSerializer(serializers.ModelSerializer):
class Meta:
model = Recipe
fields = ['title', 'uuid']
class StepSerializer(serializers.ModelSerializer):
class Meta:
model = Step
fields = ['step', 'uuid']
views.py:
from django.shortcuts import render
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import *
from .models import *
#api_view(['GET'])
def apiOverview(request):
api_urls = {
'List':'/recipe-list/',
'Detail View':'/recipe-detail/<str:pk>/',
'Create':'/recipe-create/',
'Update':'/recipe-update/<str:pk>/',
'Delete':'/recipe-delete/<str:pk>/',
'Steps' : '/steps/<str:pk>'
}
return Response(api_urls)
#api_view(['GET'])
def recipeList(request):
recipes = Recipe.objects.all()
serializer = RecipeSerializer(recipes, many=True)
return Response(serializer.data)
#api_view(['GET'])
def recipeDetail(request, pk):
recipe = Recipe.objects.get(uuid=pk)
recipe_serializer = RecipeSerializer(recipe, many=False)
steps = Step.objects.filter(uuid=pk)
steps_serializer = StepSerializer(steps, many=True)
return Response({
'recipe' : recipe_serializer.data,
'steps' : steps_serializer.data
})
How can I create a view for POST and handle both the models?
Try:
from rest_framework import generics
from .models import *
class StepAndRecipe(generics.CreateAPIView):
queryset = Step.objects.all()
queryset = Recipe.objects.all()
serializer_class = StepSerializer
serializer_class = RecipeSerializer
Add in urls.py:
from django.urls import path
from .views import StepAndRecipe
urlpatterns = [
path('steprecipepost', StepAndRecipe.as_view(), name='steps_recipes')
This will only work with POST! And one more thing: take care with the raw data and the HTML form, maybe theses get a little confused since you are using two models in the same view.

Django GCBV UpdateView AttributeError - type object 'QuerySet' has no attribute '_meta'

I am stuck at this Point. I want a view that extends the User model with a ForeignKey named UserPlanet(models.Model) and some other views, that extends the UserPlanet Model by OneToOneField. My setup looks like listed below. If I try to reach the view by the url I get an
AttributeError at /game/
type object 'QuerySet' has no attribute '_meta'
How do I solve this? Unfortunately I am missing an approach. Unfortunately, I can not find anything in the django documentation
views.py:
from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import UserPlanet, UserShips, UserDefense, UserBuildings
class IndexView(LoginRequiredMixin, generic.UpdateView):
context_object_name = 'planets'
template_name = 'game/home.html'
fields = ('name', 'planet_size', 'free_fields', 'max_temperature', 'min_temperature', 'planet_galaxy',
'planet_system', 'planet_position')
def get_object(self, queryset=None):
return self.request.user.userplanet_set.all()
models.py:
from django.db import models
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
class UserPlanet(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
name = models.CharField(default='Heimatplanet', max_length=40)
planet_size = models.PositiveSmallIntegerField(default=150)
free_fields = models.PositiveSmallIntegerField(default=150)
max_temperature = models.SmallIntegerField(default=80)
min_temperature = models.SmallIntegerField(default=-20)
planet_galaxy = models.PositiveSmallIntegerField(default=1)
planet_system = models.PositiveSmallIntegerField(default=1)
planet_position = models.PositiveSmallIntegerField(default=1)
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_user_planet(sender, instance, created, **kwargs):
if created:
UserPlanet.objects.create(user=instance)
class UserResources(models.Model):
user_planet = models.OneToOneField(UserPlanet, related_name='user_resources', on_delete=models.CASCADE)
minerals = models.IntegerField(default=1000) # Mineralien
food = models.IntegerField(default=0) # Nahrung
energy = models.IntegerField(default=0) # Energie
physics = models.IntegerField(default=0) # Physik-Forschungspunkte
engineering = models.IntegerField(default=0) # Ingenieur-Forschungspunkte
society = models.IntegerField(default=0) # Gesellschafts-Forschungspunkte
#receiver(post_save, sender=UserPlanet)
def create_user_resources(sender, instance, created, **kwargs):
if created:
UserResources.objects.create(user_planet=instance)
UpdateView is for editing a single object. The get_object method should return a single object, not a queryset.

add my own class in admin field django-cms

Hi everyone Y create my own app in djando CMS, now I want to add my own class and id's to my field.. y try this, but I don't obtain any successful result.
in my model.py I have this
class Entry(models.Model):
TYPES_CHOICES = (
('none', 'not specified'),
('s', 'Series'),
('mb', 'Multiples Bar'),
('b', 'Bar suggestion'),
)
app_config = AppHookConfigField(HealthConfig)
code = models.CharField(blank=True, default='', max_length=250)
url_suggestion = models.CharField(blank=True, default='', max_length=250, verbose_name="URL for Suggestion" )
health_placeholder = PlaceholderField('health_info')
objects = AppHookConfigManager()
def __unicode__(self):
return self.url
class Meta:
verbose_name_plural = 'entries'
and now in my form.py I have this
from django import forms
from .models import Entry
class EntryForm(forms.ModelForm):
class Meta:
model = Entry
fields = '__all__'
def __init__(self, *args, **kwargs):
super(EntryForm, self).__init__(*args, **kwargs)
self.fields['code'].widget.attrs={
'id': 'my_code',
'class': 'code_class',
}
finally my admin.py is like this
from django.contrib import admin
from cms.admin.placeholderadmin import PlaceholderAdminMixin
from .cms_appconfig import HealthConfig
from .models import Entry
from .forms import EntryForm
from aldryn_apphooks_config.admin import ModelAppHookConfig, BaseAppHookConfig
class EntryAdmin(ModelAppHookConfig, PlaceholderAdminMixin, admin.ModelAdmin):
# pass
fieldsets = (
('General data', {
'fields':('app_config','chart', 'url',('count', 'code', 'start'))
}),
('Suggestion',{
'classes':('collapse', 'suggestion',),
'fields':('url_suggestion',('key1_suggestion_name','key1_suggestion'),('key2_suggestion_name','key2_suggestion'), 'primary_suggestions')
}),
)
list_display =('app_config' ,'url', 'chart');
list_filter = (
'app_config',
)
form = EntryForm
class Media:
js = ('health/js/admin/healthAdmin.js',)
css = {
'all': ('health/css/admin/admin_area.css',)
}
admin.site.register(Entry, EntryAdmin)
any idea is I missing something, after that, I do a migrate of the component again.
Thanks in advance!
You can specify a custom form for admin using the form attribute of ModelAdmin.
So using the example from the docs linked below, that would look like;
from django import forms
from django.contrib import admin
from myapp.models import Person
class PersonForm(forms.ModelForm):
class Meta:
model = Person
exclude = ['name']
class PersonAdmin(admin.ModelAdmin):
exclude = ['age']
form = PersonForm
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form
So in your admin.py you'd need something like;
from .forms import EntryForm
class EntryAdmin(admin.ModelAdmin):
form = EntryForm

Question On Django Form Models

I am working on form models and get this error:
global name 'AdForm' is not defined
In my view I have:
from django.template import RequestContext, loader
from django.http import HttpResponse
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from django import forms
#login_required
def create(request):
if request.POST:
ad = AdForm(request.POST)
if ad.is_valid():
test = 'valid'
else:
test = 'invalid'
else:
test = 'none'
template = loader.get_template('ads/create.html')
context = RequestContext(request, {
'test': test
})
return HttpResponse(template.render(context))
However it is not picking up my model. My model in my view is:
from django.db import models
from django.forms import ModelForm
TYPE_CHOICES = (
'Image',
'Code',
)
SIZE_CHOICES = (
'Leaderboard',
'Banner',
'Skyscraper',
'Square',
)
class Ad(models.Model):
title = models.CharField(max_length=40)
type = models.CharField(max_length=7)
size = models.CharField(max_length=16)
clicks = models.IntegerField()
media = models.ImageField(upload_to='ads')
link = models.URLField(null=True)
created = models.DateTimeField(auto_now_add=True)
expires = models.DateTimeField(null=True)
def __unicode__(self):
return self.name
class AdForm(ModelForm):
class Meta:
model = Ad
Does anyone know why it is not picking up the form model?
Thanks from a noob.
At the top of your view, you need:
from .models import AdForm
Also, forms usually go in forms.py, not with the models.