Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django migrating from SQLITE to PGSSQL
I am looking to migrate my Django application from Sqlite to Postgres. I used the following code for the first step : P:\webapp>python manage.py dumpdata > datadump.json Which returned the following error: System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'admin' isn't unique. You may not be able to reverse all URLs in this namespace CommandError: Unable to serialize database: 'cp950' codec can't encode character '\ufffd' in position 310: illegal multibyte sequence Exception ignored in: <generator object cursor_iter at 0x00000000171CC1C8> Traceback (most recent call last): File "C:\Users\franky.doul\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1609, in cursor_iter cursor.close() sqlite3.ProgrammingError: Cannot operate on a closed database. I am still fairly new to Django, could someone help me understand the above error message please ? -
Change serializer class for single method in Django Rest Framework
If I want to override a method in my viewset to change the serializer_class for only a single method, how can I do that. I tried passing serializer_class=CustomSerializer but it doesn't have any effect. class VoteViewset(viewsets.ModelViewSet): queryset = Vote.objects.all() # Use normal serializer for other methods serializer_class = VoteSerializer def list(self, request, *args, **kwargs): # Use custom serializer for list method return viewsets.ModelViewSet.list(self, request, serializer_class=VoteWebSerializer, *args, **kwargs) Basically do the same list method as the inherited viewset, but use a different serializer to parse the data. The main reason for this is because javascript does not handle 64 bit integers, so I need to return the BigInteger fields as a string instead of integer. -
django: queryset doesnt show the right result
I'm not sure how to write the queryset since I have a list of categories, my try is below, however, I'm not getting the wanted result. Any help is appreciated! model: category= (('sell', 'sell'),('rent','rent')) categories= models.CharField(max_length = 10, choices= category, null = True) html: <select name="type" class="form-control " style = "width:250px;"> <option selected="true" disabled="disabled" selected>Type</option> <option value="sell" class = 'numbers'>sell</option> <option value="rent" class = 'numbers'>rent</option> </select> views>query> # type if 'types' in request.GET: types= request.GET['types'] if types: queryset_list = queryset_list.filter(category__in = ['sell','rent']) -
DataBase Error when saving a list of strings in django with MongoDB on the server side
I am trying to add a list of strings to DB, so i made a for loop to iterate over the list to save each string to the deadline_date field inside the BsfEvents class in models.py. Only the first item was saved, and after that all i am getting is DatabaseError() for unknown reasons. I tried to use try and except to catch the error as e, when i am trying to print it, it print empty line, so i used repr to print the Traceback, but i did not understand where is the problem. This is a side project, and i should note that i am not experienced so much in django with mongoDB. Here is my code inside the views.py: class BsfEventsViewSet(viewsets.ModelViewSet): queryset = BsfEvents.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = BsfEventsSerializer @action(detail=False, methods=['POST']) def add_bsfevent_to_db(self, request): BsfEvents.objects.all().delete() deadline = get_events_deadline() # deadline is a list of strings event_details = get_events_details() # event_details is a list of strings try: for item in deadline: date = BsfEvents(deadline_date=item) date.save() for item in event_details: detail = BsfEvents(description=item) detail.save() response = {'success': 'Events added successfully.'} except Exception as e: print(repr(e)) traceback.print_exc() response = {'error': 'Error while adding events to DB'} return … -
How can I change the default select options?
I set a selection model form at models.py and form.py. But I want the default options to change dynamically. For example, if it has a data [user:test, status:wishlist, gameSlug:test-1] found in the database. I hope when I using this "test" account open "test-1" page, the selection will show "wishlist" as default. here is my code: models.py: class UsersMarksTags(models.Model): STATUS = [ ('booked', 'Booked'), ('wishlist', 'Add to Wishlist'), ('Not interested', 'Not intersted'), ] user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE); status = models.CharField(max_length = 200, null = False, choices = STATUS, default = 'booked'); gameSlug = models.CharField(max_length = 200, null = False); form.py: class statusForm(forms.ModelForm): class Meta: model = UsersMarksTags; fields = ['status']; views.py: class showGameInformation(FormView): template_name = "showList/gameDetail.html"; form_class = statusForm; def form_valid(self, form): ....... test.html: <form method = 'POST'> {% csrf_token %} {{ form.as_p }} <input type='submit' value='Submit' /> </form> -
Postgres paste table to Local not working
I'm new in Postgres and currently having a trouble on how can I copy past the table through creating new connection in Navicat from a friend. So I just want to paste those table into my local but the problem is I have been encountered this error. I'm been using navicat version 15 and postgres version 11. It is possible that the problem is comes from the table restricted from my friend? Thanks in advance Image 1 Image 2 auth_group_id_seq does not exist -
Django giving error when null and blank both True
I have a field in my model: message = models.BigIntegerField('Vote Message', null=True, blank=True) Yet when I try to POST to this view (rendered from a rest_framework.viewsets.ModelViewSet), I get an error message: "This field may not be null." Why is it giving me that if I have it specifically to allow a null value? -
Django: Using a For Loop in a DetailView class page
Using Django, is it possible to have a For Loop in a page from a DetailView Class page? I have detail pages of things pulled from my database, but I was hoping I could have a For Loop inside that page that runs through a list of names in that table to link to each other (if that makes sense). urls.py: from django.urls import path, include from .views import payplan_emails_view urlpatterns = [ path('normal-payplan-emails/<int:pk>', payplan_emails_view.as_view(), name="normal-payplan-emails"), ] views.py: from django.shortcuts import render, redirect from .models import knowledgebase_instruction from django.views.generic import DetailView class payplan_emails_view(DetailView): model = knowledgebase_instruction template_name = "instructions/payplans_base.html" payplans_base.html: {% block content %} <h4>{{knowledgebase_instruction.name}}</h4> <p>{{knowledgebase_instruction.instructions|safe}}</p> <ul> <!-- I would love to loop through items in the table here --> <li><a href="#">List Item 1</a></li> </ul> {% endblock%} -
Django models: Choose a FK from two options (Just one)
This is the models.py from a Subscription app. Some fields have been omitted, to simplify the code. # PLAN class Plan(BaseVersionPlusModel): code = models.CharField(max_length=17, primary_key=True) description = models.CharField(max_length=255) price = models.FloatField() services = models.ManyToManyField(Service, through='subscriptions.PlanService', blank=True) products = models.ManyToManyField(Product, through='subscriptions.PlanProduct', blank=True) class PlanService(BaseVersionPlusModel): service = models.ForeignKey(Service, on_delete=models.CASCADE) plan = models.ForeignKey(Plan, related_name='plan_services', on_delete=models.CASCADE) limit = models.FloatField(default=9999) class PlanProduct(BaseVersionPlusModel): product = models.ForeignKey(Product, on_delete=models.CASCADE) plan = models.ForeignKey(Plan, related_name='plan_products', on_delete=models.CASCADE) limit = models.FloatField(default=9999) # SUBSCRIPTION class Subscription(BaseVersionPlusModel): client = models.ForeignKey(Client, on_delete=models.PROTECT, blank=True) plan = models.ForeignKey(Plan, on_delete=models.PROTECT, blank=True, null=True) # CONSUME class ServiceConsume(BaseVersionPlusModel): subscription = models.ForeignKey(Subscription, on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) class ProductConsume(BaseVersionPlusModel): subscription = models.ForeignKey(Subscription, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) I would like to get the Consume model in just one table instead of ServiceConsume and ProductConsume. Someting like this: Class Consume(BaseVersionPlusModel): subscription = models.ForeignKey(Subscription, on_delete=models.CASCADE) **service/product = FK(Service/Product) #But choosing only one** Is this possible in Django? -
Django Parsing Mailchimp webhooks
I'm writing a webhook handler to receive data from Mailchimp in a Django application. The Mailchimp documentation lists the code for Flask: @app.route('/', methods=['POST']) def index(): reqType= itemgetter('type')(request.get_json()) reqData= itemgetter('data')(request.get_json()) I tried the following in Django, however I received an error that 'byte indices must be integers or slices, not str': @csrf_exempt def mailchimp_handler(request): reqtype = request.body["type"] reqdata = request.body["data"] Setting the following didn't work: reqtype = request.body[0] and reqdata = request.body[1] I also tried the following, without success: def mailchimp_handler(request): data = json.loads(request.body) reqtype= data["type"] reqdata= data["data"] -
Django REST Knox Authentication Issues
I've completed the development work on a Django REST API using Knox-Rest. It works great in my development environment but after moving it to the Prod environment, it authenticates and I receive my token back. Then using Postman, to test my API, I do a get using that token to validate the user and I get a 401 error, Credentials Not Provided. Looking at the in the "knox_authtoken" table I see separate rows for each login I tried. On the same table in development, I just see one row per user. I think the answer to why it's not working is related to what I'm seeing on the table but I'm not sure what it's telling me. All of the code is identical so it's likely in the setup but I can't seem to track it down. So anyone with some experience with the Django Knox-REST API that might have some ideas, I'd really appreciate it. -
How to include python django's starting message in logging
In test, I found out that Python Django application's staring message may contain important warnings, etc, and see the screenshot below for an example. However, the log file didn't include these message. I'm wondering if there's any setting to include it in logging? Any hints will be highly appreciated. Example screen output: (venv3.7) [user@vnl1916 APPLICATION]$ python manage.py runserver 0.0.0.0:8000 Performing system checks... System check identified some issues: WARNINGS: eav.Value.value_bool: (fields.W903) NullBooleanField is deprecated. Support for it (except in historical migrations) will be removed in Django 4.0. HINT: Use BooleanField(null=True) instead. System check identified 1 issue (0 silenced). You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, authtoken, ebackendapp, sites. Run 'python manage.py migrate' to apply them. February 08, 2021 - 12:31:55 Django version 3.1.4, using settings 'ebackendproject.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. ^C(venv3.7) [user@vnl1916 APPLICATION]$ -
Why is this not in the Dockerfile?
I've been messing with Docker and Django lately and rather than clutter up my system, I decided to make a dev container for Django. I've got it working but I want to know the "why" of this situation. I followed this tutorial on the Docker website and finally got everything working. I don't get why we do docker-compose run web django-admin startproject composeexample and not put the django-admin startproject composeexample inside the Dockerfile or the compose file? I've tried to do both but it wont work, it builds the image but without a django project being created. I get a manage.py not found error. I feel like the project should be inside the image and not have to be run at the end of the docker-compose run command. So why do we do this and why doesn't putting it inside the Dockerfile work? -
How to skip any strings values from an excel column Pandas
I have a pandas dataframe in which a column must accept only decimal fields, what can I do to skip or delete all of the rows that values in this columns are strings? -
Django FileField 'SyntaxError: positional argument follows keyword argument'
I am trying to remove a discontinued package from a django project which is requiring me to replace a field that was in the package from many migration files. I switched to models.FileField however I'm getting errors that suggest issues with the order of my parameters. I tried switching around the parameters but I couldn't seem to get the error to resolve. Here's the error: models.FileField(upload_to='producer/closing/', blank=True, verbose_name='File'), ^ SyntaxError: positional argument follows keyword argument Any suggestions as to what is happening? -
I have a ValueError at /accounts/register/ in registration form
class UserFormView(View): form_class = UserForm template_name = 'registration/register.html' # display blank form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) # process form data def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=True) # cleaned (normalized) data email = form.cleaned_data['email'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] date_of_birth = form.cleaned_data['date_of_birth'] phone_number = form.cleaned_data['phone_number'] address = form.cleaned_data['address'] password = form.cleaned_data['password'] user.set_password(password) user.save() # returns user objects if credentials are correct user = authenticate(email=email, password=password) if user is not None: if user.is_active: login(request, user) return redirect('accounts:home') return render(request, self.template_name, {'form': form.as_p}) this is a views.py which check a validation of registration form, but when I register a form in a server I find a ValueError at /accounts/register/ -
Django url routing 404
I am a beginner in Full stack Machine Learning and I have decided to use Django to develop myself further. I created a simple ML - prediction and deployed it in the server of my company. By default, the server always gives the project name as the prefix. example: https://companyserver.net/projectname/. in my local system the code is working well, however if i deploy it to the company server, when i try to open another page from 'home' page, Django throws a 404 error. the URL pattern (should) looks like following: https://companyserver.net/predict/? but that is wrong, as it should contain the projectname after the .net, so it should be like this: https://companyserver.net/projectname/predict/? If I add the project in the middle of the URL just like above, the page opens correctly. What is the best practice to solve this problem? I searched somewhere online that I can use constant FORCE_SCRIPT_NAME under settings.py. Trying this, but it makes even more trouble in my local system. Appreciate your help very much. -
How can I make a line disabled (readonly) in Django?
For example, I have a table (List View) of events that will happen over a period of time. When any event is over I would like to click on a "Cancel" button that does not delete the event from the database and that keeps it appearing in the table but in a way that I cannot edit or undo the cancellation. How can I do that? The examples I saw here did not help me because none of them had any button that could disable stuff. -
django Unable to access SSL cert
For various reasons, I am using pyodbc to connect to a postgres database which has SSL verification in my Django project views.py file. I can successfully connect by referencing the files in a local drive, however I am trying to get them to become part of the static files. Here is the relevant structure of the project: my_project -mysite -views -views.py -static -ssl -postgres -root.crt I have tried this in my views.py: from django.contrib.staticfiles.storage import staticfiles_storage rootcert = staticfiles_storage.url('ssl/postgres/root.crt') link = r"Driver={PostgreSQL UNICODE};Server=my_server;Port=my_port;Database" \ r"=my_db;Uid=my_uid;Pwd=my_pwd;sslmode=verify-ca;pqopt={" \ r"sslrootcert='" + rootcert + "' " \ r"sslcert='" + sslcert + "' " \ r"sslkey='" + sslkey + "'} " However, I get an error that says that the root cert does not exist. If I access this directly with the local server running (http://localhost_ip:port/static/postgres/root.crt), then it successfully downloads the file and in the logger I get a 200 message. On the Django error report, it says the rootcert variable is: '/static/ssl/postgres/root.crt' I have tried doing py manage.py collectstatic and py manage.py runserver --insecure but I still get the same error. In my settings.py file, here is how I have the static files set: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Why is django … -
Running django-q using elastic beanstalk on aws linux 2 instances
I use Elastic Beanstalk on aws to host my webapp which needs a task runner like django q. I need to run it on my instance and am facing difficulty doing that. I found this script https://gist.github.com/codeSamuraii/0e11ce6d585b3290b15a9ad163b9aa06 which does what I need but its for the older version of ec2 instance. So far I know I must run django q post deployment, but is it possible to add the process to the procfile along with starting the wsgi server. Any help that could point me in the right direction will be greatly appreciated. -
can not save pages any more in wagtail
when clicking publish or save draft I got this error wagtail.core.models.Page.DoesNotExist: Page matching query does not exist. this happens only with old pages, the newly created pages are being able to be created and saved without any errors NB: the new pages do not have children pages yet trying to find out what is causing this error despite I did not override the save method any suggestion or hint will be very helpful thank you -
django: pass an element to my template through context dictionary
in this view ... def home(request): context = {'page_title':'Volunteers', 'action':'<button class="btn btn-primary btn-small">Leave</button>'} return render(request, 'app/home.html', context) I try to send a button element (or some other HTML) through the context dictionary. I add it to the template like this <div class="row"> <div class="col-md-6"><h4>{{page_title}}</h4></div> <div class="col-md-6 text-md-right mt-1">{{action}}</div> </div> When the page renders, it just shows the text and does not allow it to be HTML. Any idea how I can get this to treat it as HTML? Thanks, Django beginner here finally coming from the dark side (PHP) =) -
How to load my javascript and css library using django webpack loader
I started using Django with Vuejs and Webpack, and I would like to load my dashboard CSS and Javascript files. I don't know how can I do that. this my vue.config.js const BundleTracker = require("webpack-bundle-tracker"); module.exports = { // on Windows you might want to set publicPath: "http://127.0.0.1:8080/" publicPath: "http://127.0.0.1:8080/", outputDir: "./dist/", chainWebpack: (config) => { config .plugin("BundleTracker") .use(BundleTracker, [{ filename: "./webpack-stats.json" }]); config.output.filename("bundle.js"); config.optimization.splitChunks(false); config.resolve.alias.set("__STATIC__", "static"); config.devServer // the first 3 lines of the following code have been added to the configuration .public("http://127.0.0.1:8080") .host("127.0.0.1") .port(8080) .hotOnly(true) .watchOptions({ poll: 1000 }) .https(false) .disableHostCheck(true) .headers({ "Access-Control-Allow-Origin": ["*"] }); } // uncomment before executing 'npm run build' // css: { // extract: { // filename: 'bundle.css', // chunkFilename: 'bundle.css', // }, // } }; how can I load my CSS styles and javascript ? -
how can I fix this error: Field 'id' expected a number but got ['Air Condition', 'Pool']?
I created a checkbox list by ManyToMany relationship as you can see here: class Store(models.Model): amenities = models.ManyToManyField(myChoices, blank=True) this model holds the following data: class myChoices(models.Model): choice = models.CharField(max_length=154, choices=AMENITIES) which get their choices from the following data options: AMENITIES = [ ("Electricity", "Electricity"), ("Water", "Water"), ("Gas", "Gas"), ("Elevator", "Elevator"), ("Maids Room", "Maids Room"), ("Garden", "Garden"), ("Air Condition", "Air Condition"), ("Pool", "Pool"), ] now as you can see the input will be multiple selections and the output will be the list of string but I got this error: Field 'id' expected a number but got ['Air Condition', 'Pool']. I don't know why the process ask me to write the id of data instead of the string object itself? also, How can I save the multiple objects in the database? -
Extract fields from a json in pyhon(Django)
Hello I am new to the python world, and I am learning, I am currently developing a WebApp in Django and I am using ajax for sending requests, what happens is that in the view.py I get a json, from which I have not been able to extract the attributes individually to send to a SQL query, I have tried every possible way, I appreciate any help in advance. def profesionales(request): body_unicode = request.body.decode('utf-8') received_json = json.loads(body_unicode) data = JsonResponse(received_json, safe=False) return data //**Data returns the following to me** {opcion: 2, fecha_ini: "2021-02-01", fecha_fin: "2021-02-08", profesional: "168", sede: "Modulo 7", grafico: "2"} // **This is the answer I get and I need to extract each of the values of each key into a variable**