Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Call function when someone pays through PayPal
I am trying to work out how to call a function or something that will add points to a user's account when they purchase something through PayPal. For example, if someone buys 1000 credits it will add 1000 credits to a database field for their account. All help is appreciated, if anyone needs more information feel free to ask. -
set date format in Timezone aware date object
I want to get date in this format %d-%m-%Y" in following code: from django.utils.timezone import localtime, now from freezegun import freeze_time ..... @freeze_time("12-02-2012") def setUp(self): self.current_date = localtime(now()).date() In my settings.py I have these settings: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Dhaka' USE_I18N = True USE_L10N = True USE_TZ = True DATE_INPUT_FORMATS = ("%d-%m-%Y", ) DATE_FORMAT = ("%d-%m-%Y", ) But now I am getting date 2012-12-02. So what is the correct way to get date in %d-%m-%Y format in test client. -
Implementing django-vote app
I'm trying to use https://github.com/shanbay/django-vote package for my Django app. I'm not very expierenced python/django developer, so can someone provide simple example how to use this package in the real app (not vote API)? Pretending I have my models.py class Question(models.Model): topics = models.ManyToManyField('questions.Topic', related_name="questions") title = models.CharField(max_length=50) body = models.CharField(max_length=200) author = models.ForeignKey(User, default="") slug = models.SlugField(default="") created_at = models.DateTimeField(default=timezone.now) votes = VotableManager() def __str__(self): return self.title def get_absolute_url(self): return reverse("question", kwargs={"pk": self.id}) Now I want simple functionality: vote-up button and showing vote count in my template. I know that it might be simple, but I can't figure out how. Thanks in advance. -
Python/ Django- localhost is trying to load old code
I am working on a bug in my Python/ Django project, and just made some changes to one of the forms in my project. After making the change, I reloaded the webpage on which the form is displayed, and found that the change I had made did not caused another issue, and the page wouldn't load, so I undid the changes & tried reloading again. However, my page is now not loading- the browser displays a message stating: The site can't be reached. localhost refused to connect and the console shows an error message that says: TypeError: init() got an unexpected keyword argument 'attrs' This was the change that I had made, and have since undone, so it seems as though the browser is trying to load the page with the form as it was before I undid the change... I tried closing the browser tab on which I was trying to load localhost, and then tried loading it from a new tab, but get the same issue. Why is it that my browser is not trying to use the code as it currently is, but trying to load code that no longer exists? I have saved the file in … -
Django: real time search keyword showing?
What I want to implement is: If I type #ap in my search bar, it shows available recommendation keywords like #apple, #application, #ape etc. (Like searching in Instagram) I have no idea what to search in google. Or any other good django package or something? -
Django Tastypie: instancemethod object is not iterable
Trying to add ToManyField to the resource. Here is the model: class Project(models.Model): ... def access_set(self): return User.objects.all() Here is the resource: class ProjectResource(ModelResource): ... access = fields.ToManyField(UserResource, attribute = 'access_set', readonly=True, null=True) ... I have the error: 'instancemethod' object is not iterable Any thoughts please? -
Optimize Nginx + Gunicorn + Django nonrel?
How do I optimize my Nginx + Gunicorn + Django nonrel to accept more connections and perform better? -
How to create a private user to user messaging?
I'd like to create a custom private user to user messaging system. It should be really simple, the users cannot delete their own messages or edit them. Once it's sent it shows as a comment system. The user should also be able to look at the conversation history with other users. Here is what I thought doing : models.py class chat(models.Model): created = models.DateTimeField(auto_now_add=True) sender = models.ForeignKey(User, related_name="sender") receiver = models.ForeignKey(User, related_name="receiver") message = models.TextField(max_length=255) I don't want the user to type the receiver's name, there will be a contact button on the receiver's profile which will lead to the private chat. With these informations, what infrastructure do I need to set up ? (I don't want to use another built messaging system from another django projects for learning and futur customisation reasons.) -
jQuery datetimepicker limits selectable dates to end of current year
I have recently taken over the development of some software that has been written in Python/ Django. A form on one of the pages on the website allows users to enter a date/ time using a jQuery datetimepicker, and there is an issue with this, that range of dates available for selection is limited to dates between the beginning of the previous year up to the end of the current year (i.e. dates currently available are between 01/01/2016- 31/12/2017). While this is not currently an issue, it did cause some issues towards the end of last year, when my colleagues wanted to schedule meetings for the beginning of this year, but weren't able to as dates beyond 31/12/2016 were not able to be selected. I created a temporary fix for this at the time by allowing users to manually type in the dates/ times that they wanted to schedule meetings for. Now, after the new year, the dates available for selection in this field is limited to 01/01/2016- 31/12/2017, whereas up until the end of last year the dates available were 01/01/2015- 31/12/2016. So it appears that the values are being restricted to dates between the beginning of the previous … -
django/gunicorn/nginx caching with nginx
I have tried unsuccessfully to setup NGINX caching in this situation. I have gotten django caching to work, but I would ultimately like to move to NGINX doing all of the caching work but I am unclear how some of the pieces fit together. Here is what I think I would have to do in this setup... Set the caching headers in django through some custom middleware (I believe I would have to set EXPIRES, LAST_MODIFIED, and CACHE_CONTROL: max-agefoo I would then have to setup NGINX caching like I tried before using this guis(https://www.nginx.com/blog/nginx-caching-guide/) But I can't seem to figure out how this setup would respect cookies....Say a user logs in and does something at the url /account/change-email. what would happen when the next person goes to that URL? would they see the cached account page from the last person? Am I missing anything about the setup that I have not thought about? -
Python library to convert CAD files .dwg to .svg/PDF?
Is there any python library to convert cad file .dwg to .svg or PDF file? I want to render CAD files in web application. Anybody has solution? -
Does Django oscar provides features to connect your e commerce website with other ecommerce websites
I have not integrated oscar in my django project and I am planning to build an eCommerce web site using oscar. But we will be having a requirement at later stage to add connector between our website and other eCommerce giants like alibaba, amazon, ebay. So if someone have any knowledge regarding this? Thanks! -
getting a value from Redis which is saved in Redis within another function in django views.py
I am completely new to redis, so please accept my apologize if the question is too basic. I want to set a django model in my redis data store, and then in another view function, I wanna get it and reuse it again; but it turns out to say : TypeError: must be string or buffer, not None. this is my code in views.py : connection = redis.Redis('localhost') def recharge_account(request): cur = recharge_form.cleaned_data['currency'] amnt = recharge_form.cleaned_data['amount'] user_profile = models.UserProfile.objects.get(user=models.User.objects.get(id=request.user.id)) user_b_account, created = models.BankAccount.objects.get_or_create( owner=user_profile, cur_code=cur, method=models.BankAccount.DEBIT, name=request.user.username + '_' + cur + '_InterPay-account', account_id=make_id() ) # saving the temporarily deposit in redis deposit_dict = {"account": user_b_account, "amount": amnt, "banker": user_profile, "date": user_b_account.when_opened, "cur_code": cur} pickled_deposit_dict = pickle.dumps(deposit_dict) cached_deposit_name = str(user_profile.user_id) + "-cachedDeposit" connection.set(cached_deposit_name, pickled_deposit_dict) test_dict = {"one": 1, "two": 2} pickled_test_dict = pickle.dumps(test_dict) cached_test_name = "test" connection.set(cached_test_name, pickled_test_dict) .... def callback_handler(request, amount): #getting from redis new_deposit = pickle.loads( connection.get(str(user_profile.user_id) + "-cachedDeposit")) deposit = models.Deposit(account=new_deposit['account'], amount=new_deposit['amount'], banker=new_deposit['banker'], date=new_deposit['date'], cur_code=new_deposit['cur_code']) deposit.save() ..... My question is: is there any problem with my procedure? Is there any problem with saving a django model in redis ? What should I do to get this function work properly and getting the saved data "not to be … -
django caching and ajax requests
I've setup django filesystem caching from this guide (https://docs.djangoproject.com/en/1.10/topics/cache/)and it seems to be working for "regular" requests, but at the same time it seems to be treating ajax requests differently and not caching them.. example.com/about will be cached just fine, but if I have a page that loads and then sends an API request to get-data.json?foo=1&bar=2 to retrieve and do something with some JSON data, that request is not cached (because when it is returned, the DATE and EXPIRES are returned, they are the same). Is this normal behavior? How can I make it so that request would be cached? -
Python/Django 1.5/Djangocms 2.4
I have project code and database backup of my currently running site over internet written in python 2.7 using django framework. How to deploy it in my local machine or on a staging server. -
django.core.exceptions.ImproperlyConfigured: WSGI application 'application' could not be loaded
The scenario is, I cloned the Django code for OpenShift-V3 from here . When I run the code using python manage.py runserver getting an error as, django.core.exceptions.ImproperlyConfigured: WSGI application 'application' could not be loaded; Error importing module: 'application doesn't look like a module path I didn't add anything to the code and the required packages are already satisfied. -
Django UnicodeDecodeError "utf-8 can't decode byte 0x89 in position 0" while sending base64 encoded string
I am sending base64 encoded string with this JavaScript code: decodeURIComponent(escape(window.btoa(body.profile_image))) In the back-end, I am using Base64ImageField from drf-extra-fields from drf_extra_fields.fields import Base64ImageField class StudentProfileSerializer(serializers.ModelSerializer): user = UserInfoSerializer() clazz = ClassSerializer() profile_image = Base64ImageField(use_url=True) class Meta: model = Student fields = ('user', 'clazz', 'profile_image', 'info') depth = 1 def update(self, instance, validated_data): user_data = validated_data.get('user', {}) username = user_data.get('username', '') if User.objects.exclude(pk=instance.user.pk).filter(username=username): raise serializers.ValidationError( 'Student with this username already exists.' ) instance.user.__dict__.update(**user_data) instance.user.save() instance.__dict__.update(**validated_data) instance.save() return instance And when I send an image from the client, it throws Error 500: Internal Server Error with the following message: 'utf-8' can't decode byte 0x89 at position 0: invalid start byte. As long as I've read - I need to encode my image to base64 and then the Base64ImageField cares about decoding it. The real surprise is that the image is updated, but the error is still thrown, which is really strange. I tried some other encodings, but it still throws Error 500. -
Django Uploading xls files
I am new to django and I want to make a simple task though I am a bit confused with the django framework. I want to allow the user upload an xls file, then I want to run my own python script on this xls file (like extracting words for example), and then show an informative message to the user. Where can I start? I red the django tutorial and I looked at some answeres here that are related but still I don't know how to begin. any help would be appriciated. -
How to avoid using too much foreign key django
I just want to store tags data inside entry model Entry title content tags Tags should be Array but ArrayField is not portable to other database. I want to use portable alternative. -
Django union two tables into single model
I have an external database which I can't modify in any way (read-only). It has three columns - Company (id), CompanyContact (company_id, contact_id), Contact (id, company_id). Basically, Contact has a nullable foreign-key to Company table and it works as many-to-one, but if company_id is null, I have to look into CompanyContact table, which is many-to-many kind relationship. How can I combine these two tables (Contact and CompanyContact) into one model - Contact? In other words, how can I get all contacts for a given company? In SQL that would be something like: select contact.id from contact where company_id = XXX union select contact_id from companycontact where company_id = XXX -
Cannot import SubfieldBase from django.db.models import SubfieldBase
I am trying to get rid of the error and couldn't find a clue how to fix it. Please advise because I've seen few fixes in different packages but none of them are relevant. Traceback: Traceback (most recent call last): File "C:\Users\AliKhan\supermarekt\market\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 341, in execute django.setup() File "C:\Python27\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 85, in popu late app_config = AppConfig.create(entry) File "C:\Python27\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\AliKhan\supermarekt\market\catalogue\__init__.py", line 4, in <module> from django.db.models import SubfieldBase ImportError: cannot import name SubfieldBase In my Catalouge package I've just simply imported it and import is getting failed. from django.core.exceptions import ImproperlyConfigured from django.db.models.fields import CharField, DecimalField from django.db.models import SubfieldBase from django.utils import six from django.utils.translation import ugettext_lazy as _ Django Source code for SubfieldBase is following that lies at djagno.db.models.subclassing.py for Django version 1.8.16. import warnings from django.utils.deprecation import RemovedInDjango110Warning class SubfieldBase(type): """ A metaclass for custom Field subclasses. This ensures the model's attribute has the descriptor protocol attached to it. """ def __new__(cls, name, bases, attrs): warnings.warn("SubfieldBase has been deprecated. Use Field.from_db_value … -
django-registration module dont send email
i try to send activation email and reset email in django. i use django registration module but after register return back me to registration page and did not sent any email to me part of settings.py DEBUG = False ALLOWED_HOSTS = ['mysite.com', 'www.mysite.com'] EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = 'info@mysite.com' EMAIL_HOST_USER = 'info@mysite.com' EMAIL_HOST_PASSWORD = 'my pass' EMAIL_USE_TLS = True EMAIL_PORT = 1025 # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'posts', 'registration', 'django_countries', 'crispy_forms', 'django_forms_bootstrap', 'captcha', ] ACCOUNT_ACTIVATION_DAYS = 7 REGISTRATION_AUTO_LOGIN = True SITE_ID = 1 -
mysql.connector.errors.InterfaceError: Failed parsing EOF packet
I run into such problems when I running my Django project(a week ago, the project work properly, today find this problem): My Django version is 1.10.2, MySQL version is 5.5 on ubuntu 14.0. /Users/deja/Virtualenv/python3.5/bin/python3.5 /Applications/PyCharm.app/Contents/helpers/pydev/pydevd.py --multiproc --qt-support --client 127.0.0.1 --port 60850 --file /Users/mozat/project/crawler_management_system/manage.py runserver 0.0.0.0:6380 pydev debugger: process 81527 is connecting Connected to pydev debugger (build 145.1504) pydev debugger: process 81528 is connecting Performing system checks... System check identified no issues (0 silenced). You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. January 03, 2017 - 07:55:47 Django version 1.10.2, using settings 'crawler_management_system.settings' Starting development server at http://0.0.0.0:6380/ Quit the server with CONTROL-C. Internal Server Error: / Traceback (most recent call last): File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/mysql/connector/network.py", line 226, in recv_plain chunk = self.sock.recv(4 - packet_len) socket.timeout: timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/mozat/project/crawler_management_system/crawler_management_system/mysql_utility.py", line 32, in open_db raise err File "/Users/mozat/project/crawler_management_system/crawler_management_system/mysql_utility.py", line 28, in open_db yield cursor File "/Users/mozat/project/crawler_management_system/crawler_management_system/views.py", line 40, in select_batch_records cursor.execute(sql.format(table=self.table,times=times)) File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/mysql/connector/cursor.py", line 515, in execute self._handle_result(self._connection.cmd_query(stmt)) File "/Users/deja/Virtualenv/python3.5/lib/python3.5/site-packages/mysql/connector/connection.py", line 488, in cmd_query result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query)) … -
How to view AutoCAD file using HttpResponse?
I want to view autoCAD files using HttpResponse. I tried the following MIME type (content-types) but it is not showing instead it is downloading.. application/acad, image/vnd.dwg, image/x-dwg I am trying to view .dwg files. Anybody has any idea? -
Skip system checks on Django server in DEBUG mode in Pycharm
I am running django application in Pycharm in DEBUG mode. Each time when i change some code system checks are performed. pydev debugger: process 2354 is connecting Performing system checks... Is there any way to skip system checks/speed up this checks?