Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get generic model from content_type model in django
I'm stack with this problem, I have a model which has a generic relation that every model save the same field here. What I wanted to do is to include the generic relation from the model that I'm trying to query. I try to use prefetch_related with related_query_name but seems it doesn't work. and I got an error. Here is my scenario code: class Some1_Model(models.Model): ... fields ... def __str__(self): return f'({self.field}) {self.field}' class Meta: db_table = 'tbl_name' class Some2_Model(models.Model): ... fields ... def __str__(self): return f'({self.field}) {self.field}' class Meta: db_table = 'tbl_name' class ContentTypeModel(models.Model): content_type = models.ForeignKey(ContentType, blank = True, null = True, on_delete = models.CASCADE) object_id = models.PositiveIntegerField(blank = True, null = True) content_object = GenericForeignKey('content_type', 'object_id') ... customize_fields ... def __str__(self): return self.field class Meta: db_table = 'tbl_name' What I'm trying to try: # Where I should put the generic relation model here? Model.objects.prefetch_related('other1_fk').prefetch_related('other2_fk').filter(pk = self.kwargs[self.pk_url_kwarg]) -
I am trying to play my vimeo videos in my website only, for that i restricted the video to domain-level privacy but still its showing Error
I have a django websites where i want to embed my own vimeo videos and i want the video to play in my website only. For that i restricted the video to domain-level privacy. But still its showing error - Because of its privacy settings, this video cannot be played here.(in my website). Please help me to play the video. <iframe class="embed-responsive-item" src="{{ video_link }}" allowfullscreen></iframe> In this way i am embedding video. Even when i am doing curl request by passing the referral(my website domain), its return 200 -
nvim coc-pyright can't get django 'objects'
I don't know why my coc-pyright cannot access member 'objects' in django. The code works just fine, but autosuggestion box doesn't work because pyright can't read 'objects'. It only suggests that are used in the same working file. Pyright reportGeneralTypeIssues Cannot access member "objects" Member "objects" is unknown [init.vim] coc plug install]2 I've downloaded COC through vim-plug [init.vim] coc plug config coc-settings.json I just copy paste these lines from somewhere.. I think I am doing something wrong with my coc-settings.json file, but don't know how to set it right. my coc-pyright version not found coc-pyright version I checked through CocList extensions I am using: Apple M1 BigSur NVIM (0.5.0) COC Django (3.2.5) Using miniforge python is located in /opt/homebrew/caskroom/miniforge/base/bin/python3 it seems my homebrew manages every files that were downloaded through 'brew install' directories are in '/opt/homebrew/Cellar' not in 'usr/local/Cellar' -
Migrate command in django giving error when deployed to heroku
So i was trying to deploy a django app to heroku which works fine locally. Though the deployment process completes successfully but the migrate command gives an error. django.db.migrations.exceptions.NodeNotFoundError: Migration accounts.0001_initial dependencies reference nonexistent parent node ('auth', '0013_alter_user_email') Here is my migration file; import accounts.models from django.conf import settings import django.contrib.gis.db.models.fields from django.db import migrations, models import django.db.models.deletion from django.contrib.postgres.operations import CreateExtension class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('auth', '0013_alter_user_email'), ] operations = [...] -
python django django.db.utils.OperationalError: table pybo_question has no column named content error?
I was studying django with my book but I have met a unknow error This is the error django.db.utils.OperationalError: table pybo_question has no column named content I have two tables in my models.py Question and Answer. from django.db import models class Question(models.Model): subject = models.CharField(max_length=200) content = models.TextField() create_date = models.DateTimeField() class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) content = models.TextField() create_date = models.DateTimeField() After I finished writing q.save() the error came out. In my python interpreter: from pybo.models import Question, Answer q = Question(subject=hi', content='hello.' , create_date=timezone.now()) q.save() -
Query filter isn't returning object
I'm trying to get this audience object, that currently has its date set to 30/07/2021 (tomorrow), using the following querysets: print("qset 1:",Audience.objects.filter(start_date__year=self.year, start_date__month=self.month)) print("qset 2:",Audience.objects.filter(start_date__year=self.year, start_date__month=self.month, lawyer=lawyer)) But it returns nothing. So I decided to try and check manually with those... aud=Audience.objects.get(id=3) print("lawyer:",lawyer,"date",self.month,self.year,aud.start_date.month,aud.start_date.year) if aud.start_date.month == self.month: print("month") if aud.start_date.year == self.year: print("year") ... and got the return I was expecting on the console lawyer: marcosv1 date 7 2021 7 2021 month year qset 1: <QuerySet []> qset 2: <QuerySet []> qset 3: <QuerySet []> Can anyone identify the issue on this? I've spent several hours, with nothing coming to mind. -
Django pass checkbox state to view.py when clicked
Hello I'm trying to pass a change in a checkbox when this box is clicked. I'm trying to accomplish this by using Ajax, but for some reason I'm unable to accomplish this. When the checkbox is clicked I'm able to see that it's clicked in my logs. HTML/JAVASCRIPT/AJAX: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="row"> <div class="col-sm-10"> {{ map|safe }} </div> <div class="col-sm-2"> <form method="POST" id="form_legend"> <h3><span style="color: #e8c4b4;">Places</span></h3> <div class="form-check"> <input type="checkbox" class="form-check-input" id="check_legend" name="cities"> <label class="form-check-label" for="check_legend">Cities</label> </div> <div class="form-check"> <input type="checkbox" class="form-check-input" id="check_legend" name="poi"> <label class="form-check-label" for="check_legend">Points of Interest</label> </div> </form> </div> </div> <script type="text/javascript"> $("input[type=checkbox]").on("change",function(){ var names = []; $('input[type=checkbox]:checked').each(function () { names.push($(this).val()); }); $.ajax({ url: '/api/post_form/', type: "POST", dataType: "json", data: {names: names}, cache: false }).done(function(data) { if (data.result === true){ alert(data.message); } }); }); </script> url.py: path('api/post_form/', post_form_api, name="post_form_api"), Part in view.py that captures the ajax response: @csrf_exempt def post_form_api(request): data = {} if request.method == "POST" and request.POST.get('names', None) is not None: form_field1 = request.POST.get('names') # save the form data and indicate success data['result'] = True data['message'] = "Form saved successfully" if request.is_ajax(): return JsonResponse(data) else: return HttpResponseBadRequest() Another part in view.py where I try to read and print the checkbox states: def test_view(request): if request.method … -
Django multi-table query with an exclusion condition based on the max value in one table. Using SQL Server
Currently trying to get the Django ORM to build a table that excludes from table 1 where a certain condition is met in table 2. I have build the query using the connection.cursor approach but when I attempt to run the filter form over it I get an error about the object having no component called model (outputs a dictionary). Models class Table2(models.Model): User_id = models.IntegerField() UserFirstName = models.CharField(max_length=100) UserLastName = models.CharField(max_length=100) UserName = models.CharField(max_length=100) Action = models.CharField(max_length=100, choices=Action_Choices) Outcome = models.CharField(max_length=100, choices=Outcome_Choices) Notes = models.TextField(blank=True, null=True) Account_Number = models.DecimalField(max_digits=18, decimal_places=0, null=True) action_time = models.DateTimeField(default=timezone.now) Follow_up_date = models.DateField(blank=True, null=True) def __str__(self): return self.User_id class CreditOpsPropertyAllocation(models.Model): acct_num = models.DecimalField(max_digits=18, decimal_places=0, primary_key=True) cust_num = models.DecimalField(max_digits=9, decimal_places=0, blank=True, null=True, verbose_name='Customer Number') total_due_amt = models.DecimalField(db_column='TOTAL_DUE_AMT', max_digits=18, decimal_places=2, blank=True, null=True, verbose_name='Total Due') curr_due_amt = models.DecimalField(db_column='CURR_DUE_AMT', max_digits=18, decimal_places=2, blank=True, null=True, verbose_name='Current Due') deferred_charges_amt = models.DecimalField(db_column='DEFERRED_CHARGES_AMT', max_digits=18, decimal_places=2, blank=True, null=True) overdue_amt = models.DecimalField(db_column='OVERDUE_AMT', max_digits=18, decimal_places=2, blank=True, null=True, verbose_name='Overdue') billing_sub_group = models.CharField(db_column='Billing Sub Group', max_length=30, blank=True, null=True, verbose_name='Suburb') grange_luc_type = models.CharField(db_column='Grange LUC Type', max_length=20, blank=True, null=True, verbose_name='Land Use Code') land_use = models.CharField(db_column='Land Use', max_length=30, blank=True, null=True, verbose_name='Property Type') kcrm_flag = models.IntegerField(db_column='KCRM FLAG', blank=True, null=True, verbose_name='KCRM') recovery_code = models.CharField(db_column='Recovery Code', max_length=40, blank=True, null=True) entitled_flag = models.CharField(db_column='Entitled Flag', max_length=20, blank=True, … -
Adding data to Django
I'm working on an existing, fairly large, Django application. It has the 'django.contrib.auth' app in settings.py so it already has User and Group models. I'm trying to use the Group to restrict a list of users in two ways: Hide a web page element (button) from users are in a new group "guides" Prevent the same users from being able to invoke the API endpoint URL directly I think I can do this by adding the new group "guides" to the Group model and then adding a list of users to that group. My question is how to create the new group and add the list of users to that group in a way that can be moved to our Dev, State, and Prod environments, but only occur one time during deployment (CircleCi). Any suggestions or ideas would be greatly appreciated, thanks! Doug -
django project: Bad understanding
I tried understanding the link between django models, views, urls and models My real issue is to get a perfect understanding on how the data is finally stored in the db! If anyone can be of help please it's an emergency. -
Django admin - customize form-field
I need to customize a form in the admin-panel. One form's field is a long combobox (2000+ positions). It should be like when I type some text and get filtered positions. I can implement it in HTML-file with select2, but how can I include it in Django-admin panel? The additional dificulty is this field is inside inlines. Maybe, there is a better way to implement it. -
Create a thumbnail Python Django
#Model class Article(models.Model): title = models.CharField(max_length=200, verbose_name='Name',) photo = models.ImageField(upload_to='news/%Y/%m/%d/', blank=True, verbose_name='Image') def __str__(self): return self.title def get_absolute_url(self): return reverse('article', kwargs={'art_id': self.id}) How to make a thumbnail of the image, rename it to "* _thumb.jpg", and place it in the same directory where the file is saved? -
TemplateDoesNotExist at /file_name error in django
I am facing this issue and I believe I have done everything I ought to do. This is my settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'interconceptapp', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'interconcept.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'interconcept.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'interconcept/interconcept/static') … -
Deleting Django model data on button click
I am creating a donation application where people can donate stuff. On one of my screens, I have an accept button. Basically I want this button to delete the currently viewed donation. I have done research, and found out it has something to do with a pk. Can someone please help me do this? For clarity, I want to delete the donation and redirect the user after the accept button is clicked. My Class Based View (To render out each donation): class DonationDetail(DetailView): model = Donation queryset = Donation.objects.all() template_name = 'acceptdonation.html' My button (I want to delete the currently viewed data after this is clicked) <button>Accept</button> My URL (There is one for every donation) path('donations/<pk>/', views.DonationDetail.as_view(), name='donation-detail'), -
Does Django have any front end features?
I was wondering if the Django framework had any frontend features? I've heard quite a lot about Django, especially about their backend features, but I'm uncertain if Django has any frontend features too (as does React, Vue.js). I'm not as good at JS as I am at Python, so I was just trying to maximize the features for Django. Thanks. -
Model Form is not saving data
model.py ''' class Appointment(models.Model): patient = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) blood_pressure = models.CharField(max_length=10) BMI = models.CharField(max_length=10) blood_sugar = models.CharField(max_length=10) HB = models.CharField(max_length=10) platelets = models.CharField(max_length=10) date = models.CharField(max_length=30) time = models.CharField(max_length=30) detail = models.TextField() doc_name = models.CharField(max_length=100) def __str__(self): return self.patient.name ''' forms.py class AppointmentForm(ModelForm): def __init__(self, *args, **kwargs): super(AppointmentForm, self).__init__(*args, **kwargs) self.fields['patient'].disabled = True class Meta: model = Appointment fields = '__all__' views.py def appointment(request): docname = request.POST.get('docname') if request.method == 'POST': form = AppointmentForm(request.POST) if form.is_valid(): form.save() return redirect('success') form = AppointmentForm(initial={"patient":request.user}) form = AppointmentForm(initial={"doc_name": docname}) return render(request, 'appointment.html', {'form': form}) My form is not saving data appointment.html <form action="." method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="SUBMIT"> </form> </html> I am new to django, I created a form to save Data into my database but its not working, I got no error but data is not sent in database. I've tried every thing but cant find any problem. Thank you in Advance. -
How to email a unique link to user django allowing them to confirm availability for an event (and update the database as well)
Here is the problem: I have a model called invite and a model called person. An invite is associated to a person and a person only and it has a field called status. How can I send generate a url that I can then send to the person through an email so that if they click they can confirm availability to the invite and update the status. I am thinking about using the UUID of the invite and adding a line on the urls.py calling a view that updates the status of the invite with uuid. But I wonder if there is a better way that doesn't expose the UUID. -
How to call a function that requires argumets in a template - Django
I have the following button: <a href="{'url acceptdonation pk = donation.pk'}" >Delete</a> In my acceptdonation function: def acceptdonation(request, pk): deleteitem = Donation.objects.filter(id = pk) deleteitem.delete() return HttpResponseRedirect('/dashboard/') As you can see in the code above, I want to pass a pk into the function when the delete button is clicked, and delete the Donation associated with it. Something that seems so easy would not work, so I did research online. I found out that you can not pass arguments into a function from a template. How can I make it so when my delete button is clicked, the Donation associated with the pk gets deleted? -
How to use OneToOneField/ForeignKey fields in django admin fieldsets
I am trying to create an admin page for business managers to create and update db models easily, as they are not comfortable with relational db concepts. The model in question has its own fields and a 1:1 relationship with Django auth user model. This is a simplification of this model: class Student(AbstractTimeStampedModel): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) owner = models.OneToOneField( "auth.User", related_name="student", on_delete=models.CASCADE ) # other irrelevant fields What I would like to achieve is to be able to create or update a student owner's first_name, last_name and email trough the StudentAdmin class. This is a simplification of the admin class in question: class StudentAdmin(admin.ModelAdmin): fieldsets = ( ( _("Personal information"), {"fields": ("owner", "phone")}, ), ( _("Additional Information"), {"classes": ("collapse",), "fields": ("interest", "deactivated")}, ), ) The owner included in the fieldsets attribute works just fine, but it is a dropdown and it is required to open a new tab to create/update the owner. I have tried to use owner__first_name, etc. or owner.first_name, etc. within fieldsets, but it is not working. I get the following error: Unknown field(s) (owner__email, owner__first_name, owner__last_name) specified for Student. Check fields/fieldsets/exclude attributes of class StudentAdmin. Is there a way to use OneToOneField/ForeignKey fields in an … -
Can I decorate a Django REST Framework ModelViewSet Methods?
Django REST Framework ModelViewset offers the standard methods to update / create / retrieve objects. I would like to overwrite these method in the sense that they should keep their original behaviour as given by ModelViewSet, but just add to that a check in the beginning if the incoming request contains a certain query parameter. How can I do that? Eg. I would like to have class MyRessourceViewSet(viewsets.ModelViewSet): queryset = MyRessource.objects.all() serializer_class = MyRessourceSerializer def create(self, request): # Check if "key" query param is in request if "key" in self.request.data: create(request) # <<-- HERE call the "default" create method. -
How to add an additional python package to the Pipfile of a docker-compose project (DJANGO)?
Good day everyone, hope you're doing really well. I would like to start this question by prefacing that I'm a real newbie when it comes to setting up projects in the right way. Right now I'm working on a Django app with a friend that already has some more experience with web development and he had already set up everything with Docker-compose, that is, we have containers for our Django app, MySQL, Celery, RabbitMQ, etc. Now, I'm working on the back-end side of our project and need to add a new package to the list of packages the app container has: Smart-Open. The thing is, I have no idea how to do that. I'm on Windows, and using Git Bash to launch the docker-compose containers. What I've tried is opened the bash of the web app container and tried to pipenv install the module from there, but it was extremely slow, which made the Pipfile updating timeout: $ winpty docker exec -it whs_webapp_1 bash root@96caa176d252:/app/my_app_name# pipenv install smart_open[s3] Creating a virtualenv for this project… Using /usr/local/bin/python3.9 (3.9.6) to create virtualenv… ⠋Running virtualenv with interpreter /usr/local/bin/python3.9 Using base prefix '/usr/local' /usr/lib/python3/dist-packages/virtualenv.py:1090: DeprecationWarning: the imp m import imp New python executable in … -
Djoser: Password Reset with Username
I have developed an app using Django. It uses Djoser for user authentication. Problem: I have allowed user to register with already existing email addresses i.e. there might be multiple users using same email ID. So I can't reset password with the email field. Either I must use username only or the combination of username and email. How can I do this? Note:- Using base endpoint /users/reset_password/ but it requires email only to reset the password. -
Custom User PK (Primary Key) - Django - Python
I built a website with Python Django and part of it displays lines of already input data with the primary key next to it. Now I have separate user data by using a foreign key field in each one of my models and the specific user's data is only shown to that logged in user except that all the data regardless of the user is saved in one spot with the model shown in the admin interface(because I'm using foreign keys to separate data). My problem is that I need to display the primary key of just the logged-in user. Take this, for example, if User1 adds 1 line of data to their page then User2 adds 1 line of data on their page which will appear separate from one another, then User1 uploads another line of data, Then I user traditional primary key to number the data lines of User1 the numbers will be 1 and three instead of keeping them in numerical order of 1 and 2 and disregarding User2's data in the counting of the data. It's as if I need a separate primary key for each user. Sorry this is really hard to explain. I have … -
How do I make this (Django) comment form explicitly use the "POST" method on a post_detail page?
Working on the Mozilla diy blog app challenge. With tips from this tutorial, the comment form finally appears on the post_detail page. But adding a comment leads to a "Method Not Allowed" error. Searching on SO and elsewhere led me to believe the offending "method" is a "GET" method when it should be "POST". I understand the post detail page needs a GET method to display all the comments--but adding a comment via a form on that page needs to be using POST, but I am not sure how that's done--or why my code doesn't work. GitHub repo link is here. class Post(models.Model): post = models.TextField(max_length=1000) post_title = models.CharField(max_length=100) description = models.TextField(max_length=500) post_created_at = models.DateTimeField(auto_now_add=True) post_updated_at = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, related_name="posts", on_delete=models.CASCADE) @property def num_comments(self): return Comment.objects.filter(post_connected=self).count() class Meta: ordering = ['-post_created_at'] class Comment(models.Model): comment_title = models.CharField(max_length=100) comment = models.TextField(max_length=1000) comment_created_at = models.DateTimeField(auto_now_add=True) comment_updated_at = models.DateTimeField(auto_now=True) commenter = models.ForeignKey(User, related_name="commented", null=True, blank=True, on_delete=models.CASCADE) post_connected = models.ForeignKey(Post, related_name='comment', on_delete=models.CASCADE, default=None, null=True) # class Meta: ordering = ['comment_created_at'] def __str__(self): return str(self.commenter) + ' : ' + self.comment_title[:40] def get_absolute_url(self): return reverse('post-detail', args=[str(self.id)]) #admin.py @admin.register(Comment) class CommentAdmin(admin.ModelAdmin): list_display = ('comment_title', 'comment', 'comment_created_at', 'commenter') list_filter = ('comment_title', 'commenter') search_fields = ('comment_title', 'comment') … -
Django request url changing to 'django/images' for static files after deployment
This is my settings.py. Used docker compose with nginx to deploy the backend. The images load up fine in the cpanel but the request url changes to http://django/images instead of my server url. tried changing the media url to my server url, but it still doesn't work. Hosted in bluehost vps. STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_ROOT = 'static/images' MEDIA_URL = '/images/'