Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
First argument to get_object_or_404() must be a Modelt, not 'function'
First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'function'. I'm trying to show tablet details based on the tablet in the database but it keeps getting this ValueError. Can anyone help me find out what I am doing wrong? this is my views.py from django.shortcuts import render, get_object_or_404 from .models import PharmaceuticalCapsules, PharmaceuticalSuspension, PharmaceuticalPowder, PharmaceuticalSyrup, \ PharmaceuticalTablet def alltablet(request): tablet = PharmaceuticalTablet.objects return render(request, 'tablets.html', {'tablet': tablet}) def tabdetail(request, tab_id): tabdetail = get_object_or_404(alltablet, pk=tab_id) return render(request, 'tab_detail.html', {'tablet': tabdetail}) this is my models.py from typing import re from django.db import models class PharmaceuticalTablet(models.Model): tab_name = models.CharField(max_length=100) tab_image = models.ImageField(upload_to='image/', blank=True, null=True) tab_dose_strength = models.CharField(max_length=100) tab_pack = models.CharField(max_length=100) tab_form = models.CharField(max_length=200) tab_dose = models.CharField(max_length=100, default='Direction By Physician') tab_storage = models.CharField(max_length=100) tab_usage = models.CharField(max_length=100) tab_brandname = models.CharField(max_length=100) tab_composition = models.CharField(max_length=100) def __str__(self): return self.tab_name browser shows ValueErrorat /tablet/1/ First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'function'. Request Method: GET Request URL: http://127.0.0.1:8000/tablet/1/ Django Version: v2.2.1 Exception Type: ValueError Exception Value: First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'function'. -
How to perform Update, Delete operation in Django rest framework
I want to perform Update and Delete operation in Django rest framework, I did Get and Post operation. I'm new to django, Please help me to do Update and Delete operation. views.py class StudentViews(viewsets.ModelViewSet): queryset = Student.objects.all() serializer_class = StudentSerializer models.py class Student(models.Model): name = models.CharField(max_length=255, blank=True, null=True) contact_number = models.CharField(max_length=12, blank=True, null=True) email = models.EmailField(max_length=100, blank=True, null=True) address = models.CharField(max_length=500, blank=True, null=True) serializers.py class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = '__all__' urls.py router = routers.DefaultRouter() router.register('api/student', views.StudentViews) urlpatterns = [ path('', include(router.urls)), ] -
Connect django and Sql Server
i Connect with django and sqlsever django there in my system but sql server having another one system how to connect both? django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') 'ENGINE': 'sql_server.pyodbc', 'HOST': 'ip-address', 'NAME': 'db name', 'USER': 'user name', 'PASSWORD': 'pwd', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, -
CSS in Django does not register to the console
My CSS files in Django are linked to my project, but the changes that I make in the CSS files do not register in the console. For example, when I change the color to my H1 and save it, nothing has been changed in my project. When I open the console in Chrome, its as if I had not made any changes. -
How to check if session with a specific key has an empty-list value in Django
I'm using two sessions between views. Either those session, with their corresponding ['key'], have a value of empty list or a list with values. As you can observe in the code,the request session key is always existing because it's been set up with list either empty or not. The problem is , even though the list has values, it behaves as if it is empty. It always goes with the else block in the template of second view. View 1: initializing the list and setting up sessions def apply_fees(request): included = [] excluded = [] if request.POST: form = applyfees_form(request.POST) if request.POST.get('applyBtn'): checks_list = request.POST.getlist('checks') payment_id = request.POST.get('fee_selection') for item in checks_list: stud = User.objects.get(username=item) fee = Fee.objects.get(payment_id=payment_id) obj, created = FinedStudent.objects.get_or_create(pays_id=fee, stud_id=stud) if created: name = stud.first_name + ' ' + stud.last_name excluded.append(name) else: obj.save() name = stud.first_name + ' ' + stud.last_name included.append(name) request.session['included'] = included request.session['excluded'] = excluded return render(request, 'studentapp/confirmApplyFees.html') I can say that request['included'] has a list with values in it because obj.save is being triggered so I assume the append method is also triggered. View 2: Setting up dictionary key values in context varaible with requests session data def confirm_apply(request): context = { 'included': … -
How do I use static files in a Django model's TextField?
I need to display static content inside of a model's TextField. I have tried marking the TextField as safe in the template, but it doesn't seem to interpret it like the rest of the the template tags, only displaying it as raw HTML. From my template: {{ project.content|safe }} From my model: content = models.TextField() From my view: class ProjectView(generic.DetailView): model = Project context_object_name = "project" template_name = "projects/project.html" I'm expecting the content ({% static "wdv101/koala/index.html" %}) to display as a url to the static content, but instead it displays as {% static "wdv101/koala/index.html" %} -
how to use single html page to inject three different data in Django
I have a user profile model in Django models. I have a user_profile HTML template for the user profile page. On this profile page, I have three buttons to grab user info, all the posts created by the user, uploads made by the user respectively. I have created a profile-content CSS class that gives a section where above-mentioned user info will be published. But I don't know how to do that. I mean how can I load three different information that requires three different Django Views in the single HTML page. views.py class UserProfileView(DetailView): template_name = 'accounts/user_profile.html' model = models.UserProfile context_object_name = 'profile' slug_url_kwarg = 'username' slug_field = 'user__username' def get_context_data(self, **kwargs): context = super(UserProfileView, self).get_context_data(**kwargs) temp = False if models.Followers.objects.filter(user=context['profile'], follows=self.request.user.profile).exists(): temp = True context['is_follower'] = temp return context -
How to create a pymongo client in Django (using uwsgi)
I am using Django with PostgreSQL, but I have some views that are using PyMongo to get and insert data into a MongoDB database. I would like to know where should I create the PyMongo client because for now it prints UserWarning: MongoClient opened before fork. Create MongoClient only after forking. See PyMongo's documentation for details: http://api.mongodb.org/python/current/faq.html#is-pymongo-fork-safe "MongoClient opened before fork. Create MongoClient only " I am using uwsgi and it forks when gets a request. I tried to use the example from here: https://gist.github.com/josephmosby/4497f8a4f675170180ab But I have the same error. The only difference is that I am getting THE_MONGO_CLIENT directly from project/project/__init__.py when I need it, instead of having a get_mongo_db method. I also tried to put gevent.monkey.patch_all() in project/project/__init__.py, but it has the same error. -
how to configure different amazon s3 caching based on http referer
in a django project I am serving images from a amazon S3 bucket. I enabled caching by default (max-age=86400). but on a particular page I would like to disable caching (no-cache). because this content is served from amazon s3, the django decorator @never_cache has no impact on the view. is there a way to configure s3 to disable caching if the content is requested from a specific referer like example.com/no-cache-page/? note: not sure if this is possible. so far I was unable to find something explaining how to do this. -
Password authentication failed when trying to run django application on server
I have downloaded postgresql as well as django and python but when I try running the command "python manage.py runserver" it gives me an error saying "Fatal: password authentication failed for user" . I am trying to run it locally but am unable to figure out how to get past this issue. I was able to connect to the server in pgAdmin but am still getting password authentication error message -
django ecommerce: add many products at one time with form/ modelmultiplechoicefield to cart session
iam building a django ecommerce website. I can already add a product via the detail view/detail template with the add to cart button to the cart session. This works well. What iam planning and want to do: I want to have a form with “forms.ModelMultipleChoiceField and widget=forms.CheckboxSelectMultiple” in order to select/checkbox many products with quantity=1 always and add the product instances at one time to the cart session. When i go to the url the template is blank and in terminal is following: [11/Jun/2019 14:52:06] "GET / HTTP/1.1" 200 1083 Method Not Allowed (GET): /cart/add_many_products/ [11/Jun/2019 14:52:36] "GET /cart/add_many_products/ HTTP/1.1" 405 0 Its hard for me to understand how to write the view correctly for that. Iam a django beginner. I hope somebody can help me or give me a hint how I can continue. Any help/hint would be highly appreciated I was googling already a lot and couldnt find anything concrete for the combination off this form with the cart. I tried to built the form, view and template for it. . product model: from django.db import models from django.urls import reverse class Product(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) description = models.TextField(blank=True) … -
The QuerySet value for an exact lookup must be limited to one result using slicing: add data to intermediate table M2M
I'm trying to make records for my database of a web-based course planning application in an institution. My concern is that of not being able to make recordings in the intermediary table resulting from the relation M2M in views.py but it works in shell. The traceback error is ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing. raise at line 7 of views.py models.py class Departement(models.Model): code_departement=models.CharField("code du département", max_length=100, unique=True) libelle_departement=models.CharField("Libellé du département", max_length=100) faculte=models.ForeignKey("Faculte", on_delete=models.CASCADE) cursus=models.ManyToManyField("Cursus", through="AvoirCursus") class Cursus(models.Model): code_cursus=models.CharField("Code du cursus", max_length=10, unique=True) libelle_cursus=models.CharField("Libellé du cursus", max_length=100) def __str__(self): return self.libelle_cursus class AvoirCursus(models.Model): cursus=models.ForeignKey("Cursus", on_delete=models.CASCADE) departement=models.ForeignKey("Departement", on_delete=models.CASCADE) views.py if request.method == 'POST': f = forms.Departement_Form(request.POST) if f.is_valid(): dept = f.save(commit=False) code_departement = f.cleaned_data['code_departement'].upper() dept.code_departement = code_departement cursus = f.cleaned_data['cursus'] dept.save() cursus = get_object_or_404(Cursus, libelle_cursus=cursus ) AvoirCursus.objects.create( cursus=cursus, departement=dept) -
Django - Foreingkey relationship requires field
I have the following Foreignkey relationship between two models: class Text(models.Model): textcontent = models.CharField(max_length=100) class Comment(models.Model): text = models.ForeignKey(ModelA, on_delete=models.CASCADE, null=True, blank=True) commentContent = models.CharField(max_length=100) So, a text can have multiple comments, but a comment is assigned to only one text. In serializers.py I have the following: class TextSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Text fields = ('url', 'id', 'comment_set' ) As you see, I want to show also the set of comments belonging to one text via 'comment_set'. But when I create a text instance (without providing comments) I get the following on the commandline : "comment_set": [ "This field is required." ], Why is it required ? I have set the blank & null arguments to True. How I can solve this? -
"File to import not found or unreadable: ~bootstrap/scss/functions.", "formatted": "Error: File to import not found or unreadable: ~
I am trying to run a project , I am unable to get css files loaded to the login webpage.I found this error in the npm build ,At the same time I find this issues unable to lad the images though they are present in my folders. I am pretty new to the frontend let me know if I need to provide any other file configurations "file": "/Users/mthippareddygari/Documents/GitHub/workflow/node_modules/bootstrap-material-design/scss/_variables.scss", "line": 56, "column": 1, "message": "File to import not found or unreadable: ~bootstrap/scss/functions.", "formatted": "Error: File to import not found or unreadable: ~bootstrap/scss/functions.\n Web.config module : { rules : [ { test: /\.jsx/, include: APP_DIR, loader: 'babel-loader', //Just in case exclude: /node_modules/ }, //{include: /\.json$/, loaders: ["json-loader"]} ] }, -
Are SagePay merchantSessionKeys and cardIdentifiers OK to expose to end users?
I'm currently working on a REST based SagePay Integration using a combination of Django on the backend and Vue / Nuxt on the front. The current process is as follows: Client makes a request to my backend server for a merchantSessionKey via a GraphQL resolver. The backend graphene resolver uses the secret merchant integration key and password (stored in environment variables) to make a post request for the merchantSessionKey and returns it to the Vue frontend. A user fills in the credit card form (using SagePay's Own Form integration) I use the card data to generate a cardIdentifier that I will store in my vuex state and will use later to further the rest of the transaction. Is this all safe to do? Obviously it will be secured via https and I will setup CORS properly when everything goes into production, but I am technically storing the merchantSessionKey and cardIdentifier on the end users machine. -
sending data from one form to another via POST
I want to make Save contact button on my Call form. If user fill the phone no and clicks on save button.He should redirect to create contact form with phone field already filled. After filling other details contact should be saved. I have tried this in my views: This part is from Call form. if request.POST.get('contact_save') == 'done': phone = form.cleaned_data['call_to'] try: contact = Contact.objects.filter(person_who_saved=request.user).get(phone=phone) print("already saved") return redirect('make_call') except: phone = phone return create_contact(request, phone) def create_contact(request, *phone): if request.POST.get('save') == 'done': form = ContactForm(request.POST) print("valid") if form.is_valid(): contact = form.save(commit=False) contact.person_who_saved = request.user contact.save() return redirect('contacts_list') else: form = ContactForm() try: form.phone = phone except: form.phone = None return render(request, 'log/contact_form.html', {'form': form}) It is rendering the contact form with desired fields but extra fields are not saving. -
1071, 'Specified key was too long; max key length is 767 bytes' WHEN MIGRATE
I get this error when I try to migrate my django models to my new mySQL database, using python anywhere host. Here my models: class Listaprecios(models.Model): id = models.SlugField(primary_key = True, max_length =20) nombre_producto = models.CharField(max_length=30,unique=False) precio_producto = models.IntegerField() categoria_producto = models.CharField(max_length=20,unique=False) cantidad_producto = models.IntegerField() class Pedidos(models.Model): fecha = models.DateField(default=date.today) nombre_cliente = models.CharField(max_length=25) comentario = models.CharField(max_length=40) class Productosordenados(models.Model): item = models.ForeignKey(Listaprecios, on_delete=models.CASCADE) pedido = models.ForeignKey(Pedidos, on_delete=models.CASCADE) cantidad = models.IntegerField(default=1) I'm using Ver 14.14 Distrib 5.7.23. Even I changed DATABASE configuration in settings as all recommend: 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES',default_storage_engine=INNODB" -
No operator matches the given name and argument types. - Django F() expression
I'm trying to add UTM paramaters to every single link rows in my Postgresql database using Django's F() expression but I keep getting an operator does not exist: character varying + unknown. error. Here's the function I'm trying to apply from my views.py: def utm_param(request): if request.GET.get('mybtn'): # to improve, == 'something': Product.objects.all().update(link=F('link') + '?utm_source=uvergo&utm_medium=ref') return render(request, "form.html") And this is the error I'm getting: return self.cursor.execute(sql, params) psycopg2.errors.UndefinedFunction: operator does not exist: character varying + unknown LINE 1: ...link" = ("search_product"."link" + '?utm_so... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. And the arrow from the traceback is pointing towards the +. How can this be fixed? Please help. -
String to Datefield conversion
Bear with me because similar questions have been asked before. I'm just don't know how to apply it correctly. I have a field in Charfield(aka string) form called debut that represents dates in the form of 2019-06-19. I would like to it to be in this format instead 06/19/2019 or 6/19/2019. Could someone please help me with this so that I can call it in my template in that format. #MODELS class PlayerLkup(models.Model): playerid = models.CharField(db_column='playerID', primary_key=True, max_length=255) birthmonth = models.IntegerField(db_column='birthMonth', blank=True, null=True) birthday = models.IntegerField(db_column='birthDay', blank=True, null=True) weight = models.IntegerField(blank=True, null=True) debut = models.CharField(max_length=255, blank=True, null=True) # this is the field I'm working with #VIEWS from django.shortcuts import render from .models import PlayerLkup def player_info(request, playerid): playerdata = PlayerLkup.objects.get(playerid=playerid) battingstats = playerdata.hittingstats_set.all() #Hittingstats table has a foreign key that references PlayerLkup table return render(request, 'careerstats/playerpage.html', {'playerdata': playerdata, 'battingstats': battingstats}) #TEMPLATE {{ playerdata.debut }} # Unformatted call of debut -
django send_mail() ,client got all messages in only one gmail inbox
i need to send multiply mails to one client,im do it using the django send_mail() function and its work but the the problem is: the client get all the messages in one big gmail inbox with sub messages. how can i make the client to recieve each mail in seperate gmail inbox?? send_mail(subject,body,senderMail,ClientMail,fail_silently=True) -
How would I be able to show my model field to my templates?
I'm quite new to Django. Today, I decided not to follow any tutorials and whatnot to do my own site. I have my models.py here which is class Portfolio(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=1000) technology = models.CharField(max_length=100) img = models.ImageField(upload_to='media/') site = models.URLField(max_length=200) def __str__(self): return self.title class Meta: verbose_name = "project" verbose_name_plural = "projects" My views.pyis def works(request): work = Post.objects.all().order_by() context = {'work': work} return render(request, 'portfolio.html', context) And the template is <h3 class="text-center card-title title font-weight-bolder">{{how.do.i.put.it}}</h3> Where do I get the words inside {{here}}? I hope I explained it well. -
Django debug toolbar showing on bottom of page
I'm trying to add Django-debug-toolbar to my website to troubleshoot some problems. I followed the installation process and have some results, but not what I expected. There is some information showing on the bottom of the page, but there is no toolbar on the right. This half result shows on every page at the very bottom. I followed the instruction page from the autors, as well as several youtube guides. I googled this problem but didn't see anyone with the same issue. What I did: Installed django-debug-toolbar using pip - Added debug_toolbar to INSTALLED_APPS - added 'debug_toolbar.middleware.DebugToolbarMiddleware' to the end of the middleware list - Added INTERNAL_IPS = ('127.0.0.1) - Added the DEBUG_TOOLBAR_PANELS list - Added the optional 'show_toolbar' variable, just to be sure - Checked the tags - Added the 'if settings.debug' statement in the urls.py Here is a picture of the result. https://imgur.com/h7uY6wx The debugger seems to work, it's just the formatting which does not seem to function. Does anyone know where the problem might be? -
Django fixtures and auto_now_add date time field
Trying to create a fixture for a model with an auto_now_add date time field created_at = models.DateTimeField(auto_now_add=True) When the fixtures is loaded there is an error thrown IntegrityError: Problem installing fixture, null value in column "created_at" violates not-null constraint Is there a way to have Django determine the date rather than manually entering a date? [ { "model": "customer.type", "pk": 1, "fields": { "name": "type", "created_by": 1 } } ] -
Django call_command() with filename wildcard
How can you use filename wildcards in call_command()? I'm trying to create a management command that does the same as python manage.py loaddata */fixtures/*.json Below code throws CommandError: No fixture named '*' found. from django.core.management import call_command from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Load all fixtures in app directories' def handle(self, *args, **kwargs): call_command('loaddata', '*/fixtures/*.json') self.stdout.write('Fixtures loaded\n') -
null_view() got an unexpected keyword argument 'uidb64'
I am trying to activate the password reset, this error marks me: TypeError at /password-reset/confirm/MjU/573-56138431a7e751d69d53/ null_view() got an unexpected keyword argument 'uidb64'