Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cookie is not set in ajax calls from code but working fine in console
I am working on ajax call using jquery and django framework. I am getting 403 error in chrome when doing ajax call from website. But when I do ajax call from console, I am getting different response. Also, it is working in firefox. Here is my code $.ajaxSetup({ xhrFields: { withCredentials: true }, crossDomain: true }) $(document).ajaxSend(function (event, jqxhr, settings) { settings.data += '&csrfmiddlewaretoken=' + window.getCookie('csrftoken'); if (settings.type == "POST") { jqxhr.setRequestHeader('X-CSRFToken', window.getCookie('csrftoken')); }; }); $.ajax({ 'type':'POST', 'dataType':'json', 'url': url, 'data': data, }).always((data)=>{}) Can anyone tell me what is the problem? -
Does Django Cache Clear Itself After Expiration
I am currently working with Memcache and Django to cache data requested from an external API, so I don't overwhelm their servers. Currently my code looks like this: # CACHE CURRENT PRICE cache_key_price = str(stock.id)+'_price' # needs to be unique cache_key_change = str(stock.id)+'_change' # needs to be unique cache_keychange_pct = str(stock.id)+'_changePct' # needs to be unique cache_time = 60 * 5 # time in seconds for cache to be valid data = cache.get(cache_key_price) # returns None if no key-value pair if not data: delayed_price, change, changePct = get_quote(stock.ticker) cache.set(cache_key_price, delayed_price, cache_time) cache.set(cache_key_change, change, cache_time) cache.set(cache_keychange_pct, changePct, cache_time) context_dict['delayed_price'] = cache.get(cache_key_price) context_dict['change'] = cache.get(cache_key_change) context_dict['changePct'] = cache.get(cache_keychange_pct) I'm a bit new to caching and I am curious if after 5 mins the cache will clear itself and data will return None triggering the if not data: bit of code to get updated data. Thanks in advance for any help! -
403 Forbidden using mod_wsgi-express with https on apache2
I am using the following command to start mod_wsgi-express for my django project: mod_wsgi-express start-server --log-to-terminal --startup-log --https-port 443 --server-name example.com --ssl-certificate-file ssl-certs/cert.pem --ssl-certificate-key-file ssl-certs/privkey.pem --user www-data --group www-data --host example.com When loading https://example.com/, I get a 403 Forbidden error: You don't have permission to access / on this server. The terminal shows the following lines: root@localhost:/home/joel/new/myappointments# mod_wsgi-express start-server --log-to-terminal --startup-log --https-port 443 --server-name example.com --ssl-certificate-file ssl-certs/cert.pem --ssl-certificate-key-file ssl-certs/privkey.pem --user www-data --group www-data --host example.com Server URL : http://example.com:8000/ Server URL (HTTPS) : https://example.com/ Server Root : /tmp/mod_wsgi-example.com:8000:0 Server Conf : /tmp/mod_wsgi-example.com:8000:0/httpd.conf Error Log File : /dev/stderr (warn) Startup Log File : /dev/stderr Request Capacity : 5 (1 process * 5 threads) Request Timeout : 60 (seconds) Startup Timeout : 15 (seconds) Queue Backlog : 100 (connections) Queue Timeout : 45 (seconds) Server Capacity : 20 (event/worker), 20 (prefork) Server Backlog : 500 (connections) Locale Setting : en_US.UTF-8 [Sat Sep 08 20:51:37.800732 2018] [ssl:warn] [pid 5130:tid 140248589061056] AH01873: Init: Session Cache is not configured [hint: SSLSessionCache] [Sat Sep 08 20:51:37.803786 2018] [mpm_event:notice] [pid 5130:tid 140248589061056] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.6.4 Python/3.6 OpenSSL/1.1.0g configured -- resuming normal operations [Sat Sep 08 20:51:37.804264 2018] [core:notice] [pid 5130:tid 140248589061056] AH00094: Command line: 'apache2 (mod_wsgi-express) … -
CircleCI 2.0 - explicitly add project to Python path
I'm unsure how to set the PYTHONPATH correctly in CircleCI 2.0 to allow the build to run. This is a Django project that was previously building on CircleCI 1.0 successfully so I've started by using the auto generated config.yml file. version: 2 jobs: build: working_directory: ~/mygithubname/myproject parallelism: 1 shell: /bin/bash --login environment: CIRCLE_ARTIFACTS: /tmp/circleci-artifacts CIRCLE_TEST_REPORTS: /tmp/circleci-test-results DATABASE_URL: 'sqlite://:memory:' DJANGO_SETTINGS_MODULE: ocdaction.settings.test DEBUG: 0 PYTHONPATH: ${HOME}/myproject/myproject docker: - image: circleci/build-image:ubuntu-14.04-XXL-upstart-1189-5614f37 command: /sbin/init steps: - checkout - run: mkdir -p $CIRCLE_ARTIFACTS $CIRCLE_TEST_REPORTS - restore_cache: keys: # This branch if available - v1-dep-{{ .Branch }}- # Default branch if not - v1-dep-master- # Any branch if there are none on the default branch - this should be unnecessary if you have your default branch configured correctly - v1-dep- - run: pip install -r requirements/testing.txt - save_cache: key: v1-dep-{{ .Branch }}-{{ epoch }} paths: # This is a broad list of cache paths to include many possible development environments # You can probably delete some of these entries - vendor/bundle - ~/virtualenvs - ~/.m2 - ~/.ivy2 - ~/.bundle - ~/.go_workspace - ~/.gradle - ~/.cache/bower - run: pytest - store_test_results: path: /tmp/circleci-test-results - store_artifacts: path: /tmp/circleci-artifacts - store_artifacts: path: /tmp/circleci-test-results the run: pytest command is failing … -
Get current logged in user ID through WP/WC API
I am currently working on Dashboard application made with Django which pulls data from a Wordpress/Woocommerce website through WC/WP API and stores it in a PostgreSQL database. In a part of the application, I need to pull the data of currently logged in user of WP/WC website through API. I have studied Wordpress REST API documentation, but could not find any solution or endpoint for that. What I want to accomplish is: to retrieve the user ID of the current logged in user of WP/WC website in Django application. Do you have any idea how to accomplish that? I am a little bit novice in WP. Any kind of help will appreciable. Thanks -
How to modify how Djongo ArrayModelField is shown in Django Admin
I'm experimenting with Djongo right now. So far a great project! What I don't like yet is the way ArrayModelField fields are integrated in the Django admin. I am missing something like an add-button. At the moment only one additional empty inline Form is shown for the nested model. Is there a possibility to add new inline models with an "add-button"? -
Unable to create django queries for the logic required?
I want help to create django query => select those journal names which matches some ledger1.name for any particular date range, also filter all transactions in which the ledger name exists in 'By' field, and aggregate their 'To' sides total. I have the following django models: class ledger1(models.Model): Creation_Date = models.DateField(default=datetime.now) name = models.CharField(max_length=32,unique=True) group_Name = models.ForeignKey(group1,on_delete=models.CASCADE) Opening_Balance = models.DecimalField(max_digits=19,decimal_places=2) class journal(models.Model): Date = models.DateField() By = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Debitledgers') To = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Creditledgers') Debit = models.DecimalField(max_digits=10,decimal_places=2,) Credit = models.DecimalField(max_digits=10,decimal_places=2) thankyou. -
Django sql-modifying onclick function
So I'm working on some Django app right now, which is basically kind of personal movie list. This app contains: Movie Model Custom User model I want this app to display every user's lists as well as the main list, which contains every movie. In this last list I want to add in every row a custom button with onclick function, that adds this certain movie to logged in user list and saves it. How and where do I make this function, to Add movie, which is in the same row, to a ManyToMany relationship with my user model? I tried to search how to do it, yet I didn't find a case, which contains onclick button actions, which modifies sql. Here's my code: Models.py from django.contrib.auth.models import User from django.db import models class Movie(models.Model): movie_id = models.PositiveIntegerField(default=0) title = models.CharField(max_length=100) director = models.CharField(max_length=50) year = models.CharField(max_length=4) kind = models.CharField(max_length=20) countries = models.CharField(max_length=50) class NormalUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) movies = models.ManyToManyField(Movie) Views.py from .models import NormalUser, Movie def index(request): movie_list = Movie.objects.order_by('-title') context = { 'movie_list': movie_list, } return render(request, 'PTWList/index.html', context) def userlist(request, pk): normal_user = get_object_or_404(NormalUser, pk=pk) current_user = request.user context = {'normal_user': normal_user, 'current_user': current_user, 'pk': … -
Apache 2.4 wouldn't able to serve Django app on Centos 7
I am not able to serve Django web-applications with Apache 2.4 on Centos 7 O.S. Here, my configuration would be like, Alias /static /home/deepenpatel19/panchayat/panchayat/static <Directory /home/deepenpatel19/panchayat/panchayat/static> Require all granted </Directory> <Directory /home/deepenpatel19/panchayat/panchayat/panchayat> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess panchayat python- path=/home/deepenpatel19/panchayat/panchayat:/bin/python3.6 WSGIProcessGroup panchayat WSGIScriptAlias / /home/deepenpatel19/panchayat/panchayat/panchayat/wsgi.py <Directory /home/deepenpatel19/panchayat/panchayat/panchayat> <Files wsgi.py> Require all granted </Files> </Directory> I have given permission 755 to all directory files and folders. Still, apache gives me 500 error and log would be like, [Sat Sep 08 13:38:01.566214 2018] [mime_magic:error] [pid 8202] [client 103.215.93.12:48922] AH01512: mod_mime_magic: can't read `/home/deepenpatel19/panchayat/panchayat/panchayat/wsgi.py' [Sat Sep 08 13:38:01.566422 2018] [mime_magic:error] [pid 8202] [client 103.215.93.12:48922] AH01512: mod_mime_magic: can't read `/home/deepenpatel19/panchayat/panchayat/panchayat/wsgi.py' [Sat Sep 08 13:38:01.574978 2018] [:error] [pid 8199] (13)Permission denied: [remote 103.215.93.12:0] mod_wsgi (pid=8199, process='panchayat', application='website.us-central1-c.c.panchayat- 215804.internal|'): Call to fopen() failed for '/home/deepenpatel19/panchayat/panchayat/panchayat/wsgi.py'. [Sat Sep 08 13:38:02.054667 2018] [mime_magic:error] [pid 8203] [client 103.215.93.12:48924] AH01512: mod_mime_magic: can't read `/home/deepenpatel19/panchayat/panchayat/panchayat/wsgi.py' [Sat Sep 08 13:38:02.054828 2018] [mime_magic:error] [pid 8203] [client 103.215.93.12:48924] AH01512: mod_mime_magic: can't read `/home/deepenpatel19/panchayat/panchayat/panchayat/wsgi.py' [Sat Sep 08 13:38:02.055102 2018] [:error] [pid 8199] (13)Permission denied: [remote 103.215.93.12:180] mod_wsgi (pid=8199, process='panchayat', application='website.us-central1-c.c.panchayat- 215804.internal|'): Call to fopen() failed for '/home/deepenpatel19/panchayat/panchayat/panchayat/wsgi.py'. Also, I have checked wsgi.py file path and it's correct. root@website panchayat]# ll /home/deepenpatel19/panchayat/panchayat/panchayat/wsgi.py -rwxr-xr-x. … -
Not able to map a view with url
I am facing some problem while mapping a view with URL Project name-Hero app name-Movie Hero/url.py: from django.conf.urls import include,url from django.contrib import admin urlpatterns=[ url(r'^admin/',admin.site.urls), url(r'^',include('Movie.urls')) ] Movie/urls.py: from django.conf.urls import url from . import views urlpatterns=[ url(r'^$',views.index,name='Movie'), ] views.py: from django.http import HttpResponse def index(request): return HttpResponse("<h1>Hello friends ,Welcome to Django Project</h1>") These are my urls and views configurations.I am getting a 404 page. Please help me out.. Thanks -
How to auto insert the current user when creating an object in django Create template?
I have a database of articles with a User=models.ForeignKey(User,related_name="Company_Owner", on_delete=models.CASCADE) Where User is imported as follows: from django.contrib.auth.models import User. I would like to auto insert the current active user to the User field when a particular user submits the article. I have done this in django admin: class companyAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): if getattr(obj, 'User', None) is None: obj.User = request.user obj.save() But it is changing for the superusers only if I login to django admin,it doesnot change for all users if I submit a form from template it doesnot return the specific user. Anyone have any suggestions? -
Django console email backend in production with gunicorn and nginx
I used django console email backend in development and It worked fine. Now for test I tried production with gunicorn and nginx, but I have no email backend for now so I used django console email backend again for sending emails, where can I see emails? is there any log to check them? or In production console backend wouldn't work? -
Django Model name instance
I have two forms for two different category of accounts. I want to do some calculations based upon which category made the booking. models.py class category1(models.Model): name = models.CharField(max_length=100) contact = models.CharField(max_length=100) email = models.CharField(max_length=100) def __str__(self): return self.name class category2(models.Model): name = models.CharField(max_length=100) contact = models.CharField(max_length=100) email = models.CharField(max_length=100) def __str__(self): return self.name class booking(models.Model): booked_by = models.CharField(max_length=100) amount = models.IntegerField() Total = models.IntegerField() def save(self, *args, **kwargs): if self.booked_by == category1:(NEED HELP OVER HERE, what query should I use) self.Total = self.amount * 2 if self.booked_by == category2:(NEED HELP OVER HERE, what query should I use) self.Total = self.amount * 4 super(booking,self).save() forms.py class bookingform(ModelForm): class Meta: model = booking exclude = ('booked_by','Total') view.py class bookings_create(LoginRequiredMixin,CreateView): login_url = 'Mel:user_login' form_class = bookingform template_name = 'Mel/bookings_form.html' def form_valid(self, form): form.instance.booked_by = self.request.user return super(bookings_create, self).form_valid(form) If the booking is made by category1 then do some calculations. If booking is made by category2 do some calculations. -
A user with that username already exists django
I am trying to sign up a new user when the user activates his email address. i am getting this error A user with that username already exists. when i filled up the form and clicked sign up an instance has created(i checked the admin page) but then immediately the error shows up. here is my forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=254) class Meta: model = User fields = ('username', 'email', 'password1', 'password2', ) and here is my views views.py def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate Your UosFiles Account' message = render_to_string('registration/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('users:account_activation_sent') else: form = SignUpForm() return render(request, 'registration/signup.html', {'form': form}) def activate(request, uidb64, token): try: uid = urlsafe_base64_decode(uidb64).decode() user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.profile.email_confirmed = True user.save() login(request, user) return HttpResponseRedirect(reverse('files:dashboard')) else: return render(request, 'account_activation_invalid.html') my models models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() -
Tried all possible sollutionbut still Not able to install mysqlclient
i am not able to install mysqlclient on my windows 10 pc tried: -->installed visual studio -->upgraded pip -->upgraded wheel -->pip install mysqlclient -->tried installing almost 10 versions of mysqlclient wheel -->pip install --only-binary :all: mysqlclient 1.pip install --only-binary :all: mysqlclient Error :- Could not find a version that satisfies the requirement mysqlclient (from versions: ) No matching distribution found for mysqlclient 2.python -m pip install mysqlclient-1.3.7-cp35-cp35m-win_amd64.whl Error: mysqlclient-1.3.7-cp35-cp35m-win_amd64.whl is not a supported wheel on this platform. pip install mysqlclient Error : _mysql.c(29): fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\bin\HostX86\x86\cl .exe' failed with exit status 2 Failed building wheel for mysqlclient -
Render foreign key __str__ method in a template django
class A(models.Model): field1 = models.CharField(max_length=10) field2 = models.IntegerField(default=0) def __str__(self): return self.field1 + str(self.field2) class B(models.Model): a = models.ForeignKey(A) ... Now in a template I want to render the "a" attribute of an instance of model B by using: {{ binstance.a }} but this seems to either render empty string or nothing at all. How do I render the str methdod of a foreign key within the template? -
django-money vs custom solution with minor currency
I'm just about to decide if I should use the django-money package or have my own solution, which allows me to work with minor currencies. I've read a lot that if you work with money you should always use minor currency or it's the better solution (I want to use stripe and I've seen that they are also handling the money in the minor currency). In order to get the minor unit I want to use this package (iso-4217). Does anyone have experience which solution is better? -
Django logger is mixing between levels: error and info
i'm trying to add logging to my django project here's my logger configuration: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s', }, }, 'handlers': { 'default': { 'class': 'logging.FileHandler', 'filename': os.path.join(*[BASE_DIR, 'logfiles', 'debug.log']), 'formatter': 'standard', }, 'apps_errors': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': os.path.join(*[BASE_DIR, 'logfiles', 'apps_errors.log']), 'formatter': 'standard', }, 'dev_logger': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': os.path.join(*[BASE_DIR, 'logfiles', 'apps_logs.log']), 'formatter': 'standard', }, }, 'loggers': { '': { 'handlers': ['default'], 'level': 'DEBUG', 'propagate': False, }, 'gui': { 'handlers': ['dev_logger', 'apps_errors'], 'propagate': True, }, 'crawler': { 'handlers': ['dev_logger', 'apps_errors'], 'propagate': True, }, }, } As you can see, I want to log everything to debug.log and log errors on apps (crawler and gui) to apps_errors.log and log info on apps (crawler and gui) to apps_logs.log debug.log and apps_errors.log are working normally, everything is being logged to debug.log and only errors in my 2 apps, are being logged to apps_errors.log, but when it comes to apps_logs.log i keep getting both errors and info when it should be only info by the way when i want to log something i'm doing import logging logger = logging.getLogger(__name__) for info i'm doing : logging.info(my_info) for errors i'm doing: … -
django {% get_current_language as LANGUAGE_CODE %} and session['_language'] are not equal until reload
In my app I can change the language by the following: from django.utils.translation import LANGUAGE_SESSION_KEY # LANGUAGE_SESSION_KEY is "_language" ... def my_view(request, my_lang=en): request.session[LANGUAGE_SESSION_KEY] = my_lang ... context = {"mysession": session} return render(request, "mytemplate.html", context) This works mostly as expected. However, the direct response of this view renders still in the previous language despite the session variable is set correctly. In other words the following template gives imho contradictory output: {% load i18n %} {% get_current_language as LANGUAGE_CODE %} <b>Debug:</b> current_language: {{ LANGUAGE_CODE }} session_variable: {{mysession|get:"_language"}} Note that, to access the attribute _language beginning with an underscore I have to use a custom filter, see this answer. Django-Output: Debug: current_language: en sessionvariable: de All {% trans ... } statements are handled to the (outdated) content of LANGUAGE_CODE, which is annoying. After changing the language the uses expects an immediate effect. If I refresh the page or load a different view, then the new language is used correctly. Do I understand something wrong? How can I achieve that the current_language is set correctly in the immediate response. -
Django Non-Managed Models - Querying from JSON file instead of Database
I want to have model that don't need to be created in database as table but use data from other sources like json files and other model objects. So I am using Non-Managed Model. This model is being created dynamically as described here in the docs Now Let me explain how I want to create the fields in this non-managed model. I have a json file that defines what fields should be in model, Let's call it contact-model.json. fields in this json file are mapped to django fields and dynamic model is created. This part is done. { 'model_name': 'Contact' 'fields': { 'name': 'CharField', 'email': 'EmailField' } } Now I have model that is storing all data related to above contact-model.json. Code for that model is given below class GenericAnswer(models.Model): answer = JSONField() model = CharField(default='Contact', max_length=30) And value of that asnwer would be { 'name': 'Adil Malik', 'email': 'sample@email.com' } What I want to do is that when I fetch Contact.objects.all(), It should return objects fetching from GenericAnswer based on model name, in this onctext, it is Contact. Can I do it. If Yes, Plese Explain How ???? -
Pythonanywhere:Access denied for user 'Ujwal97'@'10.0.04' (using password:YES) Django
I'm trying to deploy my django app on pythonanywhere by cloning from my github. When migrating, I'm getting access denied error followed by (using password:YES),here is the a screenshot of that, Error Image Thanks in advance !! -
How to write Mixin for queryset that returns only the data owned by the logged in user?
How to write a generic Mixin for CBV so that the queryset returns only the data owned by the logged in user? Is it possible in django? If it is...Can somebody give me specific suggestions or answer of how to perform this in django... Thank you -
Django, Hosting using Pycharm
I have to host a Django website onto the private server at my workplace. I'm using MySQL as the database (Through Wamp). The machine I'm using has Windows Server 10 installed on it. Is it advisable to use Pycharm's Deployment option? If so, What options and settings do i use? Is there any way i can map my IP address to a URL so that the users dont have to remember my IP Address? Is there any alternate/effective method that i could use? Also, I've disabled the IIS on the system so that i could use WAMP. {I faced a lot of issues downloading the database version that's compatible with all the files and WAMP was the easiest option i could find. It also comes with phpmyadmin, which helps as well. Also, Keep in mind that I'm still trying to figure everything about about Django and i dont know much} -
How to simplify multiple condition in an if clause?
I have written a code in Django like: phone = request.data.get("phone") password = request.data.get("password") age = request.data.get("age") name = request.data.get("name") if not phone or not password or not age or not name: #multiple not checks return Response({"status": False}) It takes multiple not checks, is here any way to write this in simpler way? -
Getting all of foreign key's fields
I have 3 models. One model is the User model, another is a Post model, and the other is a notifications model. I want to use Django's REST framework to show all of the notifications for the signed in user, plus each user that interacted with the signed in user. class Notification(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='actors') actor = models.ForeignKey(User, on_delete=models.CASCADE, related_name='users') post = models.ForeignKey(Post, on_delete=models.CASCADE, blank=True, null=True) type = models.ForeignKey(NotifType, on_delete=models.CASCADE) is_read = models.BooleanField() created_at = models.DateTimeField(auto_now_add=True) class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField(max_length=200) share_count = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) url = models.CharField(max_length=150) serializers.py class NotificationSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' views.py class GetNotifications(ListAPIView): serializer_class = NotificationSerializer def get_queryset(self): user = get_object_or_404(User, id=self.request.user.id) return User.objects.select_related().filter(users__user=user).order_by("-users__created_at") What I have currently returns all users who have interacted with the signed in user. However, it doesn't return the details about the notification. I want all details about each notification, including the details about the post. So the output should be something like this: { "post": { "id": 1, "status": "Hello!", . . . }, "user": { "username": "Ben", "avatar": "example.png" . . }, is_read: 1, created_at: 2017-07-21, type: 2 }