Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2.0 Access Models (CREATE/REMOVE/FILTER) Standalone [without manage.py shell]
I have a Django project and I wanted to generate some objects (from the models) after importing the model with from apps.base.models import MyModel and setting up the configuration as the previous StackOverflow Questions suggested I was not able to run the script. import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myProject.settings") import django django.setup() from apps.base.models import MyModel Please note that this is on Django version 2.0.6 [Django 2.0+]. Correct settings have been used, (i.e. myProject.settings) After properly configuring everything else I get the following error: RuntimeError: Model class apps.base.models.MyModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. -
'str' object has no attribute '_meta' error when setting up django-comments-xtd per documentation
My site is actually a wagtail site, although I'm not sure if that makes a difference. It's a simple blog application with a blog page to view posts and a page to show each post. I was following the instructions here to setup django-comments-xtd The documentation says to implement the following code to get a comment count displayed on each post page. {% get_comment_count for object as comment_count %} <div class="text-center" style="padding-top:20px"> <a href="{% url 'blog:post-list' %}">Back to the post list</a> &nbsp;&sdot;&nbsp; {{ comment_count }} comments have been posted. </div> I changed the actual link to be the following, as that is what it was in my site (built from another tutorial) <p><a href="{{ page.get_parent.url }}">Return to blog</a></p> I don't think changing the url like that would cause the problem, from what I can tell. I have made sure to load comments at the start of the file also. The actual error is: Error during template rendering In template /home/jake/blog/blog/post_page.html, error at line 8 'str' object has no attribute '_meta' Line 8 refers to this line: {% get_comment_count for object as comment_count %} How can I troubleshoot this? -
Python / Django, Generate pdf after generating html
My web app is written by python 2.7 & Django 1.11. When a customer pays to subscribe, it will immediately generate an invoice pdf and send to customer via email. But the code is not working when I cut time.sleep. i guess there is a racing condition. The pdf file is generated with wkhtmltopdf (0.9.9) and pdfkit. What is the time required for sleep? or is it a suitable way? I am going to send it to customer after pdf is generated. It needs to sleep again to wait for pdf generation? output_html = current_month_folder + invoice_name + '.html' output_filename = current_month_folder + invoice_name + '.pdf' email_filename = invoice_name + '.pdf' html_content = render_to_string(input_filename, context) with open(output_html, 'w') as f: f.write(html_content) f.flush() time.sleep(5) pdfkit.from_file(output_html, output_filename) -
Django throws error on model field for wrong database
I have two databases set up for my Django project, a MySQL and a Postgres. I have a database router in place and everything has been working fine, until I changed a CharField with max_length of 300 in a Postgres model to unique. That model is in Postgres, but now Django throws this error about MySQL: [postgres_app.TestModel.slug]: (mysql.E001) MySQL does not allow unique CharFields to have a max_length > 255. I double checked my database router and everything looked fine. I also have to mention again the router was doing its job correctly before and picked the correct database for read, write, and migration. Here is my router: POSTGRES_APPS = ['postgres_app'] class PostgresRouter(object): """ Controls which apps can have access to the postgres instance. """ def db_for_read(self, model, **hints): """ Called on every read action on a model. """ if model._meta.app_label in POSTGRES_APPS: return 'postgres' return None def db_for_write(self, model, **hints): """ Called on every write action on a model. """ if model._meta.app_label in POSTGRES_APPS: return 'postgres' return None def allow_relation(self, obj1, obj2, **hints): """ Called only on migrations. Only allow relations if both models are in POSTGRES_APPS. """ return {obj1._meta.app_label, obj2._meta.app_label}.issubset(set(POSTGRES_APPS)) or None def allow_migrate(self, db, app_label, model_name=None, **hints): … -
Django-select2: ModelSelect2MultipleWidget doesn't show any options
I'm trying to use ModelSelect2MultipleWidget on User model. class NFForm(Form): user = forms.ModelMultipleChoiceField(queryset=User.objects.all(),widget=ModelSelect2MultipleWidget(model=User)) The problem is that the select says: No results found On the other hand, if I use Select2MultipleWidget, it works correctly and it shows all users as options. The problem is that I want to customize options so I need to use ModelSelect2MultipleWidget and override it's label_from_instance method. Do you know where is the problem? -
All static assets coming back as "404 (Not found)" in Django/React app
My application sits at the server path /home/myapp/. The static assets sit at /home/myapp/src/static/ when a python manage.py collectstatic is performed. It copies assets from /home/myapp/src/assets/. I have tried with DEBUG both True and False. When I navigate to the web application at https://test.example.com, it tells me that all of the assets that reside at /home/mpapp/src/assets/ are 404 (Not Found) despite the files being there. Also, my web server setup is Apache with a reverse proxy to Gunicorn. I'm serving the application with gunicorn wsgi which serves the application at 127.0.0.1:8000, which is where Apache is ProxyPass to. I've tested against a brand new Django application and this setup serves it properly, so it shouldn't be how Apache and Gunicorn are configured. What I have been doing is: 1) npm start to compile the React front-end assets 2) python manage.py collectstatic to move the assets to /static/ 3) Run gunicorn wsgi where the manage.py and wsgi.py reside Some code would be helpful. Here is my settings.py: import os import sys import json import datetime from unipath import Path from django.core.exceptions import ImproperlyConfigured # Import JSON file print(Path(__file__)) with open('./config/config.json') as f: s = json.loads(f.read()) def get_settings(settings, s=s): try: return s[settings] … -
Populating table in django using jquery ajax
My problem - I am trying to make a table which will take the data from my django code through the database. i have managed to get the data from my database to the ajax call in the form of a queryset. i need to now get the data into the table. Below is my code - this is my jquery ajax code. $(document).ready(function(){ $('#ReusableId').on('change',function(){ var catid; catid = $(this).find(':selected').attr("data-catid"); alert(catid); $.ajax({ type: 'GET', url: "InputColumns", data:{catid:catid}, success: function (data) { alert (data); $('#inputc').append("<td> he" + data['id'] + "</td>"); $('#outputc').append("<td> he" + data['id'] + "</td>") ;}, }); }) }); this is my views.py code - def get_columns(request): if request.method == 'GET': cat_id= request.GET['catid'] inputc=Input.objects.filter(iref_id=catid) inputl=list(inputc) return HttpResponse({inputc:inputc}) This is my html code - <html> <body> <table id="table" class="table"> <thead> <th>Input Name</th> <th>Is Req</th> </thead> <tbody> <td name = "#inputc" id = "#inputc"> {%for input in inputc%} {{inputc}} {%endfor%} </td> <td name = "#inputc" id = "#inputc"> {%for input in inputc%} {{inputc}} {%endfor%} </td> </tbody> </table> </body> </html> My data which is being inputed is like this - <QuerySet [<Input: Input object (1)>, <Input: Input object (2)>, <Input: Input object (3)>]> Im unable to display this. -
Can't save instance with CreateAPIView
Have a view: class BrandAddAPIView(generics.CreateAPIView): serializer_class = BrandAddSerializer permission_classes = [permissions.IsAuthenticated] and have a serializer: class BrandAddSerializer(serializers.ModelSerializer): editor = serializers.SerializerMethodField('create_editor') class Meta: model = Brand fields = ('editor', 'name', 'image', 'description') def create_editor(self, obj): # return editor When I call my URL - everithing is ok, all fields are correct, but model instance is not saved to DB. What am I doing wrong? Thanks! -
How do I save the course (FK) into the database table for course_period considering that there is no input field for course(Django)?
this is my first Stack post. I am a beginner in Django as well as Python (I am using Django 2.0.6, Pycharm Professional 2018.1 for IDE, app is called: architect) and am unable to find the solution (or a hint) on how to do a particular task. I hope I can express my problem as best as I can. Let's start: Before I go into the code section I'll first be talking about the user flow: User Flow /architect/courses This is a screen that lists down the courses a school has, represented in a table format. As can be seen each row is a course. There are 3 buttons for each course and we'll be focusing on the button 'Assign a Period'. When the user clicks on the 'Assign a Period' button, he/she will be redirected to this screen: /architect/courses/create-course-period/ In this screen, a dropdown is available for user to choose a particular Academic Year and Semester that the course will run for. Once done choosing, user clicks on the Submit button and it will be saved into the database table arc_course_periods. Now we move on to the coding side: The Codes Note that UserForeignKey is just a package I … -
How to correctly configure apache for reverse proxy serve django app
Hi I've been trying to correctly configure apache as reverse proxy for my django application. When served from port :4300 it goes all fine, but when I tried to use reverse-proxy all goes wrong. When I try to acces when logged in 192.168.100.201/fact I get the expected functionality, but when I press anything to admin app of django i get 192.168.100.201/admin when I should get 192.168.100.201/fact/admin Even if I write it in the browser I'm still redirected to 192.168.100.201/admin I kwon that maybe is a dub question but it is something that I couldnt realize. settings.py """ Django settings for SEMFAC project. Generated by 'django-admin startproject' using Django 1.11.13. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os from django.utils.translation import ugettext_lazy as _ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 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 = 'wkf8aie3kc6@xb0-_y%rwmp*tq)hqv7t+d0l6a9wop0l$1m336' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['192.168.100.205','192.168.100.203','192.168.100.201'] # Application definition INSTALLED_APPS = [ 'fact.apps.FactConfig', 'django.contrib.admin', … -
I am starting to learn Django and when I wan't to install MySql using pip i get this error message in CMD
So I found this tutorial online : https://www.youtube.com/watch?v=D6esTdOLXh4&t=1795s&ab_channel=TraversyMedia And I want to learn Django framework for backend development. When the tutorial comes to the 23:25 the guy installs mysql using pip. Now when I want to the same thing I get this error message : error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.14.26428\bin\HostX86\x86\cl.exe' failed with exit status 2 ---------------------------------------- Command "c:\python\python.exe -u -c "import setuptools, tokenize;file='C:\Users\Zlatko\AppData\Local\Temp\pip-install-l7758l00\mysqlclient\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users\Zlatko\AppData\Local\Temp\pip-record-sgqpi0_l\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\Zlatko\AppData\Local\Temp\pip-install-l7758l00\mysqlclient\ -
How to set up a periodical update for database in Django
I would like to make a system to update my database based on API that I use every month. This updating system takes place every. If I choose specific date and time, it automatically updates my database at the time and on the date. I'm not sure where I should start to do this in Django. Can anyone give me a brief direction for the way so that I can research about it on my own? -
LAMP to Django; is it wise to use the admin as the website proper?
I need to port a CMS (to be sold and needing a certain look and feel) originally written in PHP and using a mysql database on Django. While researching this framework, I found that the default admin has all the base qualities I need. Now comes the difficult question; is it wise to use the default admin (styling it for the project's needs (i.e Django-jet)), or should I create all the pages needed individually (using metronics, for example) and leave the admin as is? Do you guys have any other suggestions? Thanks!! -
'pip install -r requirements.txt' produces many 'error: invalid command 'bdist_wheel'' errors
On a RHEL machine I have some old Django projects that I'm moving to a new server, these were written for Python2.6, Django1.4.3 I've installed python2.7, created the virtualenvs in my home directory, adjusted paths and references to the Python version. I created a virtualenv for Python2.7: virtualenv -p python2.7 ~/.virtualenvs/my_site/ When I activate the virtualenv and then cd into the web site directory and run pip install -r requirements.txt after successfully fetching all the libs, the following error is displayed for every line in requirements.txt: Building wheels for collected packages: MySQL-python, Pillow...etc Running setup.py bdist_wheel for MySQL-python ... error Complete output from command /home/my_user/.virtualenvs/my_site/bin/python2.7 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-96k9a4/MySQL-python/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/pip-wheel-ngSbQU --python-tag cp27: usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: -c --help [cmd1 cmd2 ...] or: -c --help-commands or: -c cmd --help error: invalid command 'bdist_wheel' I've found many other similar questions on stackexchange and other sites, and tried the fixes but no luck! enter code here I have pip 10.0.1 wheel IS installed I did see that some answers suggested to run python setup.py bdist_wheel, but there are several setup.py files on the machine, which one would I run this … -
pip install mysqlclient. Microsoft Visual C++ 14.0 is required
I'm using windows 10 and tried to install mysqlclient. Picks Prabhakar shared a link. New Member · 19 mins Hello everyone, I'm trying to install "pip install mysqlclient" but this gives me http://prntscr.com/k09339 error. I tried to open url which is given in cmd. but it also gives me this error. http://prntscr.com/k093bq And I also checked, I have this version installed. http://prntscr.com/k093fq I researched and Google says the version 14 is upgraded to 15 So i tried to install 15 but it gives me this error I tried 2015 version http://prntscr.com/k0g76q -
Saving Django Model as dict with foreignkey
I am saving a dataframe in Django model with this code, where tb1 and tb2 are tables in models.py: for record in data_in_list: r = tb1(hash=record[3]) nr = tb2(pk_id=None, gar_tp=record[1], gar_tpsub=record[2], fk_tb1=r) nr.save() In the code above, I am using a record from tb1 as foreign key in tb2. Now I want to change the code in order to use data input as dictionary, something like this: for e in df.T.to_dict().values(): tb2(**e).save() The problem is that I don't know how to insert a record from tb1 as a foreign key in this second code. Does anyone know how to help me? This change in will improve hugely the readability in my code. Thanks in advance. -
Django ordering by field value instead of ID
we're using Django 1.10 and DRF. By default the client can sort by any field of the model. But - on the model we're keeping the field id and not it's value. I would like to return a list that is sorted by the value. Part of the model: class Type(): Fly = {'id': '1', 'value': 'Fly'} Drive = {'id': '2', 'value': 'Drive'} Ski = {'id': '3', 'value': 'Ski'} Sail = {'id': '4', 'value': 'Sail'} class Item(BaseModel): TYPES = ( (Type.Fly['id'], Type.Fly['value']), (Type.Drive['id'], Type.Drive['value']), (Type.Ski['id'], Type.Ski['value']), (Type.Sail['id'], Type.Sail['value']), ) type_id = models.CharField(max_length=50, choices=TYPES) Part of the model view: class ItemViewSet(BaseViewMixin, BaseModelView): serializer_class = ItemSerializer filter_backends = (ItemFilter, OrderingFilter,) Now, if the client would request GET ......../Item?sort=type_id They would receive Fly, Drive, Ski, Sail While the required result is: Drive, Fly, Sail, Ski Any idea? -
Integrating ReactJS SPA with Django
I have a Django backend working and also a react SPA. I made the React build to store in Django static files directory, the web page works correctly. But my problem is Django still handles the routing for e.g the 404 pages and when a user reloads a route page it takes them to Django pages. -
How can I specify a subset to reference in a Django model ManyToMany field?
I am developing a Django backend that has a model Contract with a ManyToManyField that references a RoomType model. This Contract model also has a ForeignField to a Company model, and RoomType model has a ForeignKey to a Hotel model. I want to constrain the instances of RoomType that can be referenced in Contract.room_type to those that match RoomType.hotel with Contract.company. Is there any way to tell Django to enforce the matching of those two fields, or do I have to enforce it by hand by overriding save() method of model Contract? This are my models: class Contract(models.Model): DOLAR = 'USD' EURO = 'EURO' PESO = 'MXN' CURRENCY_CHOICES = ( (DOLAR, _('USD')), (EURO, _('EURO')), (PESO, _('MXN')) ) PENDING = 'PENDING' SIGNED = 'SIGNED' DUE = 'DUE' CANCELLED = 'CANCELLED' STATUS_CHOICES = ( (PENDING, _('Pending')), (SIGNED, _('Signed')), (DUE, _('Due')), (CANCELLED, _('Cancelled')) ) company = models.ForeignKey(Company, on_delete=models.PROTECT, related_name='contracts', verbose_name=_('Company')) representative_name = models.CharField(max_length=100, verbose_name=_('Representative Name')) representative_email = models.EmailField(verbose_name=_('eMail')) representative_phone = models.CharField(max_length=12, verbose_name=_('Representative Phone')) representative_fax = models.CharField(max_length=12, null=True, blank=True, verbose_name=_('Representative Fax')) start_date = models.DateField(verbose_name=_('Start Date')) due_date = models.DateField(verbose_name=_('Due Date')) currency = models.CharField(max_length=10, choices=CURRENCY_CHOICES, default=DOLAR, verbose_name=_('Currency')) days_credit = models.SmallIntegerField(null=True, blank=True, verbose_name=_('Days of Credit')) pre_pay = models.BooleanField(default=True, verbose_name=_('Pre-Pay')) advertising = models.TextField(null=True, blank=True, verbose_name=_('Advertising')) includes_comment = models.TextField(null=True, … -
cannot import name 're_path' I am using django version 2.0.6
I want to use re_path from django.urls, django doc says I can use this from django version 2, From the error I came to know that I am using django version 2.0.6. But I am not able to re_path ImportError at / cannot import name 're_path' Request Method: GET Request URL: http://filope.com/ Django Version: 2.0.6 Exception Type: ImportError Exception Value: cannot import name 're_path' Exception Location: /home/sugushiva/myproject/filope/blogs/urls.py in , line 1 Python Executable: /usr/bin/python3 -
No home page in Django CMS
I have a Django CMS site, and I want to have no home pages, because my home page is managed through a normal Django view. Is this possible? Right now if I have no pages, and add one, it's set to be the home page, and assigned to the home route ('/'). One of the possible solutions I'm thinking of is to set the Overwrite URL of the new page to something else, but it will still be considered the home page. Also, I can create an apphook for the corresponding app, and add a home page with that apphook. Maybe this makes more sense, but I want to have options in case I really need to manage the home page through a normal Django View. Thanks. -
form_valid is not called when render data with ajax in django
I am trying to upload a edited image to DB and for editing image I am using cropper.js, I am rending data with ajax with method = "POST" and for handling this data I am using generic.UpdateView but unfortunately form_valid and form_invalid are not called. Here is my ajax $("#upload-to-server").click(function(blob) { var formData = new FormData(); formData.append('cover_image', blob); // Use `jQuery.ajax` method $.ajax('{% url "accounts:update_profile" %}', { method: "POST", data: formData, processData: false, contentType: false, success: function () { console.log('Upload success'); }, error: function () { console.log('Upload error'); } }); }); Here is view class ImageUpdateView(generic.DetailView,generic.UpdateView): model = UserProfileModel form_class = UpdateCoverImage template_name = 'accounts/image-cropper.html' success_url = reverse_lazy('accounts:update_profile') def get_object(self): return get_object_or_404(UserProfileModel,user=get_current_user(self.request)) def form_invalid(self,form): print('In valid form',form) return super(ImageUpdateView,self).form_invalid(form) def form_valid(self,form): print('Valid Form',form) return super(ImageUpdateView,self).form_valid(form) In my console no error prints, no print statements, which I had given in form_valid but also no image update ! Probably I don't know the correct method to update image with ajax, that would be a great help for me if you guide me, thanks. -
django - deleting User raises integrity error
I am doing a "Reddit Clone" using django and these are my models: models.py class Profile(models.Model): owner = models.OneToOneField(User, on_delete=models.CASCADE) dob = models.DateField() karma = models.IntegerField(default=0) class Subreddit(models.Model): owner = models.ForeignKey(Profile, on_delete=models.DO_NOTHING, null=True, blank=True, related_name='subreddits') name = models.CharField(max_length=100) title = models.CharField(max_length=100) description = models.CharField(max_length=500) subscribers = models.ManyToManyField(Profile, blank=True, related_name='subscriptions') moderators = models.ManyToManyField(Profile, blank=True, related_name='moderates') class Post(models.Model): owner = models.ForeignKey(Profile, on_delete=models.DO_NOTHING) title = models.CharField(max_length=300) content = models.CharField(max_length=1000) votes = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) subreddit = models.ForeignKey(Subreddit, on_delete=models.CASCADE) class Comment(models.Model): owner = models.ForeignKey(Profile, on_delete=models.DO_NOTHING) content = models.CharField(max_length=500) votes = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) parent_post = models.ForeignKey(Post, on_delete=models.CASCADE) parent_comment = models.ForeignKey("Comment", null=True, blank=True, on_delete=models.CASCADE) Now, I tried to delete a user who just made 1 comment. When I tried to delete the user from django admin, I got the following error. IntegrityError at /admin/auth/user/2/delete/ (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (redditdb.redditapp_comment, CONSTRAINT redditapp_comment_owner_id_fdc65fee_fk_redditapp_profile_id FOREIGN KEY (owner_id) REFERENCES redditapp_profile (id))') I did user on_delete=models.CASCADE so I don't know why I am getting this error. Do I need to restructure the foreign keys in my models? -
How to forcefully log out a user when user closes tab or browser on website built on django2.0
I used built-in login logout functionality by Django using Django authentication, this is the following url pattern for logging in urls.py: from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('',views.home), path('admin/', admin.site.urls), path('users/', include('users.urls')), path('users/', include('django.contrib.auth.urls')), path('dashboard/', include('dashboard.urls')), ] And i added following in my setting.py settings.py: LOGIN_REDIRECT_URL = 'dashboard:home' LOGOUT_REDIRECT_URL = 'dashboard:home' Now how do I check whether user closed his browser and he should be logged out? PS:I made my own logging in and sign-up HTML pages and made my own customuser derived from AbstractUser -
Sqlite DB for questions ranging from level 1 to 5
Currently I'm working on an online test MCQs project and i need to apply adaptive algorithm later so i need to set the levels for each question(1-5) and using sqlite. Can anybody provide some examples? for creating the database? for this mcq app.