Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Combining Two serializers int one JSON response
I am trying to export data from two models for a user in the format of "Level":[ { "level":1, "book_ID":"96F7EBBD-4523-4473-978B-1BFD2F62926A", "date_added":"2020-03-06 21:58:42 +0900" }, { "level":1, "book_ID":"76E8F992-7A7F-477D-B178-67BA5295DA6E", "date_added":"2020-03-06 21:59:12 +0900" }, ] "Key":[ { "key":1, "book_ID":"96F7EBBD-4523-4473-978B-1BFD2F62926A", "date_added":"2020-03-06 21:58:42 +0900" }, { "level":1, "book_ID":"76E8F992-7A7F-477D-B178-67BA5295DA6E", "date_added":"2020-03-06 21:59:12 +0900" }, ] In order to do this my code is serializer.py class LevelSerializer(serializers.ModelSerializer): book_ID = serializers.SlugRelatedField( source='book', many=False, read_only=True, slug_field='book_ID' ) class Meta: model = Level fields = ["date_added", 'book_ID', "level", ] class KeySerializer(serializers.ModelSerializer): book_ID = serializers.SlugRelatedField( source='book', many=False, read_only=True, slug_field='book_ID' ) class Meta: model = Key fields = ["date_added", 'book_ID', "mykey", ] view.py def api_get_all(request): if request.method == 'GET': all_levels = Level.objects.filter(user=1) all_key = Key.objects.filter(user=1) level_serializer = LevelSerializer(all_levels, many=True) key_serializer = KeySerializer(all_key, many=True) combine_serializer = level_serializer.data + key_serializer.data return Response(combine_serializer) However if I execute my above implementation I get [ { "level":1, "book_ID":"96F7EBBD-4523-4473-978B-1BFD2F62926A", "date_added":"2020-03-06 21:58:42 +0900" }, { "level":1, "book_ID":"76E8F992-7A7F-477D-B178-67BA5295DA6E", "date_added":"2020-03-06 21:59:12 +0900" }, { "level":1, "book_ID":"76E8F992-7A7F-477D-B178-67BA5295DA6E", "date_added":"2020-03-06 21:59:12 +0900" }, { "key":1, "book_ID":"96F7EBBD-4523-4473-978B-1BFD2F62926A", "date_added":"2020-03-06 21:58:42 +0900" } ] How can I make it so that it is serialized in a parent key? Any help is appreciated -
Django Ajax 405 (Method Not Allowed) CBV
I'm having trouble in POST-ing and DELETE-ing through Ajax call ! I've defined the methods on class! idk what is happening. Any help will be appreciated 😀 urls.py: path('<section>/add_wish/<slug>/', views.AddToWishlistView.as_view(), name='add_to_cart'), my view : class AddToWishlistView(LoginRequiredMixin, View): model = Wishlist http_method_names = ['POST'] def POST(self, request, *args, **kwargs): wished_product = get_object_or_404(Product, slug=self.kwargs['slug']) new_item = self.model.objects.get(customer = self.request.user) new_item.product.add(wished_product) return HttpResponse(status=201) and Ajax here ! $('.buy').click(function(e){ e.preventDefault(); let _this = $(this); var slug = _this.children().data('id'); var section_slug = _this.data('section'); $.ajax({ type : 'POST', url : '../'+section_slug + '/add_wish/' + slug + '/', success: function(data){ if(data.success = true){ _this.addClass('clicked'); } }, async : false, error : function(data){ console.log("ERROR"); console.log(data); alert('LOOSERR'); } }) }); -
How to make autocomplete filter in django admin form with class based model
I want to add a dropdown with autocomplete filter such as select2 into django admin form with class based model. i have tried several tricks avilable over the internet but not succeeded. here are some code snippet i have. i want to show all category for a post which is already available into model. in my model.py class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) featured_image = models.ImageField(null=True, blank=True, upload_to="blog/", verbose_name='Featured Image') author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = RichTextUploadingField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on', 'title'] def __str__(self): return self.title def _generate_slug(self): value = self.title slug_candidate = slugify(value, allow_unicode=True) self.slug = slug_candidate def save(self, *args, **kwargs): if not self.pk: self._generate_slug() super().save(*args, **kwargs) my admin.py class PostAdmin(admin.ModelAdmin): list_display = ('title', 'slug', 'status', 'category', 'author','created_on') list_filter = ("status",) search_fields = ['title', 'content'] prepopulated_fields = {'slug': ('title',)} actions = [export_as_csv_action("CSV Export", fields=['title','slug','author','featured_image','status','created_on','updated_on'])] how my form looks into django-admin please suggest anything how to add i filter for category dropdown filter with autocomplete. -
Problem while inititliazing a django project in travis CI
./app/settings.py:89:80: E501 line too long (91 > 79 characters) ./app/settings.py:92:80: E501 line too long (81 > 79 characters) ./app/settings.py:95:80: E501 line too long (82 > 79 characters) ./app/settings.py:98:80: E501 line too long (83 > 79 characters) The command "docker-compose run app sh -c "python manage.py test && flake8"" exited with 1. -
How do I show validation error in django?
I am new to Django. I am doing simple crud but without using forms.py. How do I show validation error message in template. I want to know if there is way to perform crud operation without creating forms.py. Please do consider any mistake in questions since I am new to django. Also any help will be appreciated. This is views.py def category_save(request): if request.method == 'POST': name = request.POST['name'] slug = request.POST['slug'] image = request.FILES['image'] category = Category(name=name, slug=slug, image=image) category.save() return redirect('dish:category') This is template <form action="{% url 'dish:category_save' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="name">Name:</label> <input type="text" name="name" class="form-control"> </div> <div class="form-group"> <label for="slug">Slug:</label> <input type="text" name="slug" class="form-control"> </div> <div class="form-group"> <label for="image">Choose Image:</label> <input type="file" name="image" class="form-control"> </div> <button type="submit" class="btn btn-primary">Save</button> </form> -
Unexpected error while request parsing using a serializer
While parsing my request data from front-end and converting into JSON format using a serializer. I am getting some unexpected errors. while request parsing pattern using a serializers given as mentioned below, it shows me following error: {'phone_number': {u'non_field_errors': [u'Invalid data. Expected a dictionary, but got str.']}, 'cont_email': {u'non_field_errors': [u'Invalid data. Expected a dictionary, but got str.']}} I have a Model: class RestaurantContactAssociation(models.Model): restaurant=models.ForeignKey(Restaurant) contact=models.ForeignKey(Contact,null=True,blank=True,related_name="restaurantcontact_association",on_delete=models.SET_NULL) class PhoneNumber(models.Model): contact = models.ForeignKey(Contact,related_name='contact_number') number = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) class ContactEmail(models.Model): contact = models.ForeignKey(Contact,related_name='contact_email') email = models.EmailField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) The serializers that I have created are: class PhoneNumberSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = PhoneNumber fields = ('number') class ContactEmailSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ContactEmail fields = ('email') class CrmContactSerializer(serializers.ModelSerializer): phone_number = PhoneNumberSerializer(source = 'contact_number') cont_email = ContactEmailSerializer(source = 'contact_email') class Meta: model = RestaurantContactAssociation fields = ('id','phone_number','cont_email','contact') The part of code which calls this serializer: request.data['phone_number'] = '9999999999' request.data['cont_email'] = 'tim@gmail.com' contact_name = request.data.get('c_name',None) contact_serializer = CrmContactSerializer(data=request.data) if contact_serializer.is_valid(): contact_serializer.save() Can someone please offer advise, that what am I passing wrong in it? -
Django: Uppercase/Lowercase values of Django Model attributes should be treated as same
I have model city: class City(models.Model): state = models.ForeignKey('State', on_delete=models.SET_NULL, null=True) name_regex = RegexValidator(regex=r'^[a-zA-Z]+$', message="Name should only consist of characters") name = models.CharField(validators=[name_regex], max_length=100) postalcode = models.IntegerField(unique=True) class Meta: unique_together = ["state", "name"] In this model name of city with all the cases (Uppercase/lowercase) should be treated as same like Udaipur/udaipur/udaiPuR all should be treated as same. -
Django-allauth Discord redirect uri is incorrect
According to Discord, the redirect url should start with https://discordapp.com/api/oauth2/authorize? yet when I pass {% provider_login_url 'discord' %} into my "Login with Discord" button, its redirect uri starts with https://discordapp.com/oauth2/authorize? (without the /api/). If I manually pass in the proper redirect url, it works fine. But using the {% provider_login_url 'discord' %} redirect gets an 'incorrect redirect_uri' error. If I look at the DiscordOAuth2Adapter() class from the allauth Github, it looks like it has the proper authorize_url. class DiscordOAuth2Adapter(OAuth2Adapter): provider_id = DiscordProvider.id access_token_url = 'https://discordapp.com/api/oauth2/token' authorize_url = 'https://discordapp.com/api/oauth2/authorize' profile_url = 'https://discordapp.com/api/users/@me' def complete_login(self, request, app, token, **kwargs): headers = { 'Authorization': 'Bearer {0}'.format(token.token), 'Content-Type': 'application/json', } extra_data = requests.get(self.profile_url, headers=headers) return self.get_provider().sociallogin_from_response( request, extra_data.json() ) I'm clearly missing something here. -
Django template forloop and if condition problem
if looped reach 7, it will add or change td just like the second picture showed {% for match in matches %} <tr> <td class="tblcore">{{match.id}}. {{match.Marking__Marking}}</td> </tr> {% endfor %} this is i want result -
pycharm Cannot load facet Django
I created a django project and opened it using pycharm community, and it showed error: Cannot load facet Django. I already installed django in pycharm, but it still shows this error. -
How to create a backend with Django and GraphQL that process a data from Angular then post back a result?
I'm totally a beginner to back-end. I already created the front-end for a web app by Angular which allows us to draw a number on a white space (28 pixels x 28 pixels), then sends the image as a 2D array to its back-end. The back-end then uses a machine learning model to guess which number it is. I'm trying to use Django as my back-end with GraphQL to make an API to receive data, but I'm totally confused after watching and reading some tutorials about Django. How can I create a GraphQL API with only one field which receives my array properly? And where should I put the logic to my Django back-end? Please give me some advice or resources. Thank you very much!! My back-end will simply receive a 2D array, process it then will send the result back to Angular to display and nothing else. -
Upload data from CSV to Django model
For this purpose we can write a script that would do the job. But I want a batch update on database using csv file. I tried django-adaptors also. Is there any other way to achieve this? -
celery beat fail when using djcelery schedule
I have a bit of a challenge and wonder if someone can help. I don't have any problem running celery manually,however if I use the beat with djcelery scheduler, I get a bunch of database errors. worker: Warm shutdown (MainProcess) (environment) [root@pse apps]# celery -A services_backend beat -l debug --max-interval=10 celery beat v3.1.26.post2 (Cipater) is starting. __ - ... __ - _ Configuration -> . broker -> redis://localhost:6379// . loader -> celery.loaders.app.AppLoader . scheduler -> djcelery.schedulers.DatabaseScheduler . logfile -> [stderr]@%DEBUG . maxinterval -> 10.00 seconds (10.0s) [2020-03-24 01:46:42,962: DEBUG/MainProcess] Setting default socket timeout to 30 [2020-03-24 01:46:42,964: INFO/MainProcess] beat: Starting... [2020-03-24 01:46:42,964: DEBUG/MainProcess] DatabaseScheduler: intial read [2020-03-24 01:46:42,964: INFO/MainProcess] Writing entries (0)... [2020-03-24 01:46:42,964: CRITICAL/MainProcess] beat raised exception <class 'AttributeError'>: AttributeError("'DatabaseFeatures' object has no attribute 'autocommits_when_autocommit_is_off'",) Traceback (most recent call last): File "/opt/pse/apps/environment/lib/python3.6/site-packages/kombu/utils/_init__.py", line 323, in __get_ return obj.__dict__[self.__name__] KeyError: 'scheduler' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/pse/apps/environment/lib/python3.6/site-packages/celery/apps/beat.py", line 112, in start_scheduler beat.start() File "/opt/pse/apps/environment/lib/python3.6/site-packages/celery/beat.py", line 470, in start humanize_seconds(self.scheduler.max_interval)) File "/opt/pse/apps/environment/lib/python3.6/site-packages/kombu/utils/_init__.py", line 325, in __get_ value = obj.__dict__[self.__name__] = self.__get(obj) File "/opt/pse/apps/environment/lib/python3.6/site-packages/celery/beat.py", line 512, in scheduler return self.get_scheduler() File "/opt/pse/apps/environment/lib/python3.6/site-packages/celery/beat.py", line 507, in get_scheduler lazy=lazy) File "/opt/pse/apps/environment/lib/python3.6/site-packages/celery/utils/imports.py", line 53, in … -
How to deal with authorization with DRF and React
I'm building an app using Django as backend and React as frontend, for the user authentication I will use JWT Authentication. My doubt is when I need to get data from the API without the need to be an authenticated user, how I accomplish this? Using API keys?. I read that API keys are not mean for Authentication but authorization? This will be the case? -
Reverse accessor for 'FullNcr.manager' clashes with reverse accessor for 'FullNcr.user'
I have a form that when posted will assign the current user as the author of that form. I also want to assign a different user as the manager of the posted form but when referencing the user model as a foreign key for the manager it gives the error that it clashes with user. Any help would be great thanks models look like this: from django.db import models from django.contrib.auth.models import User class FullNcr(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) manager = models.ForeignKey(User, null=True, on_delete=models.CASCADE) -
Django-select2 Select2TagWidget on inlineformset
I'm quite lazy so I try to use Django pre-built features at the maximum. My models are : Room (eg bedroom), FurnitureReference (eg bed, lamp ...) RoomFurniture (piece of furniture[FurnitureRerence], quantity...) as a "through" (intermediate model) table I have managed to have an UpdateView with an inline formset that goes like this, each row has: a select to pick the furniture reference multiple inputs for quantity, location ... The inlineformset comes with extra = 5. Everything worked perfectly thus far. Now, if the furniture reference doesn't exist, the user has to add it elsewhere and then come back on this form. I wanted to allow him to create a furniture reference by simply typing a new reference. That's when I found Select2TagWidget. I managed to make it work on a simpler form by customizing the default value_from_datadict method to my needs. But with inlineformset, everything crashes. My issues are : When I submit the form every row is considered modified even the extras which I left empty. When I leave no extras, i get a form error message that says I would be very grateful if anyone could give me a hand on any of these 2 issues, or maybe … -
django.db.utils.IntegrityError: NOT NULL constraint failed: home_post.author_id
I have built a form for posting using Ajax, however, when I click on the submit button i get the error: django.db.utils.IntegrityError: NOT NULL constraint failed: home_post.author_id I do not know what this is as before I had a separate html for creating posts but after using Ajax I am getting this error. This is my Post Model: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(validators=[MaxLengthValidator(250)]) author = models.ForeignKey(Profile, on_delete=models.CASCADE) date_posted = models.DateTimeField(auto_now_add=True) last_edited= models.DateTimeField(auto_now=True) likes= models.ManyToManyField(Profile, blank=True, related_name='post_likes') This is my post form: class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title','content',) This is my create_post view: @login_required def post_create(request): data = dict() if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): form.save() data['form_is_valid'] = True posts = Post.objects.all() data['posts'] = render_to_string('home/homepage/home.html',{'posts':posts}) else: data['form_is_valid'] = False else: form = PostForm context = { 'form':form } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) This is my Ajax Javascript code: $(document).ready(function(){ var ShowForm = function(){ var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType:'json', beforeSend: function(){ $('#modal-post').modal('show'); }, success: function(data){ $('#modal-post .modal-content').html(data.html_form); } }); }; var SaveForm = function(){ var form = $(this); $.ajax({ url: form.attr('data-url'), data: form.serialize(), type: form.attr('method'), dataType: 'json', success: function(data){ if(data.form_is_valid){ $('#post-list div').html(data.posts); $('#modal-post').modal('hide'); } else { … -
Django user profile only shows logged in user information
I am attempting to create a website where all user profiles are public. I have used AbstractUser for any changes to the base user model later on. I made the remainder of the user information in a UserProfile model. As of now, regardless of the profile I click on I am only seeing information for the currently logged-in user. This is my first time using class-based views and I think I'm veering off into the wrong direction. # users/models.py import uuid # for profile slugs from django.db import models from django.conf import settings from django.db.models.signals import post_save # signal for profile creation from django.contrib.auth.models import AbstractUser # import base user model for profile from django.dispatch import receiver from allauth.account.signals import user_signed_up class CustomUser(AbstractUser): pass class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) city = models.CharField(max_length=60, default="") ... profile_uuid = models.UUIDField( primary_key=False, default=uuid.uuid4, editable=False, unique=True ) # to use as a "slug" for profiles def __str__(self): return self.user.first_name @receiver(post_save, sender=CustomUser) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) I'm trying to use the profile_uuid as my "slug" for the URL. It will come up as "https://example.com/profile/". # urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', … -
Trouble with model queries in Django
I have two models, as shown below: class Paper(Model): owner = ForeignKey(User, on_delete=CASCADE,) category = ForeignKey(Category, on_delete=CASCADE,) citation = TextField() paper = FileField(upload_to=user_directory_path) title = CharField(max_length=500) year = IntegerField() class Notes(Model): paper = ForeignKey(Paper, on_delete=CASCADE,) notes = TextField() owner = ForeignKey(User, on_delete=CASCADE) I'm trying and failing to form the appropriate Python code to return two different query sets: The first queryset should contain all Paper objects where a Notes object exists for the currently logged in user (i.e., a paper in this list means the user has submitted notes for the paper). The second queryset should contain all Paper objects where a Notes object does not exist for the currently logged in user (i.e., a paper in this list means that the user has not yet submitted their notes) Multiple users may submit notes for the same paper. My first attempts (with hard-coded values for testing): Paper.objects.exclude(notes__owner_id=3) # I would expect this to return Paper objects that don't have a Notes object for user with ID 3, but might have other notes objects associated with them Paper.objects.filter(notes__owner_id=3) # I thought this might return the opposite of the first but doesn't -
Django Menu and Sub_menu cannot display Sub menu properly
I am trying to displaying Menu and Sub Menu in table format like. Menu1 Menu2 SubMenu1 SubMenu2 SubMenu3 Menu3 SubMenu4 SubMenu5 SubMenu6 Menu4 but i'm getting wrong. menu1 submenu1 menu2 submenu2 and when I'm adding new submenu it's appearing under both main menu my models.py for menu app from django.db import models class Menu(models.Model): menu_name = models.CharField(max_length=100,blank=True) menu_slug = models.SlugField(max_length=100,unique=True,blank=True) menu_icon = models.ImageField(upload_to="imagemenu",blank=True) def __str__(self): return self.menu_name class Submenu(models.Model): submenu_name = models.CharField(max_length=100,blank=True) submenu_slug = models.SlugField(max_length=100, unique=True,blank=True) submenu_icon = models.ImageField(upload_to="imagemenu",blank=True) parent_menu = models.ManyToManyField(Menu, verbose_name=("Mtavari Menu")) def __str__(self): return self.submenu_name my views.py from django.shortcuts import render from django.http import HttpResponse from menu.models import Menu,Submenu # Create your views here. def HomePage(request): template = "front/Homepage.html" menu_item = Menu.objects.all() menu_submenu = Submenu.objects.all() return render(request,template, {"menu_item":menu_item,}) template file <ul> {% for menu in menu_item %} <li> <a href="#">{{menu.menu_name}}</a> <ul class="sub-menu"> {% for sub in menu_submenu %}<li><a href="index.html">{{sub.submenu_name}}</a></li>{% endfo %} </ul> </li> {% endfor %} </ul> -
get username of facebook account using django
I make a web application using django framework and I want to get username of facebook account who press or click a specific link like google or any link I will give it to him to know who is pressed the anchor link any idea that can help me please and thanks -
How to delete the parent object related through a many to many field?
I have three related models - Document, Collection, and CollectionDocument. A Collection object is made up of a group of documents. class Document(Model): document_id = models.AutoField(primary_key=True) class Collection(Model): collection_id = models.AutoField(primary_key=True) document = models.ManyToManyField(Document, through='CollectionDocument', related_name='collections',) class CollectionDocument(Model): collection_id = models.ForeignKey(Collection, on_delete=models.CASCADE, ) document = models.ForeignKey(Document, on_delete=models.CASCADE, ) In the Djangop Admin, I have a DocumentAdmin and a CollectionAdmin with the CollectionDocument as inlines in the CollectionAdmin. When I delete all the documents associated with a Collection, I also want the Collection to be deleted. Right now, when I delete the documents in a Collection, the CollectioDocument is empty, but the Collection still exists without any documents associated with it. I have tried several ways to do it using pre- and post-delete signals for the CollectionDocument model, but nothing seems to work. Have I structured my models incorrectly? How do I get the Collection to be deleted when all the associated Documents are deleted? Thanks! Mark -
How to include additional details in Django admin error reporting?
I'm using the process described in https://docs.djangoproject.com/en/3.0/howto/error-reporting/ to have my application send me error reports. I've noticed that these error reports are sent for both unhandled exceptions (for example a KeyError raised somewhere in my view, and not caught) as well as when my view returns a 500 Response intentionally. For example, one of my views handles an exception raised by a 3rd party library, and returns a 500 Response with some additional details about the exception like so: def post(self, request, pk): try: # something except (ExceptionFromSomeLibrary) as ex: return Response( data=ex.to_dict(), # I'd like this info to be included in the error report status=status.HTTP_500_INTERNAL_SERVER_ERROR ) #... When this exception occurs, the response returns as expected, and I receive an admin email. This email, however, doesn't contain a traceback (since the exception was handled) and does not include any of the information I sent back to the client (data=ex.to_dict()). It only shows me that a 500 Response was returned, and the route from which it originated: # example body of the email Internal Server Error: /api/releases/511/ Report at /api/releases/511/ Internal Server Error: /api/releases/511/ # below this are the request details and Django settings etc. Is there a way that … -
Can run server via "python manage.py runserver"
I want to run my virtual env. via "python manage.py runserver" but alway get this message "RuntimeError: __class__ not set defining 'AbstractBaseUser' as <class 'django.contrib.auth.base_user.abstractbaseuser'="">. Was __classcell__ propagated to type.__new__?" Does anyone know what causes this problem? I'm using Django 1.10 and Python 3.5.8 Thanks in advance, Chris -
Multiple Google Charts in Django Template in a loop or other suitable data vizualisation
I have a Django Template. The Template loops through elements as follows: {% for x in queryset %} code {% endfor %} and prints a table with numbers, eg. 10 rows x 4 columns. - For every row I want to take 4 numbers and bild a separate chart for every row, if possible after every row. But the Google chart appears on the same place and instead of 10 expected charts after every row, I get only one chart on the top of the page. - Is there a way to display one or more different charts for every row in a loop, using Google Charts? - Is Google Charts the proper solution for such a task? Which simple visualization package could be a solution. - Thank you.