Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF - Nested Routers - Create/Update nested object on POST/PUT/PATCH
I'm currently starting a simple Task App and I'm using Django 2.0.7, DRF 3.8.2 and drf-nested-routes 0.90.2 I have these models : class Client(TimeStampedModel): """ This model describes a client for the railroader. It can be created by the manager in the back office We have at least one internal Client, which is Seelk, for internal projects """ name = models.CharField(max_length=255, unique=True) description = models.TextField(null=True) is_active = models.BooleanField(default=True) def __str__(self): return "{} : {}".format(self.name, self.description) class Project(TimeStampedModel): """ This model represents a project for a client, which we are gonna track actions on """ client = models.ForeignKey( 'railroader.Client', on_delete=models.PROTECT, related_name='projects') name = models.CharField(max_length=255, unique=True) description = models.TextField(null=True) is_active = models.BooleanField(default=True) def __str__(self): return "{} for client {}".format(self.name, self.client.name) So, following the documentation of drf-nested-routers, I set up my serializers like this : class ClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = ("id", "name", "description", "is_active", "projects") class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ("id", "name", "description", "is_active") And my viewsets like this : class ClientViewset(viewsets.ModelViewSet): serializer_class = ClientSerializer permission_classes = (permissions.IsAuthenticated, AccountPermission) def get_queryset(self): queryset = Client.objects.all() is_active = self.request.query_params.get("is_active") if is_active: queryset = queryset.filter(is_active=is_active) return queryset class ProjectViewset(viewsets.ModelViewSet): serializer_class = ProjectSerializer permission_classes = (permissions.IsAuthenticated, AccountPermission) def get_queryset(self): … -
django select_for_update continue after transaction
I have the following situation with transaction.atomic(): msgs = EmailMessage.objects.select_for_update().filter(...) ... # continue using msgs? for msg in msgs: ... Within the transaction.atomic I'd like to lock all msgs and perform some actions on them. when the transaction block is over, the select_for_update should not be applied anymore, but I still wanna continue using the msgs previously filtered. Is this the right way of achieving this? -
Am I able to classify models with folders on django admin dashboard?
I'm fresh of the django boat, working on a project that need to do 'one to many'. Here's what I'm trying to do: Patient001 Profile Record Stay Day1 Day2 Patient002 Profile Record Stay Day1 The "Patient", "Profile", "Record", "Stay" are all models and related with a foreign key "name" in "Patient" model. I hope to achieve to add or edit the data in each model by clicking in folders on django admin dashboard. How should I do this. I've been googling for days. What I found that looks like I'm looking for is a "custom django admin dashboard", but still not sure how to do this. Anyone has an ideia? =) -
Django-compressor: Enable BrotliCompressorFileStorage with offline compression mode
I'm using offline compression in conjunction with whitenoise on heroku and everything works fine before I overrode COMPRESS_STORAGE to enable broli compression as below: INSTALLED_APPS += ['compressor', ] STATICFILES_FINDERS += ['compressor.finders.CompressorFinder',] COMPRESS_STORAGE = 'compressor.storage.BrotliCompressorFileStorage' COMPRESS_ENABLED = env.bool('COMPRESS_ENABLED', default=True) COMPRESS_OFFLINE = env.bool('COMPRESS_OFFLINE', default=True) I have brolipy installed and added to requirements.txt. But django-compressor gives me this error message: module "compressor.storage" does not define a "BrotliCompressorFileStorage" attribute/class Any idea why? The spelling seems correct. I checked the source code, and there is indeed a class named BrotliCompressorFileStorage in the compressor.storage module. https://github.com/django-compressor/django-compressor/blob/develop/compressor/storage.py -
Unexpected directories and files while using collectstatic in django
This is my django project, there is two apps; polls and study This is the setting of my static file settings. STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,"study","static","HScard"), ) STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") I expected the 'python manage.py collectstatic' in the shell would copy static files to "staticfiles" from only in "study/static/HSCard"(due to STATICFILES_DIRS above). However, "collectstatic" copied unexpected files below. enter image description here Why are the files in admin and polls copied to staticfiles?? besides the files in admin folder were from here (a single example): Copying 'C:\ProgramData\Anaconda3\lib\site-packages\django\contrib\admin\static\admin\js\vendor\xregexp\xregexp.min.js' Why does 'collectstatic' working like this and how can I fix it as I expected? The version of django using is 2.0.7. Thank you. -
Uploading processed images on S3 in Django
Currently I'm uploading images in Django for a CMS application. Right now the code written does this. Gets the image uploaded. Saves it in the filesystem and the path is stored in the Postgres DB. The saved image is retrieved, processed (image gets a boundary & its attributes get printed on the boundary) Save the image again in the same name, replacing it in the filesystem. Now I want to deploy this on Heroku, so I'm storing images on Amazon S3. models.py def file_rename(instance, filename): ext = filename.split('.')[-1] count = Count.objects.get(pk=1) ZSN = "ZT-WJ-" + str(count.jeans_count + 1) filename = '{}.{}'.format(ZSN, ext) return os.path.join('images', filename) class Images(models.Model): design_id = models.CharField(max_length=128) file = models.ImageField(upload_to=file_rename) cost_price = models.FloatField() category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=False) fabric = models.ForeignKey(Fabric, on_delete=models.CASCADE, blank=False) manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE, blank=False) selling_price = models.FloatField() aliveness = models.IntegerField(default=1) date_added = models.DateTimeField(default=datetime.datetime.now) group = models.ForeignKey(Group, on_delete=models.CASCADE, blank=False) no_of_designs_or_colors = models.IntegerField(blank=False, null=True) catalogue_name = models.CharField(max_length=50, null=True, blank=True) visit_count = models.IntegerField(default=0) set_sizes = models.ForeignKey(Sizes, on_delete=models.CASCADE, blank=False) set_cat_id = models.IntegerField(default=1) brand = models.ForeignKey(Brand, on_delete=models.CASCADE, blank=False) colours = models.CharField(max_length=128, null=True, blank=True) def __unicode__(self): return unicode(self.design_id) In my views.py image.save() image2 = Image.open('media/' + str(image.file)) #Do all the pre-processing image2.save('media/' + str(image.file)) #Then transferring it to S3 … -
send PIL.Image to django server side and get it back
I don't know what's under the hood of sending an image from client side to server side, so stuck by the following scenario. I want to send a PIL.Image object to django server side using the Python requests lib and get it back in order to use the PIL.Image object on server side. As I have tested , if sent the PIL.Image object without any conversion , that is r = requests.post(SERVER_URL, data={ 'image': PILimage,#PILimage is of type PIL.Image 'wordPos':(86,23) }, ) then I just got a str object with value <PIL.PngImagePlugin.PngImageFile image mode=RGB size=149x49 at 0x13F25D0> on server side, I guess it was caused by requests, which converted the PIL.Image object to a str object before sending, so why requestsdo the conversion ? why cannot we send the PIL.Image object without any conversion over the Internet ? please give some explanation here, thanks! Someone told me I could convert the PIL.Image object to bytes form then do the sending , that is r = requests.post(SERVER_URL, data={ 'image': PILimage.tobytes(),#PILimage is of type PIL.Image 'wordPos':(86,23) }, ) but then how to get the image back to PIL.Image object on server side? It seems PIL.Image.frombytes() won't help. -
How to get data from two models in Django
I have been trying to use with the a legacy database. I have created models file using inscpectdb but now I am not able to perform joins on the table. I have two tables job_info and username_userid. Here is my models.class file: class UseridUsername(models.Model): userid = models.IntegerField(blank=True, null=True) username = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'userid_username' class LinuxJobTable(models.Model): job_db_inx = models.AutoField(primary_key=True) mod_time = models.IntegerField() account = models.TextField(blank=True, null=True) exit_code = models.IntegerField() job_name = models.TextField() id_job = models.IntegerField() id_user = models.IntegerField() class Meta: managed = False db_table = 'linux_job_table' Now how can I get all the values from LinuxJobTable and username from UseridUsername for the corresponding user. -
Having trouble with local variables, needing to reference a variable as global within a function but I know it's not good practice
I am getting json data from a web page and then storing it. My code works 100% fine except when I try to increase number of errors. When I remove the number_of_errors += 1 everything is dealt with effectively so I am pretty sure my issue is just down to global and local variables. My code structure is as follows: def scrape(): try: # too much code here to post but this just scrapes data store() except json.decoder.JSONDecodeError: number_of_errors += 1 def store(): # too much code here to post but this just stores data def scrape_and_store(): number_of_errors = 0 while number_of_errors < 10: scrape() store() With this code structure I get: UnboundLocalError: local variable 'number_of_errors' referenced before assignment so I had an idea to add in global number_of_errors: except json.decoder.JSONDecodeError global number_of_errors number_of_errors += 1 But as far as I am aware this is poor form and can get me into trouble. What is the best way to deal with this variable? I can't declare it in either scrape() or store() because then it will just reset each loop of the while statement, won't it? -
django_session table doesn't created when django test
my INSTALLED_APPS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myproject_app', ] when i create features, it works fine everything and I want make test code class TestItemList(TestCase): def setUp(self): self.user = User.objects.create(username='test', password='test123') self.client.login(username='test', password='test123') def test_access_url(self): response = self.client.get(reverse('item-list')) self.assertEqual(response.status_code, 200) when i run test command it raise django.db.utils.ProgrammingError $ python manage.py test _mysql.connection.query(self, query) django.db.utils.ProgrammingError: (1146, "Table 'test_myproject.django_session' doesn't exist") i try run command one more $ python manage.py makemigrations $ python manage.py migrate when I check development database.. and my django test database(python manage.py test) tables doesn't created not only django-session but also admin, contenttypes,,,, else please somebody tell me some advice? thank you -
How to connect Django Rest-api with MongoDB?
I'm trying to connect Django rest-api with mongo database which i created on . Below is my code which I define in settings.py file in my Django rest-api. MONGODB_DATABASES = { 'default': { 'NAME': 'dummy', 'HOST': os.environ.get('MONGO_HOST', 'mongodb://dummyuser:dummypassword@ds125851.mlab.com:25851/dummy'), } } mongoengine.connection( db='dummy', host=os.environ.get('MONGO_HOST', 'mongodb://dummyuser:dummypassword@ds125851.mlab.com:25851/dummy'), ) When I run this api I got this error host=os.environ.get('MONGO_HOST', 'mongodb://dummyuser:dummypassword@ds125851.mlab.com :25851/dummy'), typeError: 'module' object is not callable I try to search for solutions online but I found examples which were for older versions. I'm using Djangorestframework2.0.7, MongoDB3.4 and mongoengine0.15. I did not find any answer for this versions. I try to connect this api to local database and I got same error. Please share the connection code if you know the answer -
django admin site change form fields
I am new to django. I am going to create a change form in admin site for users. MyUser: class MyUser(AbstractUser): """ The customized user model for the project It has one-to-one relations to Profile. """ profile = models.OneToOneField(Profile, null=True, on_delete=models.PROTECT) profile: class Profile(models.Model): """User profile model, specifying the user's general preferences and language""" GENDERS = ( ('male', _('Male')), ('female', _('Female')), ) TYPICAL_USAGES = ( ('personal', _('Personal')), ('academic', _('Academic')), ('business', _('Business')), ) gender = models.CharField(_("gender"), max_length=10, choices=GENDERS) # We use full_name instead of the default 'first_name' and 'last_name', to enable non-personal users full_name = models.CharField(_("full name"), max_length=60) # A valid two-letter language code which is used when the user is logged in language = models.CharField(_("language"), max_length=2, choices=settings.LANGUAGES, blank=True) typical_usage = models.CharField(_("typical usage"), max_length=10, choices=TYPICAL_USAGES) country = models.ForeignKey(Country, on_delete=models.PROTECT, verbose_name=_("country"), blank=True, null=True) province = models.ForeignKey(Province, on_delete=models.PROTECT, verbose_name=_("province"), blank=True, null=True) city = models.ForeignKey(City, on_delete=models.PROTECT, verbose_name=_("city"), blank=True, null=True) is_subscribed = models.BooleanField(_("newsletter subscription"), default=True) my current admin.py: class MyUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = MyUser class MyUserChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): model = MyUser class MyUserAdmin(UserAdmin): form = MyUserChangeForm add_form = MyUserCreationForm def has_add_permission(self, request): return False admin.site.register(MyUser, MyUserAdmin) Now I want the change_form contain all fields of profile and some fields of MyUser (exclude firstname, lastname … -
Django, Keys, AutoMailing and Session management
Here's a link to what my project files look like This is what my models.py looks like ` from django.db import models # Create your models here. class Bugs(models.Model): STATUS_CHOICE = ( ('Unassigned', 'Unassigned'), ('Assigned', 'Assigned'), ('Testing', 'Testing'), ('Tested', 'tested'), ('Fixed', 'Fixed') ) STATUS_CHOICE_1 = ( ('Bug', 'Bug'), ('Issue', 'Issue'), ('Enhancement', 'Enhancement'), ('Not an issue or bug', 'Not an issue or bug'), ('Fixed', 'Fixed') ) Project_Name = models.CharField(max_length=100) Situation_Type = models.CharField(max_length=25, choices=STATUS_CHOICE_1) Basic_Description = models.CharField(max_length=100) Detailed_Description = models.TextField(default='The Description, here.') Status = models.CharField(max_length=18, choices=STATUS_CHOICE) Assigned_to = models.CharField(max_length=100) Assigned_to_Mail_ID = models.CharField(max_length=50, blank=True, null=True) Reported_by = models.CharField(max_length=50, blank=True, null=True) Reporters_Mail_ID = models.CharField(max_length=50, blank=True, null=True) Reported_Date = models.DateTimeField(null=True, blank=True) Created = models.DateTimeField(auto_now_add=True, null=True, blank=True) Updated = models.DateTimeField(auto_now=True, null=True, blank=True) Deadline_Date = models.DateTimeField(null=True, blank=True) Supporting_Documents_By_Reporter = models.FileField(null=True, blank=True) Project_Managers_Comment = models.TextField(default='The Description, here.') Supporting_Documents_by_Project_Manager = models.FileField(null=True, blank=True) Technicians_Comment = models.TextField(default='The Description, here.') Supporting_Documents_by_Technician = models.FileField(null=True, blank=True) Testers_Comment = models.TextField(default='The Description, here.') Supporting_Documents_by_Tester = models.FileField(null=True, blank=True) def __str__(self): return self.Project_Name + ' (' + self.Situation_Type + ') ' + ' [' + self.Status + '] ' class Meta: verbose_name_plural = "Project Issues" # Create your models here. class Projects(models.Model): STATUS_CHOICE = ( ('Project Manager', 'Project Manager'), ('Technician', 'Technician'), ('Tester', 'Tester') ) STATUS_CHOICE_1 = ( ('Work … -
I am getting this error rest_framework.request.WrappedAttributeError
I am trying to upgrade my django 1.9 to django 2.0. It is working fine for GET() but I am getting error in POST(). My views.py is:- class AccountInfoUpdate(APIView): authentication_classes = [IsAuthenticated] def post(self, request): user = request.user user_profile = UserProfile.objects.get(user=user) name = False contact = False if "name" in request.data: user_profile.name = request.data.get('name') user_profile.save() name = True if "contact" in request.data: user_profile.contact = request.data.get('contact') user_profile.save() contact = True if user_profile.affiliate_code is not None and (name or contact): result = service.update_affiliate(user_profile.affiliate_code, name=user_profile.name, contact=user_profile.contact) return Response({'Message': 'Account info updated successfully!'}) I am getting this error:- user_auth_tuple = authenticator.authenticate(self) rest_framework.request.WrappedAttributeError: 'IsAuthenticated' object has no attribute 'authenticate' -
Print all user's followers
I'm trying to print all the followers the person that owns a profile page has. Here is my following table that shows the following relationship: class Following(models.Model): target = models.ForeignKey('User', related_name='followers', on_delete=models.CASCADE, null=True) follower = models.ForeignKey('User', related_name='targets', on_delete=models.CASCADE, null=True) def __str__(self): return '{} is followed by {}'.format(self.target, self.follower) I am also using Django's auth User model. views.py class FollowersView(DetailView): model = User slug_field = 'username' template_name = 'profile/followers.html' def get_profile_followers(user): return user.followers.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["follower_list"] = get_profile_followers(self.object) # self.object is user profile return context In the template, I am doing this: {% for follower in follower_list %} <h1>{{ follower }}</h1> {% endfor %} But, I get this instead: Chris is followed by John. This is correct, Chris is followed by John, however, I want to display only John's user and John's attributes like avatar, follower_count, etc. that are fields in the User table. How can I do this? -
I'm in djangoblog/views.py and i want to access the home.html file in the templates folder from the root directory. How do i do that?
https://openload.co/f/037QO8ws7OM/ss_django.png I've tried writing html in the home.html but nothing renders. In my djangoblog/views.py file i have: def home(request): return render(request, 'home.html') and in my home.html: {% extends 'base_layout.html' %} which adds the header and the footer. However, whenever i try to add something beneath that template tag nothing ever shows. Any help is much appreciated. -
coroutines and Django clickjacking middleware
I am trying to use the aiohttp library with Django. I have followed the tutorial but get the following error defining one of my view methods as async. Traceback (most recent call last): File "/Users/.../lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/.../lib/python3.6/site-packages/django/utils/deprecation.py", line 97, in __call__ response = self.process_response(request, response) File "/Users/.../lib/python3.6/site-packages/django/middleware/clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'coroutine' object has no attribute 'get' The minimal working example I have of this is as follows: async def conversion_form_process(request): if request.method == 'POST': form = ConversionForm(request.POST) # check whether it's valid: if form.is_valid(): return HttpResponseRedirect('/thanks/') else: form = ConversionForm() return render(request, 'mainpage.html', {'form': form}) This suggests that it has to do with the async keyword but I don't know how to fix it. Any help is much appreciated. Thanks! -
Django & Javascript: Passing additional variable for file upload
Alright, guys. I'm stumped. I'm following this blog on uploading a file. I trying to modify it so that I can have my file model have a foreign key on another model. The pop up module works, but submitting it does not. I keep getting a 'anothermodel_id field is required' error when the file is submitted and so I need to pass in the field to my form, but I'm not sure how. I see the javascript line function (e, data) and I imagine that I need to add the variable here, but I can't seem to do it. I don't know where data is defined. Model class File(models.Model): anothermodel_id = models.ForeignKey(anothermodel) file = models.FileField(upload_to=upload_product_file_loc) Form class FileForm(forms.ModelForm): class Meta: model = File exclude = () views.py class FileUploadView(View): def get(self, request): files = File.objects.all() return render(self.request, 'anothermodel/files.html', {'files': files, 'anothermodel_id': 'rb6o9mpsco'}) def post(self, request): form =FileForm(self.request.POST, self.request.FILES) print(form.errors) if form.is_valid(): photo = form.save() data = {'is_valid': True, 'url': photo.file.url} else: print('we are not valid') data = {'is_valid': False} return JsonResponse(data) html <div style="margin-bottom: 20px;"> <button type="button" class="btn btn-primary js-upload-photos"> <span class="glyphicon glyphicon-cloud-upload"></span> Upload photos </button> <input id="fileupload" type="file" name="file" multiple style="display: none;" data-url="{% url 'anothermodel:file-upload' %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token … -
gunicorn.service: Failed with result 'exit-code'.
I'm following this tutorial How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 16.04 When I run sudo systemctl status gunicorn I get: ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2018-07-16 03:21:34 UTC; 1min 25s ago Main PID: 25829 (code=exited, status=203/EXEC) Jul 16 03:21:34 ubuntu-s-1vcpu-2gb-nyc1-01 systemd[1]: Started gunicorn daemon. Jul 16 03:21:34 ubuntu-s-1vcpu-2gb-nyc1-01 systemd[1]: gunicorn.service: Main process exited, code=exited, status=203/EXEC Jul 16 03:21:34 ubuntu-s-1vcpu-2gb-nyc1-01 systemd[1]: gunicorn.service: Unit entered failed state. Jul 16 03:21:34 ubuntu-s-1vcpu-2gb-nyc1-01 systemd[1]: gunicorn.service: Failed with result 'exit-code'. Here is my File: /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=myusername Group=www-data WorkingDirectory=/home/www/myproject ExecStart=/home/www/myproject/django_env/bin/gunicorn --access-logfile - --workers 3 --pythonpath '/home/www/myproject/myproject' --bind unix:/home/www/myproject$ [Install] WantedBy=multi-user.target Any friend can help? -
when i try to pass parameters from url to views by regex in django=1.9,i got this error,i dont know why
i want to pass parameters to my app.views with regex,but i got the fellow error. my regex is "^(?Pd+)",which means to pass the passed one or more digits as parameters to the detail in the views as parameters, where ?P defines the name used to identify the matching content. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/root/ENV3.5/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/root/ENV3.5/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "/root/ENV3.5/lib/python3.5/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/root/ENV3.5/lib/python3.5/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/root/ENV3.5/lib/python3.5/site-packages/django/core/checks/urls.py", line 10, in check_url_config return check_resolver(resolver) File "/root/ENV3.5/lib/python3.5/site-packages/django/core/checks/urls.py", line 27, in check_resolver warnings.extend(check_pattern_startswith_slash(pattern)) File "/root/ENV3.5/lib/python3.5/site-packages/django/core/checks/urls.py", line 63, in check_pattern_startswith_slash regex_pattern = pattern.regex.pattern File "/root/ENV3.5/lib/python3.5/site-packages/django/core/urlresolvers.py", line 203, in regex (regex, six.text_type(e))) django.core.exceptions.ImproperlyConfigured: "^(?Pd+)/$" is not a valid regular expression: unknown extension ?Pd at position 2 -
How can i send parameters from one template to another template/view in django?
Ok, so i have in my views.py these functions def main(request): if request.method == 'POST': return newFunction(request) return render(request,'user/main.html') def newFunction(request): num = request.POST["number"] let = request.POST["letter"] context = {'num':num,'let':let} return render(request,'user/test.html',{'c':context}) And that main.html looks like this {%extends 'base/base.html'%} {%block title%}Main{%endblock%} {%block content%} <form method="post"> {%csrf_token%} <input type="text" name="number"> <input type="text" name="letter"> <button type="submit">Save</button> </form> {%endblock%} The urls.py path('index/',main,name='main'), path('test/',newFunction,name='test'), As you can see, i enter the main.html page and a form appears, asking me for a number and a letter. I enter these 2 inputs and when clicking the submit, it redirects me to another html and show me the letter and number. The problem is that the url still shows user/index.html, not user/test.html How can i do this? i want to basically click the submit and send all the values to another template but changing the url in the process. -
Django allauth's social login not working after adding domain
Recently i tested the app on a live server with heroku. my site has a name example.com has a .herokuapp.com attached. Everything was working fine with the social login i had no issues at all. Now that i bought a domain and changed all of my social login callback url to the new example.com i got a "example.com refused to connect error" and even the admin had no site query matching does not exist when i go directly to /admin. How is it that everything worked fine at example.com.herokuapp.com but just because i switched to example.com everything related to social auth failed? I am still able to login on the site and then access the admin but i really want the social auth. It is about 13hrs since i switched domain name -
Generate a random word from list of words in back end and display it on front end
I am new to Django and trying to learn more in detail. Currently working on a problem where I need to generate a random word from a pool of words and display it in the front end web page. I am able to generate the random word using python but wondering how to display the random word in the front end. Could you share some thoughts on this if you have encountered this. Any help would be appreciated. Thank you. -
Gunicorn cannot find system Renviron error
I have been struggling with this for days, reaching my limit. I am porting a Django project from using mod_wsgi/httpd to use gunicorn/nginx I have set up a virtual environment using virtualenv/virtualenvwrapper and pip installed the requirements file into it, as well a gunicorn. The django project is a very complex site with lots of dependencies. When I start the app using `python manage.py runserver` everything runs fine with no errors. However when I try to start with gunicorn `gunicorn wsgi` I get this error ``` cannot find system Renviron Fatal error: unable to open base package ``` I don't even know where to start troubleshooting this. I have added .Renviron files to my user directory, added os.environ["Renviron"]=/path to both the wsgi.py and settings.py files, downgraded RPy2 back to 2.5.6. Nothing seems to help. I don't know what else to do. Any help would be much appreciated. Here is my set up: MacOS High Sierra (10.13.5) running in Parallels Desktop Lite 1.3.3 VM Django==1.9.2 gunicorn=19.9.0 gevent==1.3.4 greenlet==0.4.13 whitenoise==3.3.1 rpy2==2.5.6 Homebrew==1.6.17 R=3.5.1 Django wsgi.py file """ WSGI config for ri project. """ import os, sys, socket, site dev_path = "/Users/evans/.virtualenvs/base_env/" os.environ["R_HOME"]='/usr/local/lib/R/etc/Renviron' os.environ["Renviron"]='/usr/local/lib/R/etc/Renviron' host = socket.gethostname() print "HOST: ",host site.addsitedir(dev_path+'lib/python2.7/site-packages') # Activate … -
Installation of mysqlclient python library on mac high sierra doesn't work
I tried all the solutions proposed by other Stack Overflow questions related to the title, but my problem seems to be a bit more specific. The error that is displayed when I try to install mysqlclient is this one: Error message and code executed before it was displayed This is the code version of the error displayed: Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error Complete output from command /Users/mymac/Documents/chatbot_web_project/virtualenv/bin/python3 -u -c "import setuptools, tokenize;__file__='/private/var/folders/v0/64wkf9q11kn9lg6w1fbcw_dw0000gn/T/pip-install-da0w8w2v/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 /private/var/folders/v0/64wkf9q11kn9lg6w1fbcw_dw0000gn/T/pip-record-wirofbuy/install-record.txt --single-version-externally-managed --compile --install-headers /Users/mymac/Documents/chatbot_web_project/virtualenv/include/site/python3.6/mysqlclient: running install running build running build_py creating build creating build/lib.macosx-10.6-intel-3.6 copying _mysql_exceptions.py -> build/lib.macosx-10.6-intel-3.6 creating build/lib.macosx-10.6-intel-3.6/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb copying MySQLdb/compat.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb creating build/lib.macosx-10.6-intel-3.6/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.macosx-10.6-intel-3.6 /usr/bin/clang -fno-strict-aliasing -Wsign-compare -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -arch i386 -arch x86_64 -g -Dversion_info=(1,3,13,'final',0) -D__version__=1.3.13 -I/usr/local/Cellar/mysql/8.0.11/include/mysql -I/Users/mymac/Documents/chatbot_web_project/virtualenv/include -I/Library/Frameworks/Python.framework/Versions/3.6/include/python3.6m -c _mysql.c -o …