Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Foreign key of foreign key fields are not shown - Django
I want to create form for creating new Person object which has foreign key Address (all these models is just for practice). The problem is that, I can't see neither address label, nor text field for address in PersonCreateForm template. Here are my codes: person_app/models.py: class Person(models.Model): name = models.CharField(max_length=20) address = models.ForeignKey('address_app.Address', on_delete=models.CASCADE) address_app/models.py: class Address(models.Model): country = models.CharField(max_length=30) person_app/forms.py: class CreatePersonForm(ModelForm): def save(self, commit=False): person= super(CreatePersonForm, self).save(commit=False) Person.objects.create( name = person.name, address = person.address.country) person.html: <h1>{{ form.name }}</h1> (name is visible) <h1>{{ form.address }}</h1> (but address not) -
Django Annotate not working on some cases
I have a Django queryset with annotation that works well doing a count over year/month, but for some reason THE SAME CODE for another model does not work. Code that works: usages = Usage.objects.all() usages = usages.annotate(year=ExtractYear('usage_datetime'), month = ExtractMonth('usage_datetime')).values('year','month').annotate(total=Count('id')) Code that dont work (only calculates 1 on the count): events = Events.objects.all() events = events.annotate(year=ExtractYear('created'), month = ExtractMonth('created')).values('year','month').annotate(total=Count('id')) The first one outputs: <QuerySet [{'year': 2020, 'month': 9, 'total': 13}, {'year': 2020, 'month': 8, 'total': 18}, {'year': 2020, 'month': 7, 'total': 29}, {'year': 2020, 'month': 6, 'total': 31}, The second one: <QuerySet [{'year': 2020, 'month': 8, 'total': 1}, {'year': 2020, 'month': 8, 'total': 1}, {'year': 2020, 'month': 8, 'total': 1}, {'year': 2020, 'month': 8, 'total': 1} 'total': 1}, '...(remaining elements truncated)...']> The second one is not counting like the first one.... not sure what it may be.... Since the only difference is on the model, I would assume thats the issue, so here are my models: models.py class Event(models.Model): name = models.CharField(max_length=255) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) class Usage(models.Model): name = models.CharField(max_length=255) usage_datetime = models.DateTimeField(auto_now_add=True) -
Placeholder Fields - Django CMS
I can't get those placeholder fields to work. This is my model: class Category(models.Model): class Meta: verbose_name = "Kategorie" verbose_name_plural = "Kategorien" header = PlaceholderField('header') And this is my views: def rooms_list(request): categories = Category.objects.all() return render(request, "rooms/rooms-list.html", locals()) If I know try to render it like so: {% render_placeholder category.header %} Nothing happens at all... Thanks in advance! -
Invalid password format or unknown hashing algorithm. in django rest-framework
while saving the user password field is shows an Invalid password format or unknown hashing algorithm. user is created the password field is Invalid password format or unknown hashing algorithm. When I go to register the user it did not show any error while registration. unable to find y also tried user.set_unusable_password() in serializer but the same result could not figure it out from rest_framework import serializers from accounts.models import User class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','phone' , 'password',) write_only_fields = ('password',) def create(self, validated_data): user = User.objects.create(validated_data['phone']) user.set_password(validated_data['password']) user.save() return user }) class Register(APIView): def post(self, request, *args, **kwargs): phone = request.data.get('phone', False) password = request.data.get('password', False) print(phone) print(password) if phone and password: old = PhoneOTP.objects.filter(phone__iexact=phone) if old.exists(): old = old.first() validated = old.validate if validated: temp_data = { 'phone': phone, 'password': password } serializers = CreateUserSerializer(data=temp_data) serializers.is_valid(raise_exception=True) user = serializers.save() old.delete() return Response({ 'status': True, 'detail': 'Account is created ' }) -
Django JSONField or Foreignkey to store data
I want to store some values such as league data, statistics data or bracket data. Which approach is more effective for future (performance, scalability, efficient) class League(models.Model): ... class MatchStatistics(models.Model): point=models.IntegerField(null=True,blank=True) rank=models.IntegerField(null=True,blank=True) ... class MatchStatistics(models.Model): league=models.ForeignKey(League) statistics=models.ForeignKey(MatchStatistics) OR class MatchStatistics(models.Model): statistics=models.JSONField() league = models.JSONField() bracket = models.JSONField() For example, i have 32 teams and i want to create and store bracket for these. So, which approach better. (32 teams=32 rows) class Bracket(models.Model): match=models.FK team =models.FK winn = lose = ... OR bracket = models.JSONField() -
How to add a constraint comparing to field of different model
The models: class Listing(models.Model): starting_bid = models.DecimalField( max_digits=11, decimal_places=2, verbose_name='Starting Bid*') class Bid(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=11, decimal_places=2) class Meta: constraints = [ models.CheckConstraint(check=Q(amount__gte=***listing.starting_bid***), name='amount_gte_starting_bid') ] Is there any way to say in the constraint "get the starting bid amount of the listing that the user is bidding on, and make sure that the amount is greater than or equal to it"? I've thought of manipulating POST data in views.py, submitting a hidden input in the html, (these two methods I'm guessing won't work because the database constraint is checked without submitting the POST request) or using an F() object in the CheckConstraint, but nothing satisfactory. If this is impossible, please let me know. Before, I was just using some logic in views.py to return an HttpResponse with an error message, which worked fine, but I wanted to see if I can use the nice dialogue box that the database constraint gives. -
How do staff users edit their profiles in Django?
I'm new to Django. I'm working on a website that will only contain users as staff users. I'm the administrator. My plan is to register a user and give him his username and password to log in; I want him only to be able to edit his profile to add more information, not to change existing attributes. How can I do that? -
Django Function Based View - Variable Value Returns None when set inside Conditional Expression
Setting a session_uid when the page loads. Then, passing that session_uid to the server to create a directory to temporarily store files. The variable session_uid changes to None if I attempt to call the variable within the IF conditional statement as shown in my code snippet. Why does this happen? Is there a better way to set up a temporary directory? I'm using Sebastian Tschan's fileupload widget. views.py if request.method == 'POST': session_uid = request.POST.get('session_uid') # session uid is generated by uuid.uuid4() that is passed in the GET method via the return render's context dictionary. temp_path = os.path.join(settings.MEDIA_ROOT, str(session_uid)) print(temp_path) # prints as expected (e.g. \media\be017eb6-be74-421a-96dd-8c171a933c54) if 'file' in request.FILES: # to save files that are uploaded form = FileForm(request.POST, request.FILES) print(temp_path) # the session_uid variable now is None (e.g. \media\None) # remaining code to save the file to the path # script.js function send_uid_value(){ var formAction = $(this).attr('data-url'); $.ajax({ url: formAction, method: 'POST', data: {session_uid: $("#uid").val()}, }); }; -
How to get many to many data in django at same model
class Consumer (models.Model): name=models.CharField(max_length=32) address=models.CharField(max_length=32) telephone=models.CharField(max_length=32) email=models.CharField(max_length=32) ac_no=models.IntegerField(default=0) class Consumer_order(models.Model): name=models.ForeignKey(Consumer, on_delete=models.CASCADE) ac_no=models.ManyToManyField(Consumer) newspaper=models.ForeignKey(Newspaper, on_delete=models.CASCADE) added_date=models.DateField(max_length=32,auto_now_add=True) i try many ways many to many relationship but not work those error occur (fields.E302,E303,E304). How to get Model Consumer from ac_no To Consumer_order to ac_no datafield? -
Real-time update on Django application using MySQL <> WebSocket
I need to continuously get data from a MySQL database which gets data with an update frequency of around 200 ms. I need to continuously update the data value on the dashboard text field.My dashboard is built on Django. I have read a lot about Channels but all the tutorials are about chat applications. I know that I need to implement WebSockets which will basically have an open connection and get the data. With the chat application, it makes sense but I haven't come across anything which talks about MySQL database. I also read about mysql-events. Since the data which is getting in the table is from an external sensor, I don't understand how I can monitor a table inside Django i.e whenever a new row is added in the table, I need to get that new inserted based on a column value. Any ideas on how to go about it? I have gone through a lot of articles and I couldnt find something specific to this requirement. -
jQuery missing for django-autocomplete-light
I am trying to get autocomplete light working admin interface in Django 3. Select2 is giving the following error which indicates that the window.jQuery is undefined. Select2: An instance of jQuery or a jQuery-compatible library was not found. Make sure that you are including jQuery before Select2 on your web page. This is covered in the documentation, here: "This is to override the jquery.init.js script provided by the admin, which sets up jQuery with noConflict, making jQuery available in django.jQuery only and not $." I ensured that the dal APPS are in the right order: 'dal', 'dal_select2', # "django.contrib.humanize", # Handy template tags "django.contrib.admin", It appears that the jquery.init.js scripts are in the wrong order, that the autocomplete_light one should be after the admin one or that the admin one should be after the select import. <script type="text/javascript" src="/static/admin/js/vendor/jquery/jquery.js"></script> <script type="text/javascript" src="/static/autocomplete_light/jquery.init.js"></script> <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script> <script type="text/javascript" src="/static/vendor/select2/dist/js/select2.full.js"></script> <script type="text/javascript" src="/static/admin/js/core.js"></script> <script type="text/javascript" src="/static/vendor/select2/dist/js/i18n/en.js"></script> <script type="text/javascript" src="/static/admin/js/admin/RelatedObjectLookups.js"></script> <script type="text/javascript" src="/static/autocomplete_light/autocomplete.init.js"></script> <script type="text/javascript" src="/static/admin/js/actions.js"></script> <script type="text/javascript" src="/static/autocomplete_light/forward.js"></script> <script type="text/javascript" src="/static/admin/js/urlify.js"></script> <script type="text/javascript" src="/static/autocomplete_light/select2.js"></script> <script type="text/javascript" src="/static/admin/js/prepopulate.js"></script> <script type="text/javascript" src="/static/autocomplete_light/jquery.post-setup.js"></script> After loading, window.jQuery is not defined, yl.jQuery is defined. > window.jQuery < undefined > yl.jQuery < ƒ ( selector, context ) { … -
Applying auth.0008_alter_user_username_max_length...Traceback (most recent call last), django mssql backend migration error
Please, need help; i use the last version of django 3.1, with django-mssql-backend to migrate ms sql database, whene trying to migrate i faced this problem : auth.0008_alter_user_username_max_length...Traceback (most recent call last); Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length...Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Leo\PycharmProjects\Django\untitled\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Leo\PycharmProjects\Django\untitled\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Leo\PycharmProjects\Django\untitled\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Leo\PycharmProjects\Django\untitled\venv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\Leo\PycharmProjects\Django\untitled\venv\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Leo\PycharmProjects\Django\untitled\venv\lib\site-packages\django\core\management\commands\migrate.py", line 245, in handle fake_initial=fake_initial, File "C:\Users\Leo\PycharmProjects\Django\untitled\venv\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Leo\PycharmProjects\Django\untitled\venv\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\Leo\PycharmProjects\Django\untitled\venv\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\Leo\PycharmProjects\Django\untitled\venv\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\Leo\PycharmProjects\Django\untitled\venv\lib\site-packages\django\db\migrations\operations\fields.py", line 236, in database_forwards … -
How can I sort a nested dictionary in python
I got this dictionary which I want to sort the keys inside the key, so the key 8 for example would be after 7. What I got: {8888: {1: 2.0, 2: 2.0, 3: 2.0, 8: 4.0, 4: '-', 6: '-', 7: '-', 9: '-'} What I want: {8888: {1: 2.0, 2: 2.0, 3: 2.0, 4: '-', 6: '-', 7: '-', 8: 4.0, 9: '-'} -
How do I ask a good question?Django runserver
Trying to run Python manage.py runserver but this is what is occcuring when one try to do it. Have no clue, just begun learning django. One is trying to make a tutorial code4startup but cant get by this error. Dont know how to solve these kind of error but think something in library is missing., and not good att navigating what kind of error this is, hard to search for it if it is already posted. '(virtual) C:\Users\PC\Desktop\Event\virtual\Project>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\PC\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\PC\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\PC\Desktop\Event\virtual\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\PC\Desktop\Event\virtual\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\PC\Desktop\Event\virtual\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\PC\Desktop\Event\virtual\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\PC\Desktop\Event\virtual\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\PC\Desktop\Event\virtual\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\PC\Desktop\Event\virtual\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\PC\Desktop\Event\virtual\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Users\PC\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", … -
django rest Invalid password format or unknown hashing algorithm
User = get_user_model() class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','phone' , 'password',) write_only_fields = ('password',) def create(self, validated_data): user = User.objects.create(validated_data['phone']) user.set_password(validated_data['password']) user.save() return user }) class Register(APIView): def post(self, request, *args, **kwargs): phone = request.data.get('phone', False) password = request.data.get('password', False) print(phone) print(password) if phone and password: old = PhoneOTP.objects.filter(phone__iexact=phone) if old.exists(): old = old.first() validated = old.validate if validated: temp_data = { 'phone': phone, 'password': password } serializers = CreateUserSerializer(data=temp_data) serializers.is_valid(raise_exception=True) user = serializers.save() old.delete() return Response({ 'status': True, 'detail': 'Account is created ' }) while saving user pasword feild is shows Invalid password format or unknown hashing algorithm. user is created the password feild is Invalid password format or unknown hashing algorithm. uable to find y also tried user.set_unusable_password() in serializer but same result could not figure it out -
Django: Media files not being saved (Even though they show up on the database but not with a correct URL)
I'm trying to make a user upload a post where the user can upload a caption, an image(NULL=True) and a video file(NULL=True). When I'm trying to upload an image or a video, the Django saves it to the database but not in the media folder that I made for the media files on my local machine. Though it does shows up on the database but it's not at the correct URL rather it gives me a 404. Even though I did added a media URL in my URLS.py ,here are the screenshots: Here's my views.py: @login_required def savepost(request): if request.method == 'POST': user = request.user Post = post(user=user, caption=request.POST.get("usercaption"), image=request.POST.get("fileimg"), video=request.POST.get("filevid")) Post.save() return redirect('usersfeed') My Models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) caption = models.CharField(max_length=1000) image = models.FileField(upload_to='images/', null=True, blank=True) video = models.FileField(upload_to='videos/', null=True, blank=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.caption HTML Form: <form action="/savepost/" method="POST"> {% csrf_token %} <input type="text" name="usercaption" placeholder="Write Something..." required> <div class="attach"> <input type="file" name="fileimg" id="fileimg" accept="image/*" class="inputfile"> <label for="fileimg"><i class="fal fa-image"></i> Image</label> <input type="file" name="filevid" id="filevid" accept="video/*" class="inputfile"> <label for="filevid"><i class="fal fa-video"></i> Video</label> <input type="file" name="file" class="inputfile"> <label for="file"><i class="fal … -
How to get related model data in Django Admin panel?
I am developing a product base table and my product table is related to Informtion table, it means a product can have information, but when i add product from admin panel, i am not getting information data there when i submit the product, Please let me know how i can get the information table fields in product add form in django admin panel. Here is my `models.py file... class Product(models.Model): name=models.CharField(max_length=50, blank=True, null=True) type=models.CharField(max_length=50, blank=True, null=True) def __str__(self): return self.name class Information(models.Model): product=models.ForeignKey(Product, default=None, related_name='product_info', on_delete=models.CASCADE) title=models.CharField(max_length=50, null=True, blank=True) number=models.IntegerField(default=None) def __str__(self): return self.title my `admin.py' file is this from django.contrib import admin from customer.models import * # Register your models here. admin.site.register(Product) admin.site.register(Information) when i am clicking on add product it's displaying there only name, type and i want to display the data from information table also, i want all fields when i click on add product -
No support available to deploy Django web app on godaddy?
I have never really have deployed a django app. There is no help available in the godaddy docs if it supports django app deployment or not, if any one has done it please help! Can not buy another host. -
Loop over range in Django Html Template
In my django template I want to replicate a line by the number of quantities like the following: Something like repeating Material Request 67 14 times, 34 15 times and so on for that I have retrieved quantity in a list like following: d_docket = AllotmentDocket.objects.filter(parent_company = client_pk.pk, transaction_date__range =[start, end]).order_by('-transaction_date') quan = list(d_docket.values_list('product1_quantity', flat=True)) which gives: [14, 15, 15, 15, 15, 20, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 14, 15, 13, 6, 15, 15, 10, 15, 15, 15, 7, 8] But how can I loop over range of each element of quan in django template ? Current Template: {% for i in query %} <tr> <td class="align-middle">{{ i.sales_order.owner }}</td> <td class="align-middle">{{ i.sales_order.pk }}</td> <td class="align-middle">{{ i.sales_order.flow }}</td> <td class="align-middle">{{ i.sales_order.kit }}</td> </tr> {% endfor %} -
Django shopping cart update
I am trying to send slg (as quanty when update shopping cart): {% for item in myCart.values %} <tr> <td class="product-col"> <img src="/media/{{item.image}}" alt=""> <div class="pc-title"> <h4>{{item.name}}</h4> <p>${{item.price}}</p> </div> </td> <td class="quy-col"> <div class="quantity"> <div class="pro-qty"> <input type="number" min="1" name="slg[{{item.id}}]" value="{{item.slg}}"> </div> </div> </td> <td class="size-col"><h4>Size M</h4></td> <td class="total-col"><h4>${% widthratio item.price 1 item.slg %}</h4></td> <td class="total-col"><a href="{% url 'home:deleteCart' item.id %}">Delete</a></td> </tr> {% endfor %} This is my view, i am trying to get data form templates but it's not work def updateCart(request): slg = request.POST['slg'] return render(request, 'home/check.html', {'myCart': slg}) -
How to apply 2D chaining with Celery
I have the following tasks that I want to implement a pipeline for them from abc import abstractmethod from celery import Task from django.core.paginator import Paginator class PipelineTask(Task): @abstractmethod def run(self, *args, **kwargs): pass class BaseStagingTask(PipelineTask): @abstractmethod def stage(self, *args, **kwargs): pass def run(self, *args, **kwargs): self.stage(*args, **kwargs) class BaseLoadingTask(PipelineTask): @abstractmethod def load(self, *args, **kwargs): pass def run(self, *args, **kwargs): self.load(*args, **kwargs) class BaseFinalizingTask(PipelineTask): @abstractmethod def finalize(self, *args, **kwargs): pass def run(self, *args, **kwargs): self.finalize(*args, **kwargs) class BasePipeline: def __init__(self, input_paginator, staging_tasks, loading_tasks, finalizing_tasks): """ :type staging_tasks: List[StagingTask] :type loading_tasks: List[LoadingTask] :type finalizing_tasks: List[LoadingTask] :type input_paginator: django.core.paginator.Paginator """ self.input_paginator = input_paginator self.staging_tasks = staging_tasks self.loading_tasks = loading_tasks self.finalizing_tasks = finalizing_tasks def run(self): pass pipeline = BasePipeline( input_paginator= Paginator(some_queryset), staging_tasks=[s1,s2,s3], loading_tasks=[l1,l2,l3], finalizing_tasks=[f1,f2,f3] ) pipeline.run() I need to run the stages tasks in sequential order per data chunk, and at the same time, to run them in parallel across the entire data with the condition that each staging task start after the previous one finishes. It's depicted in the diagram below I just need a pseudo-code to implement the above pipeline. -
Trying to migrate my Django App from REST to GraphQL
Im trying to change my Django API from REST to GraphQl , I've changed my serializer and my viewsets for this purpose , however I'm getting an error : "'function' object has no attribute 'get_extra_actions'" now I know I might have to add .as_view at the end of my viewsets that I've routed to in urls.py but I'm not sure how I can do that with the current format. new views.py(named api.py) : from .models import Song from .models import Artist from .models import Album import graphene from .serialize import SongSerializer from .serialize import AlbumSerializer from .serialize import ArtistSerializer class Query(graphene.ObjectType): song_queryset = graphene.List(SongSerializer) def resolve_song(self , info , **kwargs): name = kwargs.get("Name") genre = kwargs.get("Genre") artist = kwargs.get("Artist") album = kwargs.get("Album") return Song.objects.get(name) , Song.objects.get(genre), Song.objects.get(artist), Song.objects.get(album) album_queryset = graphene.List(AlbumSerializer) def resolve_album(self, info, **kwargs): name = kwargs.get("Name") genre = kwargs.get("Genre") artist = kwargs.get("Artist") song = kwargs.get("Song") date = kwargs.get("DatePublihsed") return Album.objects.get(name), Album.objects.get(genre), Album.objects.get(artist), Album.objects.get(song) ,Album.objects.get(date) artist_queryset = graphene.List(ArtistSerializer) def resolve_artist(self, info, **kwargs): name = kwargs.get("Name") type = kwargs.get("Type") album = kwargs.get("Album") song = kwargs.get("Song") prefer = kwargs.get("PreferredGenre") date = kwargs.get("DateOfFormationorBirth") bio= kwargs.get("Bio") return Artist.objects.get(name), Artist.objects.get(type), Artist.objects.get(album), Artist.objects.get( song), Artist.objects.get(prefer) , Artist.objects.get(date), Artist.objects.get(bio) schema = graphene.Schema(query=Query) urls.py: from rest_framework import … -
Django OneToOne field - no reverse accessor to AUTH_USER_MODEL
I am trying to extend Django's default UserModel, referenced by settings.AUTH_USER_MODEL, with a custom model, UserProfile. In every case I use the OneToOne-Relationship, I get an accessor on the referenced model also. So this usually works: class ModelA(models.Model): text = models.CharField(max_length=100) class ModelB(models.Model): link_to_model_a = models.OneToOneField(ModelA, on_delete=models.CASCADE) model_a = ModelA() model_a.modelb # Works fine But it does not work in this case (snippet shortened): class UserProfile(models.Model): # There are more fields, but removed # for this example user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) from django.contrib.auth import get_user_model get_user_model().userprofile # Causes AttributeError: type object 'User" has no attribute 'userprofile' I could not find any information about if this phenomenon could appear due to the relationship to djangos default user-model. Maybe they treat it in a special way and do not allow reverse accessing? I'm really thankful for any help in this concern. -
How to post data in django rest framework using ajax
I have an app that looks like a social network and I want to provide an option to post something in the user profile, but when I try to add a new post using ajax and django rest framework I always get a POST http://127.0.0.1:8000/api/post-list 500 (Internal Server Error) error. I have not found a solution to my problem in internet, please help. models.py class GreenLeafUserProfile(models.Model): id = models.PositiveIntegerField(primary_key=True, unique=True) profile_picture = models.ImageField(default='/pictures/default.png', upload_to='pictures') user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=63, blank=True) phone = models.CharField(max_length=15, blank=True) def __str__(self): return str(self.user) + ' profile' class PostProfile(models.Model): author = models.ForeignKey(GreenLeafUserProfile, on_delete=models.CASCADE) post_text = models.TextField(max_length=5000) publication_date = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.author) + ' post owner ' + str(self.publication_date) + ' publication date' serializer.py class PostSerializer(serializers.ModelSerializer): class Meta: model = PostProfile fields = '__all__' views.py class PostList(APIView): def get(self, request): posts = PostProfile.objects.all() serializer = PostSerializer(posts, many=True) return Response(serializer.data) def post(self, request): serializer = PostSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) script for button in html file $('.add-new-post').on('click', function () { let postTextarea = $('#newPostText'); alert('clicked'); $.ajax({ type: "POST", url: "../api/post-list", data: JSON.stringify({ post_text: postTextarea.val(), id: postTextarea.attr('userId'), }), dataType: "json", beforeSend: function (xhr, settings) { xhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}'); }, … -
What is a better approach, less code and more ForeignKeys or more code and columns?
I'm writing my first commercial Django app and I'm looking for some help as I'm stuck with changing and optimizing the models for quite some time. Right now I'm considering what is the better approach to creating models. Let's say I have few models that all have few fields in common (like name, city, address, post code). Can you tell me what is the better approach, repeat those few fields (columns) in every model (table) or just go for foreignkeys everywhere it fits and create an Address model even though those addresses will be of completely different things (people, institutions etc.) and I won't need them in one table. I understand the more foreignkeys I make the more queries the app will make every time it needs some info from those other tables? Is it even worth considering? The advantages I see are: less code not repeating myself and disadvantages: more queries for the same information? little bit more complicated to implement later bigger possibility of duplicated rows Thank you for you help.