Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding contact-us feature in django website
How to add contact-us facility through email in a website built using django? -
Can't install django cms
Hey I'm stuck with django cms installation. I'm using ubuntu 16.0, python 2 How I installed: 1.virtualenv A 2.source A/bin/activate 3.aptitude install libpq-dev python-dev libjpeg-dev libpng-dev 4.sudo aptitude install libmysqlclient-dev python-dev 5.pip install pillow 6.pip install psycopg2 7.pip install djangocms-installer 8.mkdir Aa 9. cd Aa/ and I run command djangocms -f -p . mysite After running the command I get an error: File "/root/A/bin/djangocms", line 11, in <module> sys.exit(execute()) File "/root/A/local/lib/python2.7/site-packages/djangocms_installer/main.py", line 41, in execute django.setup_database(config_data) File "/root/A/local/lib/python2.7/site-packages/djangocms_installer/django/__init__.py", line 388, in setup_database output = subprocess.check_output(command, env=env) File "/usr/lib/python2.7/subprocess.py", line 574, in check_output raise CalledProcessError(retcode, cmd, output=output) subprocess.CalledProcessError: Command '['/root/A/bin/python' -
django-ckeditor non staff member image upload
I have deployed my site and want regular (logged in) users to be able to upload images, how to do this is described on git homepage/readme: Add CKEditor URL include to your project's urls.py file: (r'^ckeditor/', include('ckeditor_uploader.urls')), Note that by adding those URLs you add views that can upload and browse through uploaded images. Since django-ckeditor 4.4.6 those views are staff_member_required. If you want different permission decorator (login_required, user_passes_test etc.) then add views defined in ckeditor.urls manually to your urls.py. and here is my urls.py file: from django.conf.urls import url, include from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ url(r'^$', views.index, name='index'), # ex: /reports/5/ url(r'^(?P<report_id>[0-9]+)/$', views.detail, name='detail'), url(r'^create/$', views.create, name='create'), url(r'^create2/$', views.reportsparticipants, name='reportsparticipants'), url(r'^addparticipants/$', views.addparticipants, name='addparticipants'), url(r'^(?P<report_id>[0-9]+)/like/$', views.like, name='like'), url(r'^(?P<report_id>[0-9]+)/dislike/$', views.dislike, name='dislike'), url(r'^deleteparticipant/(?P<part_id>[0-9]+)/$', views.deleteparticipant, name='deleteparticipant'), url(r'^modify/(?P<report_id>[0-9]+)/$', views.modify, name='modify'), url(r'^modifyparticipants/(?P<report_id>[0-9]+)/$', views.modifyparticipants, name='modifyparticipants'), url(r'^deleteparticipantmodify/(?P<part_id>[0-9]+)/(?P<report_id>[0-9]+)/$', views.deleteparticipantmodify, name='deleteparticipantmodify'), url(r'^reportadded/$', views.reportadded, name='reportadded'), url(r'^commented/(?P<report_id>[0-9]+)/$', views.commented, name='commented'), url(r'^ckeditor/', include('ckeditor_uploader.urls')), #url(r'^liked/(?P<report_id>[0-9]+)/$', views.liked, name='liked'), url(r'^dc/$', views.dc, name='dc'), ] I can't think of the appropriate changes to my urls.py file for the desired state described in step 2 -
Psycopg2 Error- Reason: Image not found in Django project running PostgresApp
I have a Django project running a PostgreSQL database. I run the postgresapp for this. I installed psycopg2 using pip and ran the command: python manage.py migrate I got the following error: Referenced from: /Users/{{my_username}}/{{my_project}}/myvenv/lib/python2.7/site-packages/psycopg2/_psycopg.so Reason: image not found I obviously googled and came across some solutions. I then ran the following commands from the solutions: sudo ln -s /Applications/Postgres.app/Contents/MacOS/lib/libssl.1.0.0.dylib /usr/lib ln: /usr/lib/libssl.1.0.0.dylib: File exists sudo ln -s /Applications/Postgres.app/Contents/MacOS/lib/libcrypto.1.0.0.dylib /usr/lib ln: /usr/lib/libcrypto.1.0.0.dylib: File exists Each time, it says the file exists. So I ran the migrate command again, and the error still occurred. What am I doing wrong? How can I fix this? Any help? Thanks. -
Office365 Authentication: getting user email from access token
I am using python and django for my web application, and I am trying to use Microsoft Graph API for user sign in authentication to my app using their office365 credentials. I've read up on examples on the web and have been able to successfully get an authorization code and an access token. However I am not able to get a valid response from my GET API call, and get_me function. I keep getting a 500 error. I am using in my scopes openid, profile, and email. Any suggestions on what I am doing wrong? authhelper.py outlookservice.py -
Filter range from two dates in the same query Django/Python
I need to create a query to filter the range from 5 days but get the result from two dates from the same model: This is my code: startdate = datetime.now().date() endate = datetime.now().date() + timedelta(days=4) lineas_de_reporte = Reporteots.objects.filter(original_fcd_date__range=[startdate, endate], target_pdate__range=[startdate, endate]) But I'm not getting the result I want, any idea? -
Django 1.10: Commit data to log table after fail / rollback of main transaction
I am moving to Django 1.10 from Django 1.5 and discovering that database transactions are quite different with little commit and rollback control. What I want: Perform series of queries in view: my_function(request) If all queries succeed: commit if any query fails: rollback insert into log table and commit the insertion In Django 1.5, I handle this with rollback and commit in the Exception Middleware: class ExceptionMiddleware(object): def process_exception(self, request, exception): # do rollback # insert into log table # commit How can I achieve this in Django 1.10 where there doesn't seem to be a way to do rollback? My 1.10 settings: AUTOCOMMIT = True ATOMIC_REQUESTS = True This puts all queries into a single transaction that, correctly, only commits upon completion. I would have more rollback/commit control with "AUTOCOMMIT = False," but Django recommends against this: "this is best used in situations where you want to run your own transaction-controlling middleware or do something really strange." -
Please make a simple Chat application, using Python and Linux. The application should work in the following manner: [on hold]
Step 1- Open Application Screen Shows: Logo and signup/login window. -- (phone number is the primary id/Login id) Step 2- We will sign up with our phone number and password The application should create a new account, and ask us to login again using our newly created id and password Step 3 – When we login, we should see a list of contacts to chat with During the first login, we should not see any numbers added by default, we should be able to add numbers to our friend list, manually Once, we have added the phone numbers, the list should display these numbers Step 4 – Once we have the contacts list ready, we should be able to click any one of these contacts and chat with the contact Step 5 – Now when we leave this chat, and go back again, we should be able to see the chat messages sent in the past (Chat message history display) You need to implement this using Socket and MQTT protocol ***please help me how to start the project step by step. actually I'm beginner in python.*** -
How do you override Django's admin app_index?
I'm very familiar with how to override Django's admin templates, but I haven't been able to find any instructions on how to properly override the context available to said templates. For example this page: /admin/users/ The style for this page can be overridden by creating a file at: root/users/templates/admin/users/app_index.html But what if I want to do some more Python-level stuff before the template is loaded? Specifically in my case I want to generate a sort of dashboard for /admin/users/ and for that I'll need to run a rather elaborate query. Now I know I could hack this by creating a template tag that does the query for me, but frankly that's pretty dirty as you're hitting the database from a template, so I'd like to do this better if such a way exists. If however you can state with confidence (and convincingly) that this simply can't be done without rewriting django.contrib.admin.sites.AdminSite.app_index, then I'll flag your answer as correct and go with my ugly hack. -
PyTest-Django Failing on missing django_migration table
I'm trying to add pytest-django and pytest 3 to my current pytest2/Django1.7 environment. Everything seems to visually look good and the tests seem to pass until the end when I get the following error messages: request = <SubRequest '_django_db_marker' for <Function 'test_filter_recurring_outside_sync_window'>> @pytest.fixture(autouse=True) def _django_db_marker(request): """Implement the django_db marker, internal to pytest-django. This will dynamically request the ``db`` or ``transactional_db`` fixtures as required by the django_db marker. """ marker = request.keywords.get('django_db', None) if marker: validate_django_db(marker) if marker.transaction: getfixturevalue(request, 'transactional_db') else: getfixturevalue(request, 'db') ve/lib/python2.7/site-packages/pytest_django/plugin.py:376: self = <django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x11976a478> query = 'SELECT "django_migrations"."app", "django_migrations"."name" FROM "django_migrations"', params = () def execute(self, query, params=None): if params is None: return Database.Cursor.execute(self, query) query = self.convert_query(query) > return Database.Cursor.execute(self, query, params) E OperationalError: no such table: django_migrations ve/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py:485: OperationalError I tried creating the table with ensure_schema in the conftest.py. I've tried every option of --nomigrations and --create-db to pytest. I'm guessing it's a weird configuration problem I have with a legacy system, but I'm not sure where to start looking. Anyone have suggestions? -
Django model OneToOneField : "This field is required" error in admin
When I open an entry of "Placerating" in Admin, and try to save it after making a change to any field, Django admin displays "This field is required" above the field "Pic". class Placerating(models.Model): theplace = models.ForeignKey('ThePlace', on_delete=models.CASCADE, null=True, related_name='placeratings') pic = models.OneToOneField('fileupload.Picture', on_delete=models.SET_NULL, null=True) def __unicode__(self): return self.theplace.name class Picture(models.Model): def set_upload_to_info(self, path, name): self.upload_to_info = (path, name) file = ImageField(max_length=500, upload_to=user_directory_path) def filename(self): return os.path.basename(self.file.name) theplace = models.ForeignKey(ThePlace, null=True, blank=True, related_name='pictures') def __unicode__(self): return str(self.id) def save(self, *args, **kwargs): super(Picture, self).save(*args, **kwargs) I created the entry without problem with a form, so I don't understand why admin would now require this field to be completed. -
Build a sequence model in Django
I have a Django model named "orders", which represents objects which contains information about orders made at a shop. Those orders need to be processed until they are ready to be shipped, but their sequence of handling is not necessarily sorted for example by date. Also the user may drag an order from ex 1st place to the 3rd, or the opposite. What's the optimum method to build up such functionality in python/django? It should be something like a task queue, but of editable order. Any suggestions are more than welcome as I'm kinda stuck on this issue! Thanks in advance -
IntegrityError not raised on None
I have a model with the following unique constraints: class Record(Model): type = ForeignKey(Type, related_name='records') code = CharField(max_length=32) group = ForeignKey('self', null=True, blank=True, related_name='members') class Meta: unique_together = ('type', 'code', 'group') I want two records to be the same if they both have the same type and code, and both have no group. I expect an integrity error to be raised, but this does not happen in the following test case: Record.objects.create(type=type_article_structure, code='shoe', group=None) Record.objects.create(type=type_article_structure, code='shoe', group=None) The unique constraint is working if I fill the same group for both: group = Record.objects.create(type=type_article_structure, code='group') Record.objects.create(type=type_article_structure, code='shoe', group=group) Record.objects.create(type=type_article_structure, code='shoe', group=group) This results in: django.db.utils.IntegrityError: UNIQUE constraint failed: md_masterdata_record.type_id, md_masterdata_record.code, md_masterdata_record.group_id How can I make sure that I get the same error in the first case? PS. My test cases use SQLite, my production server uses PostgreSQL. -
Python pass arguments to callable function reference
I am not sure if I worded the question the best way but, in Django, our model fields can have a default value, which can be a function Example : (Yes I know it is pointless in context, and I know I can extend the base class/overwrite the save method) class MyModel(models.Model): #How do i pass an argument without calling it model_name = models.IntegerField(default=my_func) def my_func(model): return model.__name__ This should result in an error as my_func expects the model argument, but I can't call it in the default because it expects a function reference and will call it later. Can this be done in Python? -
Django - How to add an entry in Ascending order in the database efficiently?
I am working on making an application in Django that can manage my GRE words and other details of each word. So whenever I add a new word to it that I have learnt, it should insert the word and its details in the database alphabetically. Also while retrieving, I want the details of the particular word I want to be extracted from the database. Efficiency is the main issue. Should I use SQLite? Should I use a file? Should I use a JSON object to store the data? If using a file is the most efficient, what data structure should I implement? Are there any functions in Django to efficiently do this? Each word will have - meaning, sentence, picture, roots. How should I store all this information? It's fine if the answer is not Django specific and talks about the algorithm or the type of database. -
Django File Storage: Add passwords to file names
We use Python Django. I want to store user-uploaded files in the following way: /<INTEGER>/<PASSWORD>/<FILE> <INTEGER> is a subfolder which is meant to contain max 1000 files. <PASSWORD> is a secret code individual for each file, to prevent hackers to download a somebody's other file from our HTTPS server. <FILE> is the filename. How to write a Django storage implementing this? First, can I derive my class from django.core.files.storage.FileSystemStorage or I need to derived from django.core.files.storage.Storage directly? Second, which methods should I override? Should I override save? It seems yes, because it is best to generate the password only when saving, but I am unsure I can do in save what I need. What about overriding _save? Also: what's about overriding get_available_name and/or generate_filename? They seem not be quite tailored to my needs, because it would be better to generate the password only when actually saving the file, not just when considering its name. So, what to do? -
Django add a new argument to Field base class
Is it possible to add a new argument to the Field base class, that will be available in all other fields when I create them? For example, I want to add an optional argument called 'mask', with default value as False, and then all other fields will inherit it phone = models.IntegerField(verbose_name="Phone Number", mask = 'templates.masks.phone') My website is all AJAX based and server-rendered so this would be a great help -
Import all (*) from dynamic file
I have a package: urls/ __init__.py dev_urls.py prod_urls.py This urls package is in an app api and in my main urls.py: ... url(r'^api/v1/', include('apps.api.urls')), ... I know that if I add this to urls.__init__.py file: # __init__.py from dev_urls import * Django will run including dev_urls.py as apps.api.urls. But I'd like to make this dynamic by adding a variable in my settings module: # settings URLS_ENV = 'dev' # This could be 'prod' Then in my urls.__init__.py: # __init__.py from django.conf import settings name = settings.URLS_ENV + '_urls' Now, here is the question: How can I do somwthing like: from <name> import * Is this possible? -
Django- Uploading Data Methodologies
I would like to give to an user that is logged in the ability to upload his data into the database (postSQL). This information is composed of several single fields, like a name, but also a time series (for example: a track of 300 prices(float) with dates and type(string)). It seems that forms and formset are not really suitable for that. What do you recommand? I am working with the django-excel package. Do you think that it is the right package for this functionality? (i.e. an user fills in an excel template and uploads it) If not, what do you suggest? If so, the database is composed of several tables (models) which are linked together (by different Foreign key). How do you manage an upload within the tables (models)? Could you provide an example? How do you link an user to this upload? Could you also provide an example? Many thanks in advance for your help, Gilles -
ProgrammingError django migrations
I'm getting a programming error on our EC2 instance. Basically, our migration files are on the server and are correct but it says no migrations to apply when I run migrate. We use a testing website with a different database and when changes are ready for the production version, we merge the branches,hence the migration files are carried over from the testing repository to the production repository. All that's left to do is to migrate on the production server since the migration files are already on the server after merge. But, it says no migrations to apply. Has anyone experience this error before? -
django powered website switches between logged in users
I am trying to find the root cause for the following problem with a Django powered website. The problem is: Sporadically, a user that is currently logged into the website, on clicking random links on the website, is automatically switched to a different user along with the permissions of that user. It is not clear yet in which scenario this happens. Visiting different pages on the website may bring him back to his login. Django version: 1.9.4 Webserver: Apache/2.4.7 (Ubuntu 12.04) Database: mysql 5.5.4 Python: 2.7.3 MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Template caching is enabled: loaders = [('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ]), ] This website uses {% if user.is_authenticated %} in the templates. The user variable is set only once, and it is when the user logs in. LDAP Backend for authentication user = authenticate(username=username, password=password) function is run, and then login(self.request, user) return super(LoginView, self).form_valid(form) I read various blog posts about how Django does session handling. But I do not understand how refreshing/clicking around random links can switch the current user to a different one. If somebody knows what could be going wrong in this scenario, please reply. I hope I have given … -
Django delete old file before/after save new
My code in django view: file_obj = MyFile.objects.get(id=5) old_preview = file_obj.preview_path form = FilePreviewForm(request.POST, request.FILES, instance=file_obj) if form.is_valid: print old_preview # /upload/files/hahaha.jpg print file_obj.preview_path # ololo.jpg # you can see different objects - it's good! old_preview.delete() # I want delete only /upload/files/hahaha.jpg - old file print old_preview # print file_obj.preview_path # # you can see all files are deleted!!! it's so bad!!! Why is this happening? If I delete old file after saving, it will be the same. I checked! -
Get the average from list of values of foreign key object fields
I am making a movie rating app. Each movie can be rated by users. class MovieRating(models.Model): movie = models.OneToOneField(Movie) users = models.ManyToManyField(User, through='UserRating') average_rating = ??? or whichever is better @property def average_rating(self): ??? class UserRating(models.Model): movie_rating = models.ForeignKey(MovieRating) user = models.ForeignKey(User) rating = models.PositiveIntegerField( default=1, validators=[ MinValueValidator(1), MaxValueValidator(10) ] ) review = models.TextField() pub_date = models.DateTimeField(default=timezone.now) class Meta: unique_together = ('movie', 'user') I want to get the average rating of for that movie. Meaning average_rating = (Total rating by user for a MovieRating) / (Total users of MovieRating) I can get the total users of a MovieRating by movie_rating.users.count() But how do I get the rating of every users in Total? Or else what can I do to get the average rating for a movie? -
Retrieve files from local directory in django
I found myself in a situation where a client asked if we can serve the files in the web app withought him uploading them. Instead he wants to drop the files in a local directory. Let's say in '/Desktop/myfiles/'. Question #1 = Is it possible to rerieve all the files from a local directory? Question #2 = If I can retrieve the files from the local directory how can I store the file_path to store it in a FileField field in mymodel? So When I I write Mymodel.objects.all() I get all the Files!! PS: Of course I don't know the filenames in advance. That would be a bonus! Any Ideas? -
How does Django generates uuid?
I have a model in Django that uses uuid this way: uuid = models.CharField(max_length=100, default=uuid.uuid1) The thing is, when I generated 2 objects, one after the other, I got this: 933e35c4-df1c-11e6-8a53-ace01055799e And then: 933e35c5-df1c-11e6-8a53-ace01055799e From what I know every uuid is generated at random, but the probability of collision is very low, how are they exactly generated when I get these 2 uuid that are almost the same? (it differs only in the last number of the first block) and how probable is this?. Is there a more secure way of doing this? The thing is that I have a set of clients that each get a unique uuid by e-mail, if they could just change one character and get to another client's uuid that would be a problem.