Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - edit default graphene Set query
i am building a django application with graphql and i have two models Column Model: class Column(models.Model): name = models.CharField(max_length=100) Task Model: class Task(models.Model): column = models.ForeignKey(Column, on_delete=models.CASCADE) content = models.CharField(max_length=255) position = models.IntegerField() and i have a query to query all Columns and their tasks class ColumnType(DjangoObjectType): class Meta: model = Column class Query(object): columns = graphene.List(ColumnType) def resolve_columns(self, info, **kwargs): return Column.objects.all() and i can query this by: { columns { id taskSet{ content } } } but by doing this i cant add fields to taskSet function so i want to add a filter that will get only the first 20 tasks -
Programming error at all URLS in django, postgres cannot find tables in db?
My Django project works fine locally on my machine, but when I deployed it to Heroku. I'm getting an error for all of my urls. My urls include: admin/ blog/ projects/ When I type in a different url, I get the following error: ProgrammingError at /blog/ relation "blog_post" does not exist LINE 1: ...t"."last_modified", "blog_post"."created_on" FROM "blog_post. This occurs at every url. Looking at the traceback, it seems like it has to do with the Templates. Here is the traceback: Template error: In template /app/personal_portfolio/templates/base.html, error at line 3 relation "blog_post" does not exist LINE 1: ...t"."last_modified", "blog_post"."created_on" FROM "blog_post... and File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute 84. return self.cursor.execute(sql, params) The above exception (relation "blog_post" does not exist LINE 1: ...t"."last_modified", "blog_post"."created_on" FROM "blog_post... ^ ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/blog/views.py" in blog_index 12. return render(request, "blog_index.html", context) I'm also thinking it has something to do with the tables/database. I'm currently using SQLite on my local machine, but I know heroku is using postgres. I've deleted the migrations folders … -
How to fix Error: pg_config executable not found on Elastic Beanstalk permanently
I have a Django project that works with PostgreSQL on Elastic Beanstalk. I have found the next error when deploying: Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... I followed psycopg2 on elastic beanstalk - can't deploy app to solve it and it worked! BUT after a while Amazon seems to update my virtual env and the error returns so I have to go back and do the same stuff over and over again. I also have tried configuring the database instance directly from the Elastic Beanstalk panel but nothing changes. The database is on RDS and I think it's important to say that when I manually install psycopg2 on my instance and re-deploy everything works fine, I even have made a couple of deploys after that and the problems is not there but it is after a while. I really want to know how to solve it once for all. Thanks in advance. -
How to use django professionally?
I have just started to do web with django. In my interpretation, templates is the view showing to users, view is to handling the logic. However, I am quite confused on how to do the website better. Lets say I have a dataframe table, and I want to put it in myhtml. But at the same time, I use booststrap button to design my table, which add a button at the last of the row. So I have come up with this solution: for i in len(df.rows): #Loop 'rows' times (I know the syntax is wrong, just the algorithm) temp = df.to_html() #Convert it to string #Adding the button e.g. <td class = xxxxxxxxx> at every last of the row #Lastly #pass it to something like {xxxx|safe} to the html My question is how to do this kind of stuff in a proper way since I think this is quite stupid and hard coding. It is not efficient to convert it to string everytime. -
I want my django app to get a file from a remote machine
I need my django app to scp a file on a remote server into the django 'media' folder. Is spawning an scp session with pexpect in my django app the best way to go about this? Alternatively, are there libraries I can use in my django app to do this? Any help is much appreciate. -
Insert data into intermediary table while submitting main modelform in Django
I have a Task model. I want to assign task to multiple users so i have taken ManytoMany relationship. So Django is creating a ManytoMany table but i want to track that which user has completed task and when. So I took intermediary model by using through='TaskComplete'. Now I can not see task_assign_to feild in form. And even i declare in modelForms and submit it gives below error. Cannot set values on a `ManyToManyField` which specifies an intermediary model. Use audit.Membership's Manager instead. Now I want that admin selects the user from main form and into intermediary model. I tried but can not find any solution for this. below is my code. Please guide me how to do it? My Model: class Task(models.Model): task_audit_title = models.ForeignKey(MainAudit,on_delete= models.CASCADE, related_name='audit_title_for_task',verbose_name= ('Audit Title')) task_subtask_name = models.ManyToManyField(SubTask, related_name='subtask_for_task',verbose_name= ('Subtask Title')) task_subject = models.CharField(verbose_name= ('Task Subject'),max_length=100,blank=False) task_description = models.CharField(verbose_name= ('Task Description'),max_length=1000,blank=True) task_assign_to = models.ManyToManyField(User, related_name='task_assign_to', through='TaskComplete') task_assign_by = models.ForeignKey(User,on_delete= models.CASCADE, related_name='task_crt_by') task_deadline = models.DateTimeField(null=True,blank=True) task_perticulars = models.ManyToManyField(Perticular, related_name='task_perticular', blank=True) task_created_time = models.DateTimeField(default=timezone.now) task_modified_by = models.ForeignKey(User,on_delete= models.CASCADE, related_name='task_mod_by', null=True, blank=True) task_modified_time = models.DateTimeField(null=True,blank=True) is_del = models.BooleanField(default=0) class Meta: permissions = ( ("change_temp_delete_task", "Can delete temporarily"), ) def __str__(self): return self.task_subject def get_absolute_url(self): return reverse('create-task') class TaskComplete(models.Model): … -
Django Overwrite storage not working correctly
I have a model that looks like this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=160, null=True) avatar = models.ImageField(storage=OverwriteStorage(), upload_to=create_user_image_path) if self.avatar: with Image.open(self.avatar) as image: image_path = self.avatar.path image_name = self.avatar.path[:-4] image_ext = self.avatar.path[-4:] resize_images(image, image_path, image_name, image_ext) image.close() Each time a user uploads a picture, I overwrite the storage here: class OverwriteStorage(FileSystemStorage): def get_available_name(self, name, *args, **kwargs): try: file_path = os.path.dirname(name) shutil.rmtree(os.path.join(settings.MEDIA_ROOT, file_path)) except FileNotFoundError: pass return name So basically, because I create a random image name (needed so that browser updates cache), I need to delete the entire files in the directory. This works perfectly, however, after uploading once again after a few seconds I get the following error: PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\Users\xx\xx\xx\media\users\179\avatars \179312.jpg' I see inside FileSystemStorage there's this comment: # There's a potential race condition between get_available_name and # saving the file; it's possible that two threads might return the # same name, at which point all sorts of fun happens. So we need to # try to create the file, but if it already exists we have to go back # to get_available_name() and try again. How do … -
Why Django requires "_id" in the name of ForeignKey field?
I have models for players, teams and matches. Obviously, that I have some ForeignKey field. But if I don't add "_id" in the end of ForeignKey field, Django raises the error: "no such column: betbot_testmatch.leftTeam_id" I have tried to add "_id" in the end of my ForeignKey fields and it really solved the problem, but in my previous project I designed, I have been usin FK fields without any "_id" in the end of field names and there were no problems. models.py from django.db import models class TestMatch(models.Model): leftTeam = models.ForeignKey('TestTeam', on_delete=models.DO_NOTHING, related_name='+', default='Left Team') rightTeam = models.ForeignKey('TestTeam', on_delete=models.DO_NOTHING, related_name='+', default='Right Team') class TestTeam(models.Model): name = models.CharField(max_length=30, default='Team') urlslug = models.SlugField(max_length=5) class TestPlayer(models.Model): name = models.CharField(max_length=100, default='Player') nick = models.CharField(max_length=20, default='Nickname') team_id = models.ForeignKey('TestTeam', on_delete=models.DO_NOTHING, default='Team') #photo = models.ImageField(upload_to='', null=True) No = 'N' Yes = 'Y' STANDIN_CHOICES = [ (Yes, 'Yes'), (No, 'No'), ] standin = models.CharField(max_length=5, choices=STANDIN_CHOICES, default=No) slug = models.SlugField(max_length=20, default=nick) I want that I could use my names for ForeignKey field without the mistake. -
Cannot Edit User on django admin
I try to make second user that contain 'staff' and 'super user' in django admin built in. The result was The cannot saved it self. Then I try to edit my user account through this django admin panel, and it cannot work to. The sistem pop up a message that i have missing some form to edit, but it didn't appear. I don't know what i must do to solve this issue my user model: from django.contrib.auth.models import AbstractUser from django.db.models import CharField from django.urls import reverse from django.utils.translation import ugettext_lazy as _ class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = CharField(_("Name of User"), blank=True, max_length=255) def get_absolute_url(self): return reverse("users:detail", kwargs={"username": self.username}) form: from django.contrib.auth import get_user_model, forms from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from snowpenguin.django.recaptcha2.fields import ReCaptchaField from snowpenguin.django.recaptcha2.widgets import ReCaptchaWidget User = get_user_model() class UserChangeForm(forms.UserChangeForm): captcha = ReCaptchaField(widget=ReCaptchaWidget()) class Meta(forms.UserChangeForm.Meta): model = User class UserCreationForm(forms.UserCreationForm): error_message = forms.UserCreationForm.error_messages.update( {"duplicate_username": _("This username has already been taken.")} ) class Meta(forms.UserCreationForm.Meta): model = User def clean_username(self): username = self.cleaned_data["username"] try: User.objects.get(username=username) except User.DoesNotExist: return username raise ValidationError(self.error_messages["duplicate_username"]) user admin: from django.contrib import admin from django.contrib.auth import … -
How can I generate a multi-step process in Django without changing pages (w/out a new request)?
I have a model (Category) which references itself for its parent category. The categorty's roots can be found with a filter and aggregated into a select dropdown for example. But how would you generate another dropdown with the selected categories sub-category? As far as I can tell, the solution would be to use Django REST api, but it seems like a bit of an overkill just to select a category. Would anyone have any suggestions? My model is: class Category(models.Model): # PK cat_id = models.IntegerField(primary_key=True) # Foreign parent_category = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) # Column name = models.CharField(max_length=128) # the name of the category limit_message = models.CharField(max_length=255, null=True, blank=True) level = models.PositiveIntegerField() # 1 for root (major category) followed by 2, 3 ... is_leaf = models.BooleanField() is_enabled = models.BooleanField(default=True) def __str__(self): return self.name -
How to include the routes of React to django?
I am working on a varsity project which is a web based application.It uses React as frontend and django as backend. Here is my app.js.. function App() { return ( <BrowserRouter> <Route path="signin/" exact component={Signin} /> <Route path="signin/signup/" component={SignUp} /> </BrowserRouter> ); } my django base urls looks like.. urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^dream11/', include('core.urls')), url(r'^api/', include('api.urls')), url(r'^api-token-auth/$', views.obtain_auth_token, name="token" ) ] when i'm going to dream11/signin/ link , django is not showing anything.it gives me the error, Using the URLconf defined in Dream11v3.urls, Django tried these URL patterns, in this order: ^admin/ ^dream11/ ^$ [name='index'] ^api/ ^api-token-auth/$ [name='token'] The current path, dream11/signin/, didn't match any of these. How can I solve this? -
Django 2.2 staticfiles do not work in development
I'm making a new django app where a user can upload images and then they can be displayed on a page. I've read the django docs 10000 times through and I still don't understand why my images aren't loading (DEBUG = True) All my images are going to where they're supposed to be and in the admin in my models django has the right path that leads to the image but it just won't load properly. my setup in settings.py: STATIC_URL = '/static/' STATIC_ROOT = 'static' # live cdn such as AWS S3 STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(STATIC_ROOT, 'media') MEDIA_URL = '/img/' my directories: |- src |- myproject |- settings.py, views.py, urls.py etc |- myapp |- views.py urls.py models.py forms.py etc |- static (this folder is empty and appeared after running collectstatic |- templates |- db.sqlite3 |- manage.py |- static (this folder is OUTSIDE src) |- admin |- django admin stuff |- media |- img |- myimage.png in models.py of myapp the imagefield upload_to = 'img/' as i said, the images don't load on the page but to upload to static/media/img/image_name.png I've been trying to fix this for ages but i can't get any help from … -
How to make DRF with aliready exists Django app?
I would like to create DRF api. In my case, I have already existing Django app. I would like to add api to this existing app. But I don't know how can I define DRF's models. There is a using table in the existing app. So, I run following command python3 manage.py inspectdb I think that I'll reuse those models, but I have a complicated custom user model. How to create DRF app with already existing Django app ? -
In Django Bootstrap 4, how to avoid rendering an alert with form errors?
I'm using django-bootstrap4 (https://django-bootstrap4.readthedocs.io/en/latest/) in a project and find that when there are errors in a form, an alert box shows up with a list of the errors. In my case, this is problematic because the errors are repeated: I've had a look at the FormRenderer source code, and I don't see a way I can opt out of displaying this 'alert of errors': class FormRenderer(BaseRenderer): """ Default form renderer """ def __init__(self, form, *args, **kwargs): if not isinstance(form, BaseForm): raise BootstrapError( 'Parameter "form" should contain a valid Django Form.') self.form = form super(FormRenderer, self).__init__(*args, **kwargs) self.error_css_class = kwargs.get('error_css_class', None) self.required_css_class = kwargs.get('required_css_class', None) self.bound_css_class = kwargs.get('bound_css_class', None) def render_fields(self): rendered_fields = [] for field in self.form: rendered_fields.append(render_field( field, layout=self.layout, form_group_class=self.form_group_class, field_class=self.field_class, label_class=self.label_class, show_label=self.show_label, show_help=self.show_help, exclude=self.exclude, set_placeholder=self.set_placeholder, size=self.size, horizontal_label_class=self.horizontal_label_class, horizontal_field_class=self.horizontal_field_class, error_css_class=self.error_css_class, required_css_class=self.required_css_class, bound_css_class=self.bound_css_class, )) return '\n'.join(rendered_fields) def get_fields_errors(self): form_errors = [] for field in self.form: if not field.is_hidden and field.errors: form_errors += field.errors return form_errors def render_errors(self, type='all'): form_errors = None if type == 'all': form_errors = self.get_fields_errors() + self.form.non_field_errors() elif type == 'fields': form_errors = self.get_fields_errors() elif type == 'non_fields': form_errors = self.form.non_field_errors() if form_errors: return render_template_file( 'bootstrap4/form_errors.html', context={ 'errors': form_errors, 'form': self.form, 'layout': self.layout, 'type': type, } ) … -
Django, JSON serialize queryset and list of models has different behavior
I have a Django model with a function (on the Python class) that modifies some of its fields. I can do this, and it works from django.core.serializers.json import DjangoJSONEncoder json.dumps(list(MyModel.objects.filter(...).values()), cls=DjangoJSONEncoder) Now I'd like to call the function MyModel.MyFunction on all the models before JSON encoding them. I've tried this, but obviously it returns the fields as they are in the database, not modified by MyFunction: from django.core.serializers.json import DjangoJSONEncoder mymodels = MyModel.objects.filter(...) for mymodel in mymodels: mymodel.MyFunction() # or mymodel.myfield = somethingelse json.dumps(list(mymodels.values()), cls=DjangoJSONEncoder) So I've tried this from django.core.serializers.json import DjangoJSONEncoder mymodels = MyModel.objects.filter(...) _mymodels = [] for mymodel in mymodels: mymodel.MyFunction() # or mymodel.myfield = somethingelse _mymodels.append(mymodel) json.dumps(_mymodels, cls=DjangoJSONEncoder) but TypeError: Object of type MyModel is not JSON serializable. I've read on other answers that you'd have to either install django rest framework or implement a to_json function on MyModel. However, I'd like not to clutter my application to achieve a behavior that is already available. How can I tell django to behave the same way on an array of models that it behaves on a queryset of the same model? -
Should I build my tuition website in Phoenix/Elixir
For background, I want to build a tuition site which can help tutors: Be found by students/parents and arrange lessons with said clients Organise their timetables with these students Teach online create my own plugins for the site (e.g. like a homework generator or something like that) Why Phoenix? From my research, even though it's new, it's very good at concurrency and hence should be very scalable if I manage to get a lot of tutors. It's also particularly fast which really sold me too. However, I've just come out of university with a BSci in Comp sci so it's my first proper deployable project. It's a really really enjoyable project (Functional languages are amazing) but I don't want my zeal to give me tunnel vision. I should also say, this is my own personal project that I want to build really to help students that I tutor. It is very fun learning phoenix, but I notice it's quite difficult to troubleshoot as it's not exactly the most popular framework. Stuff like ruby has a lot more tutorials and things like that. Nonetheless, from my surface-level research, phoenix feels perfect with its speed benchmarks. I'm a pretty capable programmer too. … -
Pagination in Django with two Querysets formatted in different ways
I want to get pagination to work with two separate query sets that are formatted in different ways. The first query set is smaller and will never be longer than the first page. The second query set is very long and will go on for 5 or 6 pages. The result content of both query sets are the same, but I format them in different ways in the html template. The models are exactly the same, Book and PremiumBook, except PremiumBook has lots more books (and contains all the elements in Book). I'll include the views.py and then the template: def servicesListView(request, category): model = Books table = Books.objects.filter(category=category) values_books = table.filter().values_list("serviceid") # remove these observations from next table. My next table is premium and not available to non-authenticated users new_table = PremiumBooks.objects.filter(category=category).exclude(bookid__in=values_books) new_table = new_table.filter().annotate(price_count=Count('premiumcost__price')).order_by('-price_count')[:60] page = request.GET.get('page', 1) paginator = Paginator(new_table, 5) try: new_table = paginator.page(new_table) except PageNotAnInteger: new_table = paginator.page(1) except EmptyPage: new_table = paginator.page(paginator.num_pages) return render(request, 'services/index.html', {'table': table, 'new_table': new_table}) Then, this is the template for the them: <main class="ui-book-list"> <div class="results-list grid-view"> <div class="container"> <h2>Book list </h2> <div class="grid-results-list book-list"> {% for book in table %} <div class="record"> <div class="content"> <h6> {{ book.easy_desc }} … -
Views in Django: Sending array with dictionaries
I am looking for a smart solution on how to provide data to my template in django. Given is a array, filled with dictionaries. in the file "views" i have: from .pymodules import url_scraper as spider from .pymodules import url_list def result(request): top10 = spider(url_list) #array filled with dicts return render(request, "result.html", {"top10" : top10} ## example for top10 --> [{"key1" : "value_A"},{"key1" : "value_B"},{"key1" : "value_C"}] Now i have the problem, that everything I try does not give me the "key" : "value" output i want. Trying for something like this: {% x in top10 %} {x[key]} ## key is given {% endfor %} -
Retrieve Data to Populate Table in Django
I have one view which renders a dropdown where a user will select an order number and direct them to another view where there should be a table which populates with all data related to that order #. Each order # has multiple records associated to it - I'm not sure how to properly get this data and display it. This is what I'm trying - but I just keep getting errors, and I have a feeling I'm not approaching this right in the first place. views.py #rendering the dropdown def manifest_reference_view(request): query_results = Orders.objects.all() reference_list = BlahBlah() context = { 'query_results': query_results, 'reference_list': reference_list, } return render(request, 'manifest_reference_view.html', context) #this view should show table with all data relating to user selection def manifest(request): if request.method == 'POST': reference = request.POST.get('Reference_Nos') referenceid = reference form = CreateManifestForm(request.POST, instance=referenceid) manifest = Manifests.objects.all().filter(reference__reference=referenceid) #order = Orders.objects.get(reference=reference) if form.is_valid(): form.save() return redirect('display_orders') else: form = CreateManifestForm(instance=referenceid) return render(request, 'edit_manifest_frombrowse.html', {'form': form}) forms.py class BlahBlah(forms.Form): Reference_Nos = forms.ModelChoiceField(queryset=Orders.objects.values_list('reference', flat=True).distinct(), empty_label=None) class CreateManifestForm(forms.ModelForm): class Meta: cases = forms.IntegerField(widget=forms.TextInput(attrs={'placeholder': 'Enter Cases'})) model = Manifests fields = ('reference', 'cases', 'product_name', 'count', 'CNF', 'FOB') edit_manifest_frombrowse.html {% extends 'base.html' %} {% block body %} <div class="container"> <form id="create_mani_form" method="POST"> … -
How to set CELERY_TASK_QUEUES so that django-celery-beat uses "default" queue?
In my django admin interface, it shows this under the Periodic Tasks table from django-celery-beat I need my beat tasks to use the queue: 'default', which is doesn't by default. I can't find any reference to CELERY_TASK_QUEUES in any documentation. How do I set the default queue to 'default' for django-celery-beat periodic tasks? -
how to pass parameters from views django to the template
what is the error in my code because i have been trying to pass the variable for several hours without any success. Yet i know that i can send it as dictionary. so i am using a form that will allow user to enter the folder number and then it will be send it to the views using ajax call to get the request and store it in the database then it render the dropDown.html and display the folder number using Django Tags and it print the value correctly in the cmd. all the process is done but concerning the display in the template , it display nothing. create_folder.html <form> <!-- problem in formInput vs radioBtn --> <div id='left-column-Input'> <!-- <div class="formInput" id="fileIDfield"> <input type="text" id="fileID" value = "{{dbfolder.id}}" name="fileID" autocomplete="off" required /> </div> --> <div class="formInput" id="fileNum"> <input type="number" id="fileNumField" name="fileNum" autocomplete="off" required /> <label for="fileNum" class="label-name"> <span class="content-name" name="fileNum">folder number</span> </label> </div> <div class="home-Button" id="linkFormDiv"> <button id="linkForm" name="formSave" type="submit">Link</button> </div> </form> <script type="text/javascript"> $(document).ready(function(){ $("#save").on('click',function(event){ event.preventDefault() // MalafID = $('#fileIDfield').val() MalafNum = $('#fileNumField').val() $.ajax({ url: '/folder/', method: 'POST', data:{ FolderNum: MalafNum, } headers:{ 'X-CSRFToken':'{{csrf_token}}' } }).done(function(){ // alert('done redirecting to Person Module') alert('Folder saved') // this line will … -
DRF - Add get_FIELD_display fields (AssertionError)
I want to modify a serializer such that it contains FIELD_display field for every field which has any choices, the value is get_FIELD_display. I'm trying to dynamically add those fields inside __init__ method but it returns error: The field 'subcategory_display' was declared on serializer ApiRealestateSerializer, but has not been included in the 'fields' option. serializer class ApiRealestateSerializer(serializers.ModelSerializer): subcategory_display = serializers.CharField(source='get_subcategory_display') class Meta: model = RealEstate fields = [x.name for x in RealEstate._meta.fields] def __init__(self, instance=None, data=None, **kwargs): super().__init__(instance, data, **kwargs) self.set_display_fields() def set_display_fields(self): """adds FIELD_display field for every CharField (eg. name = "peter", name_display = "Peter" )""" for field in RealEstate._meta.fields: if field.choices: fieldname = f"{field.name}_display" self.fields[fieldname] = serializers.CharField(source=f'get_{field.name}_display') self.Meta.fields.append(fieldname) Do you know how to make it work? -
Cross validation in Django Admin between Parent and Child inline models
I have a Post model, which can contain either images or links to videos, or both. The requirement is that every Post must have at least one image or one link to video. My current problem is I don't know where to place the correct validation to make. I tried to override the functions add_view and change_view in PostAdmin but could not make it work. I also tried to make some validations in ImagenPostAdminFormSet and VideoLinkPostAdminFormSet, but were useless as either of them can be empty, but not both. Following is my code for the models: class Post(models.Model): .... nombre_post = models.CharField('Nombre del Posteo', max_length=255) descripcion = models.CharField('Descripción', max_length=255) .... class ImagenPost(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="imagen_post") imagen_post = ContentTypeRestrictedFileField('Imagen del Posteo', upload_to=media_posteos, help_text='Formatos válidos: jpg, jpeg, gif, png') ... class VideoLinkPost(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="video_link_post") video_link = EmbedVideoField('Link de Video', max_length=150, help_text='Ingresar Link de Video') ... Following the code for Admin: class ImagenPostAdminInline(admin.StackedInline): model = ImagenPost form = ImagenPostAdminForm formset = ImagenPostAdminFormSet extra = 1 class VideoLinkPostAdminInline(admin.StackedInline): model = VideoLinkPost form = VideoLinkPostAdminForm formset = VideoLinkPostAdminFormSet extra = 1 class PostAdmin(admin.ModelAdmin): form = PostAdminForm inlines = [ImagenPostAdminInline, VideoLinkPostAdminInline] As I said, the validation to make is that one … -
How to interpret an SQL Query to Django Queryset
What is the best way to read and interpret a raw SQL query and convert it to Django QuerySet, Im having trouble to understand with the alias and the join For example: select sum(balance_amount) balance_amount from account_balance a join public.account_catalog b on a.account_id=b.id where b.account_type in accounts and a.balance_date in date and bank_id in bank -
Issues with HyperlinkedModelSerializer with recursive model
Overview I'm setting up a new Django application with Django REST Framework (DRF), and this is my first time using the HyperlinkedModelSerializer for the API endpoint. I've overridden the get_queryset() method on the ModelViewSet, so I've also the basename argument to the application router and explicitly defined the url attribute in the serializer as suggested here. This fixed issues that I was having with the model's own url attribute. However, I'm getting the following error message when trying to serialize a ForeignKey field of the same class as the parent model. It fails with the following message: Could not resolve URL for hyperlinked relationship using view name "employee-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. Is there something special in the serializer I need to do to support using recursive model relationships like this? Example code # app/models.py from django.db import models class AbstractBase(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: abstract = True class Employee(AbstractBase): name = models.CharField(max_length=254) manager = models.ForeignKey('self', related_name='direct_reports', on_delete=models.SET_NULL, blank=True, null=True) ... def __str__(self): return str(self.name) # app/views.py from rest_framework import viewsets from rest_framework.pagination import PageNumberPagination from app import models …