Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add Aldryn Google Analytics to Django CMS
I currently have a django cms website and will like to have google analytics installed, using the aldryn-google-analytics plugin. I don't have a Divio Cloud account, and I'm really new to python. May I seek your advice on the GitHub files to be added to my project please and where the files should be placed into project. -
filter dataset not having a value
Suppose i have a schema like below : Book | Author ------------- B1 | A1 B1 | A3 B1 | A2 B2 | A5 B2 | A4 B2 | A3 B3 | A5 B3 | A6 B3 | A1 B4 | A1 B4 | A5 B4 | A6 and i want to filter out all those book whose author is not A1 (B2 in this case) This is simple SQL using group by and not having clause, what i am having tough time is getting it done usinng django queryset and annotate. Most of the annotate work around count which i am not able to fit in this particular case. any pointers is helpful, thanks! :) -
Access friendlist without taggable_friends permission in Facebook Graph API
I am trying to access the list of friends from facebook that I can display on the Django application made by me. I knoww that there is one permission required called taggable_friends but after reviewing facebook is granting it to me and giving very weird reasons that they found no login button on my application. Even though I have it they still deny. Well, my question is : Does anyone know what can be other way around for getting the facebook friends using the graph API apart from the taggable-friends. Please do not suggest me the read_custom_friendlist and user_friends, as I have checked it and tried to. It gives nothing. Kindly help me. I am using Facebook Graph API v2.10 -
Why the css file can not be found in Django template?
I have created a project in Django. Also, I am using django-allauth for sign up and login. In order to use my own templates with django-allauth, I have created a html file called signup.html in a folder called account inside a folder called templates which is outside of of all my apps (/templates/account/signup.html). That works. I tried to use some custom css file inside signup.html: <link rel="stylesheet" href="/templates/account/signup.css"> It says that the file can not be found. Though, it is located in templates/account. -
Django Rest Framework error: {"user":["This field is required."]
When posting this: curl -X POST -H "Authorization: Token sometoken" -d "url=someurl" 127.0.0.1:8000/create/ I get the error: {"user":["This field is required."] with the ItemSerializer, I have seen other posts on SO talking about using perform_create, which I am trying to use to save the user object, but it doesn´t work for some reason. Perform_create works when user is defined like this: user = serializers.CharField( default=serializers.CurrentUserDefault() ) But I want to use the user object, not only CharField storing the username Serializers: class UserDetailsSerializer(serializers.ModelSerializer): class Meta: model = UserModel fields = ('pk', 'username', 'email', 'first_name', 'last_name') read_only_fields = ('email', ) class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ['cat'] class CommentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Comment fields = [ 'comment', ] class ItemSerializer(serializers.HyperlinkedModelSerializer): user = UserDetailsSerializer() category = CategorySerializer(many=True) thecomments = CommentSerializer(many=True) timestamp = serializers.SerializerMethodField('get_mytimestamp') def get_mytimestamp(self, obj): return time.mktime(datetime.datetime.now().timetuple()) class Meta: model = Item fields = [ "url", "user", "timestamp", "categories", "thecomments", ] Model: class Item(models.Model): url = models.CharField(max_length=1000) user = models.ForeignKey('auth.User', unique=False) timestamp = models.DateTimeField(auto_now_add=True) url = models.CharField(max_length=1000) categories = models.ManyToManyField(Category) View: class ItemCreateAPIView(generics.CreateAPIView): serializer_class = ItemSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) -
CronJob, django and environment variables
I have built an application for django on Openshift v3 PRO with the django-ex template. It works great. I'm using POSTGRESQL with persistent storage. I need a scheduled cron job to fire every hour to run some django management commands. I'm using the CronJob pod for this. My problem is this: I need to create the CronJob job with the same environment variables that the django pod was created with (DATABASE_, DJANGO_, and others), but don't see an easy way to do this. Any help would appreciate it. -
join two queries together as one - django
I am working on a django project and I want to basically create one query out of two queries that I was creating. I have a friends table that has the following columns user - friend - status - create ------------------------------- josh - omar - 1 - 1 steve - omar - 1 - 1 omar - tava - 1 - 1 I would create one query to grab records where the user is omar and another one to grab records where the friend is omar. is there a way to create a query that would combine the two queries like Grab all the records where omar is a friend or user and set them as one queryset object. -
Modify value of a Django form field during clean() and validate again
I want to do something like this: def clean(self): cleaned_data = self.cleaned_data self.data['cpf'] = re.sub("[\.-]", "", self.data['cpf']) clean_data_again_to_revalidate_the_field I want to change the field CPF to remove dots. After, I want to validate the field again. Is it possible? Also, the self.data['cpf'] receiving the value is not possible. it is failing with: This QueryDict instance is immutable. -
heroku django app no module named site
I'm trying to deploy my Django app to heroku, but I keep receiving an enigmatic 'ModuleNotFoundError: No Module Named lukasSite' -- lukasSite is the name of the website I'm working on. It's also the name of my project folder, and app, though I have some other folders named 'community.' I can't tell where this error is coming from, but I get it both when I try to run heroku local web and try to deploy my website to Heroku. Full error below: [OKAY] Loaded ENV .env File as KEY=VALUE Format 21:33:09 web.1 | [2017-10-19 21:33:09 -0500] [18983] [INFO] Starting gunicorn 19.7.1 21:33:09 web.1 | [2017-10-19 21:33:09 -0500] [18983] [INFO] Listening at: http://0.0.0.0:5000 (18983) 21:33:09 web.1 | [2017-10-19 21:33:09 -0500] [18983] [INFO] Using worker: sync 21:33:09 web.1 | [2017-10-19 21:33:09 -0500] [18986] [INFO] Booting worker with pid: 18986 21:33:09 web.1 | [2017-10-20 02:33:09 +0000] [18986] [ERROR] Exception in worker process 21:33:09 web.1 | Traceback (most recent call last): 21:33:09 web.1 | File "/Users/lukasudstuen/softwareProjects/lukassite/env/lib/python3.6/site-packages/gunicorn/arbiter.py", line 578, in spawn_worker 21:33:09 web.1 | worker.init_process() 21:33:09 web.1 | File "/Users/lukasudstuen/softwareProjects/lukassite/env/lib/python3.6/site-packages/gunicorn/workers/base.py", line 126, in init_process 21:33:09 web.1 | self.load_wsgi() 21:33:09 web.1 | File "/Users/lukasudstuen/softwareProjects/lukassite/env/lib/python3.6/site-packages/gunicorn/workers/base.py", line 135, in load_wsgi 21:33:09 web.1 | self.wsgi = self.app.wsgi() 21:33:09 web.1 … -
How to read a file upload from the webpage by django?
This is the first time I develop a website project, and I don't have any experience in frontend and backend before. I've read Django's official tutorial and get some intuition about it, but I have to say frontend is such a horrible thing, I don't have time to learn it carefully because I have to finish the task before the end of this week. Here comes the problem. I have to read a file upload by any user from the webpage, the HTML code was written by other people in the lab like follow: <label>select a file &nbsp;&nbsp;&nbsp;&nbsp; <input id="photoCover" class="input-large" type="text" style="height:30px;"> <button class="btn1 btn-primary" onclick="$('input[id=lefile]').click();"><i class="fa fa-folder-open"></i>&nbsp;&nbsp;浏览&nbsp;&nbsp;&nbsp;&nbsp;</button> </label> I want to know how to process the file selected in the Django views. Here are my thoughts: 1.The selected file must be in some directory on the local machine, maybe I should directly get the path of that file. 2.Should I create a form to handle this problem? Is there anybody could give me a hand or some hints about how to solve this problem? any other resource is appreciated. -
Many foreign keys in a model, better way to do models?
I'm kind of new to django. While writing the models for an app I'm doing, I felt like I was doing something wrong because of all the foreign keys I was using for a single model (ticket model to be specific) My thinking at the beginning was that I wanted each Ticket to keep the information on it's creator, what team this ticket is assigned to and the comments made on the ticket. And other information that don't need foreign keys. Am I doing this right ? I dont know why, but I feel like there is a better way. class Team(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=2000) members = models.ManyToManyField(User, through='Team_members') def __str__(self): return self.name class Ticket(models.Model): name = models.CharField(max_length=200) creator = models.ForeignKey(User, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) comments = models.ForeignKey(Comment, on_delete=models.CASCADE) #worker = models.ForeignKey(User, on_delete=models.CASCADE) *to be finished description = models.CharField(max_length=500) status = models.BooleanField(default=False) date_opened = models.DateTimeField('date opened') date_closed = models.DateTimeField('date closed',null=True, blank=True) def __str__(self): return self.name class Team_member: team = models.ForeignKey(Team) user = models.ForeignKey(User) date = models.DateTimeField('date joined') class Comment: text = models.CharField(max_length=2000) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.text -
Target WSGI script wsgi.py' cannot be loaded as Python module
I'm trying to scale my django project with AWS ElasticBeanstalk but i get an error, the error doesn´t appear when I deploy the proyect, but when I scale it I get this error: ValueError: Unable to configure handler 'file_log': [Errno 13] Permission denied: '/var/log/meatme/django.log' mod_wsgi (pid=4829): Target WSGI script '/opt/python/current/app/meatme/meatme/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=4829): Exception occurred processing WSGI script '/opt/python/current/app/meatme/meatme/wsgi.py'. Traceback (most recent call last): File "/opt/python/current/app/meatme/meatme/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/opt/python/run/venv/lib/python2.7/site- packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/opt/python/run/venv/lib/python2.7/site-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/opt/python/run/venv/lib/python2.7/site- packages/django/utils/log.py", line 75, in configure_logging logging_config_func(logging_settings) File "/usr/lib64/python2.7/logging/config.py", line 794, in dictConfig dictConfigClass(config).configure() File "/usr/lib64/python2.7/logging/config.py", line 576, in configure '%r: %s' % (name, e)) I have this config files .ebextensions: commands: 00_create_dir: command: mkdir -p /var/log/meatme 01_change_permissions: command: chmod g+s /var/log/meatme 02_change_owner: command: chown -R wsgi:wsgi /var/log/meatme and wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "meatme.settings") application = get_wsgi_application() When I do eb deploy it works perfect, but when i do eb clone 2 (to test scale) the new instance dont work. -
class: forms-control is not showing
I'm doing a Django App using Materialize. I am doing an app using ModelForms with form-control. When I run the app, the inputs don't appear. Everything works fine, just the input is not appearing. As you may see, the name of the fields are in Spanish (ignore that). forms.py: class UsuariosForm(forms.ModelForm): class Meta: model = Usuarios fields = ('Nombre', 'Apaterno', 'Amaterno', 'Telefono', 'Email', 'Passwd',) views.py: def user_create(request): context = {} NewUsuariosForm = UsuariosForm() # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request NewUsuariosForm = UsuariosForm(request.POST) UserValid = NewUsuariosForm.is_valid() # check whether it's valid if UserValid: Usu = NewUsuariosForm.save(commit=False) Usu.Activo = True ID = Usuarios.objects.count() + 1 Usu.Usuarioid = ID Usu.save() return user_lists(request) context = { 'NewUsuariosFrom': NewUsuariosForm } return render(request, 'Usuarios/usuarios_form.html', context) # if a GET (or any other method) we'll create a blank form return render(request, 'Usuarios/usuarios_form.html', context) usuarios_form.html {% extends 'base.html' %} {% load widget_tweaks %} {% block content %} <div class="container"> <br> <h3 class="center pink-text"> Usuarios - Crear Usuario </h3> <br> <br> <br> <form method="post"> {% csrf_token %} <div class="form-group"> <div class="row"> <label for="Nombre"> Nombre: … -
about IDE, on clonning a github repository. issue: i require a "commit diff" to be cloned instead of the final project
I will explain my own problem so it is easier to understand. I have several books of Django, currently on Django Unleashed by Andrew Pinkham. On the sample project files you have this straightforward project https://github.com/jambonrose/DjangoUnleashed-1.8/ I managed to fork it to my github and clone it on Pycharm professional IDE through its VCS/checkout from version control/github, so I can do certain stuff like right click stuff and see where it leads to within the project etc... The issue I am finding, however is that when reading through the book as the code develops in each chapter, this code isn't saved in the whole parent branch divided by episodes, but it is instead saved as diff commmits, or steps of the process towards the final github project I, for example can link to certain commits as dju.link/a30e354253/organizer/views.py but when I fork this to my account, only the final project which is up gets to my profile and ends up being cloned. For example this final link to a commit I just put leads to a folder called blob which doesn't even exist when i look at the project ....github.com/jambonrose/DjangoUnleashed-1.8/blob/a30e354253/organizer/views.py While a search for blob or a30e354253 on jambonrose's project wont … -
Form not saving object a redirect to new form view
I am attempting to build an app the creates patient data, saves it, and displays it. Problem : When I populate the fields and click save it does not save the object and render data to the document object model. It reloads the page with the field data still in the fields. I am not sure what I have done wrong. The view, form and models code seem to be accurate. I welcome any useful assistance. Here is the code : models.py from django.db import models from django.contrib.auth.models import User from Identity import settings import datetime class Identity_unique(models.Model): NIS = models.CharField(max_length = 200, primary_key = True) user = models.ForeignKey(settings.AUTH_USER_MODEL) Timestamp = models.DateTimeField(auto_now = True) first_Name = models.CharField(max_length = 80, null = True ) last_Name = models.CharField(max_length = 80, null = True ) location = models.CharField(max_length = 100, blank = True) date_of_birth = models.DateField(auto_now = False, auto_now_add = False, blank = True, null = True) contact = models.CharField(max_length = 15, null = True) views.py from django.shortcuts import render, redirect from django.views.generic import TemplateView, UpdateView from nesting.forms import Identity_Form, Symptom_Form from nesting.models import Identity_unique, Symptom_relation class Identity_view(TemplateView): template_name = 'nesting/nesting.html' def get(self, request): form = Identity_Form() Identities = Identity_unique.objects.filter(user = request.user) var … -
django-filters {{ field.label_tag }} not displaying but {{ field }} is
So I'm having a weird issue with Django-filters. I got them working a previous time but now they just aren't. I'm trying to split the fields in a for loop so I can have more control over the CSS of the label_tag. However, the label_tag isn't showing up. But the field itself is. I have absolutely no idea why. Perhaps somebody has some insight? filters.py from django.contrib.auth.models import User from django import forms from .models import Post, Comment, UserProfile, Question, Answer from university.models import University import django_filters class ClassFilter(django_filters.FilterSet): title = django_filters.CharFilter( lookup_expr='icontains', widget=forms.TextInput(attrs={ 'class': 'home_page_search', 'placeholder': 'Search by Class or University', 'id': 'list_of_post_search_box_id', 'autocomplete': 'off', }), ) university = django_filters.ModelChoiceFilter( queryset=University.objects.all(), widget=forms.RadioSelect(attrs={'class': 'list_of_class_university_filter_btn_input'}), empty_label=None ) class Meta: model = Post fields = ['title', 'university',] template {% for university in filter.form.university %} {{ university.tag }} # This is showing up fine {{ university }} # Showing up as well, I see my label tags perfectly {{ university.label_tag }} # Not showing up {{ university.label }} # Not showing up either {% endfor %} -
A lightweight django cart app
What's an up to date cart app for django that isn't years old and isn't a full blown framework? There seems to be no middle ground between something like oscar which I definitely don't need or something like satchless which I have no idea how to even start using. All I need is a cart app I plug in and I can process payments using django-payments. Essentially I just want to have a cart I can display on my site, which isn't really e-commerce, but users can create items they pay for and add them to a cart. So, the cart needs to be able to handle different model types and store the current items in the cart with the ability to remove them. I don't know how to roll my own solution for this. Hence, my question. -
Django weasyprint HTML to PDF convert is working very slow
I am covering HTML to PDF file using weasyprint in Django web app. Everything is working fine but It is working is very slow when converting HTML to PDF. It takes more than two minutes long When I convert it. I am using Bangla font in my HTML file. this is my views.py code def get_pdf_file(request, customer_id, sys_type): sys_type = customer_id area = "pdf" site_credit = site_credit1 time_now = timezone.now() customers = get_object_or_404(CustomerInfo, pk=customer_id) due_taka_track = customers.duetaka_set.all() if due_taka_track == None: due_taka_track = 0 unpaid_taka = int(customers.customer_price - customers.customer_due_taka_info) due_taka_track = customers.duetaka_set.all() sum_cost_taka = due_taka_track.aggregate( sp=Sum('customer_due')).get('sp', 0) if sum_cost_taka == None: sum_cost_taka = 0 total_paid_taka = sum_cost_taka + customers.customer_due_taka_info payment_status = 'complete' payment_message = 'Full Paid' remain_taka='PAID' remain_msg='' if customers.customer_due_taka_info < customers.customer_price: payment_status = 'incomplete' payment_message = 'সম্পূর্ন টাকা পরিষোধ করা হয়নি' remain_msg='টাকা বাকী আছে' baki_ase="পাওনা আছে " remain_taka = customers.customer_price - customers.customer_due_taka_info context = {'customers': customers, 'sys_type': sys_type, 'area': area, 'site_credit': site_credit, 'site_name': 'Moon Telecom', 'sys_type': sys_type, 'due_taka_track': due_taka_track, 'total_paid_taka': total_paid_taka, 'payment_message': payment_message, 'time_now': time_now, 'unpaid_taka': unpaid_taka, 'payment_message': payment_message, 'remain_taka': remain_taka, 'sum_cost_taka': sum_cost_taka, 'remain_msg': remain_msg} html_string = render_to_string('shop/pdf_invoice.html', context) html = HTML(string=html_string) result = html.write_pdf() response = HttpResponse(content_type='application/pdf;') response['Content-Disposition'] = 'inline; filename=invoice'+sys_type+'.pdf' response['Content-Transfer-Encoding'] = 'UTF-8' with tempfile.NamedTemporaryFile(delete=True) as output: … -
Save is not Working in django, in shell and Model Form
Please help, I have not seen this error before.The save function is not updating my model either in Shell or in the view. It also gives no error message. >>> from course.models import Course >>> course = Course.objects.get(pk=1) >>> course.title 'test' >>> course.title = "NameChange" >>> course.title 'NameChange' >>> course.save() >>> If I exit and then Re-enter the shell >>> from course.models import Course >>> course = Course.objects.get(pk=1) >>> course.title 'test' The following will also not work on my update view where I use a model Form, I cant post the code for the model form. @superuser_required def update(request, course_id): course = get_object_or_404(Course, pk=course_id) if request.method=='POST': form = CourseForm(data=request.POST, instance=course) if form.is_valid(): form.save() messages.info(request, _("The course has been updated")) return redirect(reverse("course:admin:index")) else: form = CourseForm(instance=course) context = {'form': form,} return render(request, 'course/admin/update.html', context) I would post my models.py file but StackOverflow won't let me, says there is too much code. -
MultiValueDictKeyError when trying to upload image in Django
Hi I'm trying to upload an image file through a form field using Django and i'm getting django.utils.datastructures.MultiValueDictKeyError when trying to submit the form. This is my forms.py: class UserProfileForm(forms.ModelForm): type = forms.ModelChoiceField(queryset=UserType.objects.all(), required=True) phone = forms.CharField(required=False) address = forms.CharField(required=False) picture = forms.ImageField(required=False) class Meta: model = UserProfile # matches data model fields = ('type','phone','address','picture') # shown on the form This is my models.py: class UserProfile(models.Model): user = models.OneToOneField(User) type = models.ForeignKey(UserType, on_delete=models.CASCADE) phone = models.CharField(max_length=10, blank=True) address = models.CharField(max_length=128, blank=True) picture = models.ImageField(upload_to='profile_images', blank=True) def __str__(self): return self.user.username This is my views.py: def register(request): if request.method == 'POST': response = {} username = request.POST.get('username') password1 = request.POST.get('password1') password2 = request.POST.get('password2') type = request.POST.get('type') first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') email = request.POST.get('email') phone = request.POST.get('phone') address = request.POST.get('address') picture = request.POST.get('picture') data = {'username': username, 'password1': password1, 'password2': password2, 'type': UserType.objects.get(type=type).pk, 'first_name': first_name, 'last_name': last_name, 'email': email, 'phone': phone, 'address': address, 'picture': picture} user_form = UserForm(data) profile_form = UserProfileForm(data) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(data['password1']) user.save() profile = profile_form.save(commit=False) profile.user = user #if 'picture' in request.FILES: #profile.picture = request.FILES['picture'] #picture = Image.open(StringIO(profile_form.cleaned_data['picture'].read())) #picture.save(MEDIA_DIR, "PNG") #newPic = Pic(imgfile=request.FILES['picture']) newPic=request.FILES['picture'] newPic.save() profile.save() return JsonResponse({'response': 'success'}) else: errors = user_form.errors.copy() … -
@route not working for Home page
I'm working on a Python/Django project. I have to implement AMP (Accelerated Mobile Page) to some pages. In order to achieve that I'm using route in the models this way: @route(r'^$') def vanilla(self, request): return Page.serve(self, request) @route(r'^amp/$') def amp(self, request): context = self.get_context(request) return TemplateResponse(request, '/pages/article_amp.html', context) That works perfectly fine. When I go to localhost:3000/article/ I get the normal layout, when I go to localhost:3000/article/amp/ I get the AMP version of the page. However when trying with the homepage I get a 404 error: localhost:3000 ==> Works fine localhost:3000/amp/ ==> 404 error Why is this happening? Alternatively, how can I achieve the same for the homepage? -
How to upload the image into the profile (ImageField in Django doesn't work)?
Everybody hello! Somebody help me please, what do i do wrong? I try to upload image (avatar) but something goes wrong. If i use form.save() user is created, but the photo isn't uploaded. If i use instance - photo is uploaded, but i have Exception Value: NOT NULL constraint failed: user_management_app_person.user_id model from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class Person(models.Model): user = models.OneToOneField(User) phone_number = models.CharField(verbose_name="Контактный номер:", max_length=255, null=True, blank=True) birthdate = models.DateField(verbose_name="Дата рождения:", null=True, blank=True) photo = models.ImageField(verbose_name="Загрузите Ваше главное фото:", upload_to="images/avatars/", name="photo", null=True, blank=True) rules = models.BooleanField(max_length=32, blank=True, default='True') def __str__(self): return self.user.username def create_user(sender, **kwargs): if kwargs['created']: user = Person.objects.create(user=kwargs['instance']) post_save.connect(create_user, sender=User) view from django.http import HttpResponseRedirect from django.shortcuts import render from user_management_app.forms import MyRegistrationForm from user_management_app.models import Person def registration(request): if request.method == 'POST': form = MyRegistrationForm(request.POST, request.FILES) if form.is_valid(): form.save() # instance = Person(photo=request.FILES['photo']) # instance.save() return HttpResponseRedirect("/privateroom/") else: form = MyRegistrationForm() args = {'form': form} return render(request, "registration.html", args) form from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class MyRegistrationForm(UserCreationForm): username = forms.CharField(max_length=32, widget=forms.TextInput(attrs= {"type": "text", "class": "form-control", "placeholder": "Username"})) last_name = forms.CharField(max_length=32, widget=forms.TextInput(attrs= {"type": "text", "class": "form-control", "placeholder": "Фамилия"}), required=False) first_name = forms.CharField(max_length=32, … -
How add a domain and port in imagefield sended by django channels?
I have a application written in Angular and Django (with Django REST framework and Django channels). I created a model with "ImageField" and added a data binding (for this field). The problem: When I want get all images (by API), in the response I have a absolute image url: "url": "http://192.168.0.164:8000/media/photos/2017-10-19_20%3A50%3A26.jpg", but... When I add a new Photo, a channel send me by websocket field with relative url (without domain and port and MEDIA_URL) "url": "photos/2017-10-19_20%3A50%3A26.jpg" How to fix it? How add a domain and port in channels? -
Adding Cookiecutter-django users urls to i18n_patterns breaks tests
I'm having a problem with tests and internationalization. Project is Django 1.11 Python 3.5 project created with cookiecutter-django Internationalization code in settings.py: TIME_ZONE = 'UTC' LANGUAGE_CODE = 'en-us' SITE_ID = 1 USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = [ ('en', _('English')), ('fr', _('French')), ('es', _('Spanish')), ('de', _('German')), ] Running pytest on the standard Cookiecutter tests for Users, without adding i18n_patterns, successfully completes. Once the urls are updated like this: urlpatterns += i18n_patterns( .... # User management url(r'^accounts/', include('allauth.urls')), url(r'^users/', include('users.urls', namespace='users')), .... ) The url tests then fail. The output looks like this: ====================================================================== FAIL: test_get_redirect_url (users.tests.test_views.TestUserRedirectView) ---------------------------------------------------------------------- Traceback (most recent call last): File "users/tests/test_views.py", line 33, in test_get_redirect_url '/users/testuser/' AssertionError: '/en-us/users/testuser/' != '/users/testuser/' - /en-us/users/testuser/ ? ------ + /users/testuser/ As you can see, the issue is that /en-us/ is the prefix being used on the url. Now, I could fix this by adding /en-us/ to my assertions. However, the /en-us/ prefix is incorrect. This is a language code and not the regular language prefix as shown in my settings file. Outside of testing, and using runserver, if I navigate to the /users// url it is prefaced with /en/ not /en-us/ So, the big question is … -
NameError for defined class variable [duplicate]
This question already has an answer here: Nested list comprehension scope 1 answer Below, the artifact_urls class variable is clearly defined, and there is no problem referencing it in a print statement or dict constant, but referencing it from within a list comprehension raises a NameError. Why?!?! Here's the code and output. from otree.api import ( models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer, Currency as c, currency_range ) class Constants(BaseConstants): artifact_urls = ["Hello, world!"] print(artifact_urls) artifact_const = { "url": artifact_urls[0] } artifact_const = [{ "url": artifact_urls[i] } for i in range(1)] Output: ['Hello, world!'] Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x1085426a8> Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 107, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 252, in raise_last_exception six.reraise(*_exception) File "/usr/local/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked …