Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Elastic Beanstalk URL cannot access Website after successful environment update
I am hosting a Django site on Elastic Beanstalk. I haven't yet linked it to a custom domain and used to access it through the Beanstalk environment domain name like this: http://mysite-dev.eu-central-1.elasticbeanstalk.com/ Today I did some stress tests on the site which led it to spin up several new EC2 instances. Shortly afterwards I deployed a new version to the beanstalk environment via my local command line while 3 instances were still running in parallel. The update failed due to timeout. Once the environment had terminated all but one instance I tried the deployment again. This time it worked. But since then I cannot access the site through the EB environment domain name anymore. I alway get a "took too long to respond" error. I can access it through my ec2 instance's IP address as well as through my load balancer's DNS. The beanstalk environment is healthy and the logs are not showing any errors. The beanstalk environment's domain is also part of my allowed hosts setting in Django. So my first assumption was that there is something wrong in the security group settings. Since the load balancer is getting through it seems that the issue is with the Beanstalk … -
valueError: Cannot assign, "User.userprofile" must be a "UserProfile" instance
Within my serializers I have this: def update(self, instance, validated_data): password = validated_data.pop('password', None) if password is not None: instance.set_password(password) instance.save() new_instance = super(UserSerializer, self).update(instance, validated_data) firebase_user_crud(new_instance, validated_data) return new_instance This part in specific gives me error: new_instance = super(UserSerializer, self).update(instance, validated_data) This is what my models look like: class UserProfile(models.Model): user = models.OneToOneField(User) mobile = models.CharField(blank=True, null=True, max_length = 50) picture = models.ImageField(_('image'), blank=True, null=True, upload_to=user_upload_to) @property def lit_points(self): lit_points = LitPoint.objects.filter(user=self.user).aggregate(models.Sum('points')) if lit_points['points__sum'] == None: return 0 else: return lit_points['points__sum'] User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0]) User.settings = property(lambda u: UserSettings.objects.get_or_create(user=u)[0]) Error Message: ValueError: Cannot assign "{u'mobile': u'blahblah', u'lit_points': 5}": "User.userprofile" must be a "UserProfile" instance. -
How to have additional field besides the fields in the model in ModelForm
I have a model named Customer and modelForm named Customer, but in my form i need more fields than the fields in Model. For example i want a confPass field in my ModelForm. Code for Model: class Customer(models.Model): name = models.CharField(max_length=50) email = models.EmailField(max_length=100, unique=True) mobile_no = models.CharField(unique=True, validators=[validate_mobile], max_length=10) state = models.CharField(choices=STATES, max_length=2) city = models.CharField(max_length=20) password = models.CharField(max_length=256) def __str__(self): return self.email class CustomerForm(ModelForm): class Meta: model = Customer fields = ['name', 'email', 'mobile_no', 'state', 'city', 'password'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['name'].widget.attrs.update({'placeholder': 'Enter Name', 'class': 'form-control'}) self.fields['email'].widget.attrs.update({'placeholder': 'Enter Email', 'class': 'form-control'}) self.fields['mobile_no'].widget.attrs.update({'placeholder': 'Enter Mobile Number ', 'class': 'form-control'}) self.fields['state'].widget.attrs.update({'class': 'form-control'}) self.fields['city'].widget.attrs.update({'placeholder': 'Enter City', 'class': 'form-control'}) self.fields['password'].widget.attrs.update({'class': 'form-control'}) -
Django + NGINX only serving some static files
This is probably the millionth django+nginx post, but since I didn't find an answer after more than 5 hours here it goes: My issue is that not all static files get served, only some. The whole thing runs inside Docker where I run RUN python manage.py collectstatic --noinput; RUN python manage.py makemigrations; RUN python manage.py migrate; on each start, but it does not serve my new .js and .css files although they are in the same directories as the old ones. I also see the message: 132 static files copied to '/static'. and above that is the list of files being copied there, including the new ones. Project Structure: /djangoapp /app /static /css /js /django /Dockerfile /docker-compose settings.py: DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = '/static' nginx.conf: upstream web { ip_hash; server web:8000; } server { location /static { autoindex on; alias /static; } location / { proxy_connect_timeout 3600; proxy_send_timeout 3600; proxy_read_timeout 3600; proxy_pass http://web/; } listen 8000; server_name localhost; } Why aren't all static files being served? EDIT: Dockerfile: FROM python:3.6.4-onbuild RUN mkdir /config; RUN mkdir /src; COPY . /src WORKDIR /src RUN python manage.py collectstatic --noinput; RUN python manage.py makemigrations; RUN python manage.py migrate; RUN chmod 775 … -
Django sites framework without SITE_ID
Are there any advantages/disadvantages to using SITE_ID in order to manage the sites framework in Django - as opposed to just relying on the hostname and allowing Django to "work out" the site based on that? I need to provide multiple sites off the same codebase and the same database and I'm just trying to work out whether I need to set the SITE_ID or not. If I want to use SITE_ID, I'll need a settings.py for each site - which means creating a separate web server (nginx) config for each site and some corresponding uwsgi stuff. But in theory, I can take the SITE_ID out altogether, point the nginx config at the same server instance, have 1 settings.py and get_current_site will work out which site it's running on at runtime. Is either way better than the other? If so, why?! -
Django rest framework, tokken authentification, but not for the creation of users
I've been making a simple project with DJango and his rest framework, I want my users to authenticate with tokkens, the problem is that when I try to register users I get this message: "Authentication credentials were not provided". Thi is a problem, a first time user should be able to register without authentication, any idea how can I make my users registrate witout tokkens?. Here are my User serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password', ) The user views: class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all() serializer_class = UserSerializer The urls: router = routers.DefaultRouter() router.register(r'devices', views.DeviceViewSet) router.register(r'users', views.UserViewSet) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include(router.urls)), url(r'^api-auth/', cosa.obtain_auth_token), ] The problem is that when I tried to create a User with this command: http POST http://127.0.0.1:800/users/ username="Foo" password"admin123456" email="foo@gmail.com" I get this message: "Authentication credentials were not provided". Any idea how to fix it? -
How to connect front-end with back-end
I'm doing a project on Machine learning. I have my front-end in django and back-end in python. Now how shall I connect them. I want to give the input in front-end and it would be processed in back-end and output would be shown on front-end. Any links would be helpful. Thanks in advance. -
Does Django Debug Toolbar work with DRF?
I'm trying to setup Debug Toolbar to debug some API methods via DRF's Browsable API. I've went through the steps described on the Installation page (like updating INSTALLED_APPS, MIDDLEWARE, etc.) but still can't see any toolbar. So does Debug Toolbar work with DRF? How to debug the issue with it not showing up? -
Django - Looping through a dictionary using a second variable in template
I'm trying my best not to repeat myself in my code but I'm encountering a problem looping through a dictionary by key in my template. I have two dicts: exampledict={'firstkey':firstval, 'secondkey':secondval} keys=['firstkey', 'secondkey'] keydict={'keys':keys} In my template I want to loop over the exampledict using the keydict: <tr> {% for val in keydict %} <td>{{ exampledict.val }}</td> {% endfor %} </tr> I've noticed this kind of combination of variables doesn't work at all, I tried by using: {'firstkey':'firstkey'} And sending that through to the template and later trying {{ exampledict.firstkey }} Is there a better way to accomplish what I'm trying to do here? Edit: Manually going through each key as: <td> {{ exampledict.firstkey }} </td> <td> {{ exampledict.secondkey }} </td> Where firstkey and secondkey is the actual dictkey for exampledict works, although it makes for a lot of repetition. -
Django rest framework custom user registration
I am trying to get django rest framework user registration working and I am stuck. I have a custom user that adds a field to the django auth user and I am following the first answer on this link but it's giving me a 'KeyError' and I don't really know how to solve it. Any help is appreciated! Here is my Model: class CustomUser(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) birthday = models.DateField() Here the Serializer: class CustomUserSerilizer(serializers.Serializer): birthday = serializers.DateField() class Meta: model = CustomUser fields = ('birthday') class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) custUser = CustomUserSerilizer(required=False) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password', 'custUser') def create(self, validated_data): profile_data = validated_data.pop('custUser') user = User.objects.create(**validated_data) user.set_password(validated_data['password']) user.save() Customer.objects.update_or_create(user=user,**profile_data) return user And the Views: @api_view(['POST']) def create_auth(request): serialized = UserSerializer(data=request.data) if serialized.is_valid(): serialized.save() return Response(serialized.data, status=status.HTTP_201_CREATED) else: return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) Traceback: File "C:\Users\admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "C:\Users\admin\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\generic\base.py" in view 69. return self.dispatch(request, *args, **kwargs) File "C:\Users\admin\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\views.py" in dispatch 494. response = self.handle_exception(exc) File "C:\Users\admin\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\views.py" in handle_exception … -
TypeError __str__ returned non-string (type NoneType) [Python/Django]
I have a form that generate PDF file based on fields values. There is an upload field to add image to display it in the pdf. The uploaded file name is added in a multiple select field. If i try to generate the pdf, i got this error : __str__ returned non-string (type NoneType) This is the code that generate the error: {% for photo in nouvelle_fiche_pdf.photos_persistent.all %} {% if photo.legende is not None%} {{ photo.legende }} <img src="{{ photo.image.url }}" width="150" style="float: left"/> {% endif %} {% endfor %} view code photos_persistents = [] photo_ids = request.POST.getlist(prefix + 'photos') print("photo_ids: " + str(photo_ids)) if photo_ids: for photo_id in photo_ids: print("yes") photo = models.Photo.objects.get(pk=photo_id) photo_persistent = models.PhotoPersistent() composantes = models.PhotoPersistent.objects.all() cmpt = 1 for composante in composantes: if str(photo) == str(composante): photos_persistents.append(composante) cmpt = 0 break if cmpt == 1: photo_persistent.produit = photo.produit photo_persistent.legende = photo.legende photo_persistent.image = File(photo.image) photo_persistent.save() photos_persistents.append(photo_persistent) new_photo def new_photo(request): if request.method == "POST": photo_form = forms.PhotoForm(request.POST, request.FILES, prefix="photo") if photo_form.is_valid(): photo = photo_form.save() photo.save() return HttpResponse(json.dumps({"id": photo.pk, "produit": photo.produit, "legende": photo.legende, "name": photo.image.name})) else: HttpResponseBadRequest() elif request.method == "GET": print(models.Photo.objects.all()) photos = {} for p in models.Photo.objects.all(): photos[p.pk] = {"produit": p.produit, "legende": p.legende, "name": p.image.name} … -
django use value of a link parameter in a template
I need to use a parameter in a link inside a template for example if my url link is http://127.0.0.1:8000/app1/factory=toyota/ inside my template with the same link I just mentioned above I tried : 1- {% if 'factory' in request.GET %} <h1>my {{request.GET.factory}}</h1> {% endif%} and tried 2- {% if request.GET.factory %} <h1> {{request.GET.factory}}</h1> {% endif%} and tried 3- {{request.GET.factory}} without using if statement but nothing appear at my template page.....any ideas??what am I doing wrong? Thanks -
Access form data of POST method in table in Django
currently I am working with Django In template, I combined table and form and thus the code looks like this: <form role="form" method="post">{% csrf_token %} <table class="table" border="0.5px" > <thead> <tr> <th>ID</th> <th>NAME</th> <th>LOWER_BOUND</th> <th>UPPER_BOUND</th> <th>GENE_REACTION_RULE</th> <th>SUBSYSTEM</th> </tr> </thead> <tbody> {% for object in reactioninfo %} <tr> <td><input type="checkbox" name="checkbox" id="checkbox" value="{{ object.id }}"><a href="{{ object.get_absolute_url }}">{{ object.id }}</a></td> <td>{{ object.name }}</td> <td>{{ object.lower_bound }}</td> <td>{{ object.upper_bound }}</td> <td>{{ object.gene_reaction_rule }}</td> <td>{{ object.subsystem }}</td> </tr> {% endfor %} </tbody> </table> <button type="submit" id="generate" name="generate" value="generate" class="btn btn-default btn-success pull-right">Generate Graph</button> </form> And in views.py, the code looks like this: class MetaboliteDetail(FormMixin, generic.DetailView): model = Metabolites template_name = 'Recon/metabolite_detail.html' def get_context_data(self, **kwargs): pk = self.kwargs.get(self.pk_url_kwarg, None) context = super(MetaboliteDetail, self).get_context_data(**kwargs) context['reactions'] = Reactionsmeta.objects.all() context['reactioninfo'] = Reactions.objects.filter(metabolites__contains=pk) return context def generate(self, request): checklist = request.POST.getlist('checkbox') btnval = request.POST.get('btnDelete') if checklist and btnval == 'btnDelete': context = dict(result=checklist) return render(request, "Recon/combinegraph.html", context) elif btnval == 'btnDelete': context = dict(result=checklist) return render(request, "Recon/combinegraph.html", context) else: context = dict(result=checklist) return render(request, "Recon/combinegraph.html", context) However, when I finished this and click on the Generate button, the url is actually not changed and the the page appears HTTP405 error. What is going wrong and how can I … -
Django Jsonresponse filtered queryset by id
My objective is to get the id and make a queryset filtered by id, as in the following code: views.py class MyProfile(TemplateView): model = Reports template_name = 'template.html' def get_context_data(request, *args, **kwargs): if kwargs.get('pk', None): q = kwargs.get('pk', None) queryset = Reports.objects.all().values('id','line_x','line_y',).filter(id = q) data = list(queryset) return JsonResponse(data, safe=False) urls.py url(r'^profiles/(?P<pk>\d+)/$', views.MyProfile.as_view()) It returns the following error: context must be a dict rather than JsonResponse Django 1.11.8 -
Django: Preventing form from being saved inside models.py
I'm working on a Django app in which users can ask a Question, but problem is that in case a user types ???, %%, etc in the question form & submit it, then slug becomes '' (slug == '') & the form gets saved into database. class Question(models.Model): question_text = models.CharField(max_length=250) slug = models.SlugField(max_length=255, unique=True) def get_unique_slug(self): slug = slugify(self.question_text) unique_slug = slug num = 1 while Question.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 if slug == '': # what can we do now? return unique_slug def save(self, *args, **kwargs): if not self.slug: self.slug = self.get_unique_slug() return super(Question, self).save() We have to either prevent slug from being a empty string or simply prevent the form from being saved. How can we do that? Thank You! -
How to use Multi Choice Field in Django 2.0
This picture below illustrate all what I want to implement in the Database. Please I don't know how to connect checkbox button to each course in the ChoiceField Turple and likewise the course_code will be on the same line with courses... Pls i need a solution on how to go about it.... Students can enroll all Courses in the Turple model.py class Course(models.Model): COURSES_CHOICES = ( ('analysis', 'Analysis'), ('numerical', 'Numerical'), ('philosophy', 'Philosophy'), ) course_names = models.Charfield(choices=COURSES_CHOICES, null=True,) course_code = models.CharField(max_length=40) couse_unit = models.intergerField() class Department(models.Model): name = models.Charfield(max_length=30) student = models.ForeignKey(User) course = models.ManyToManyField(Course) I dont know if am right with my model.py... Am still a learner in Django -
Django ManyToMany queries
Might be a silly question but I'm new to django. This is my user, class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, max_length=255) mobile = PhoneNumberField(null=True) username = models.CharField(null=True, unique=True, max_length=255) And this is my Room object which has a ManyToMany relationship with the User class Room(Base): name = models.CharField(unique=True, max_length=255) club = models.ForeignKey(Club, on_delete=models.CASCADE, null=True) users = models.ManyToManyField(User) From this model its easy to get all Users in a room. My questions is how do I get all Rooms for an user. Any help appreciated. -
Django - Refreshing sessions the easy way
I have a question about refreshing sessions! When I was making sessions expire using PHP I just required sessionmaintenance.php at the top of a document, is there an easy way to do the same in a Django template, so that I don't have to do it in every view? Example view-code: @login_required def index(request): request.session.set_expiry(30) testvar="Hi!" return render(request, 'testapp/index.html', {'testvar':testvar}) @login_required def uploadview(request): request.session.set_expiry(30) etc... What I'd like to do is make a base.html that looks something like this - Example template code: {% if user.is_authenticated %} <h6>{{ request.user.username }} {{ request.user.first_name }}</h6> {% endif %} {% request.session.set_expiry(30) %} {% block content %} {% endblock %} Incorporating the session refresh into my base.html so that my view-code looks cleaner and I don't have to repeat myself as much. -
Django template tags get/filter models
I'm trying to accomplish something using template tags. I have a shop which have ratings of products. I wanted a template tag that get rating value and user if exists. @register.simple_tag def puntaje_usuario(prod): rating = Rating.objects.get(usuario=request.user.id, producto=prod.id) return rating I wanna use it here: (template rating stars) <div class="prod-info"> <h5><a href="{{x.get_absolute_url_shop}}" class="txt-muted"> {{x.nombre}} </a></h5> {% if puntaje_usuario x %} <!-- SAME SELECT THAT "else" WITH RATING VALUE OPTION SELECTED --> {% else %} <div class="stars stars-example-css m-b-10"> <select class="rating-star puntaje-producto" data-url="{% url 'puntuar_producto' %}" data-producto="{{x.id}}" data-usuario="{{request.user.id}}" name="rating" autocomplete="off"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </div> <h6 class="txt-info">{% rating_promedio x.id %}</h6> {% endif %} The error I'm getting is Unused ''x'' at end of if expression. -
What is the difference between context.push() and context.update() in Django Context
From the documentation , I understand that the context object is a stack. Then what are push() and update() doing with respect to this code segment ? It is stated in the doc that push() and update() are similar but update() takes a dictionary as argument. Then why are we using them simultaneously here ? import django.template import django.template.loader def render(name, *values): ctx = django.template.Context() for d in values: ctx.push() ctx.update(d) t = django.template.loader.get_template(name) return str(t.render(ctx)) Also , what is the need of having context object as a stack ? -
Unable to use data of one app in another in Django
I have three apps (Internship, UserProfile and Infrastructure) in my django project. I have made models Profile and StudentProject in UserProfile Model. The StudentProject Model contains two foreign key-> user and Lab (this model is defined in the Infrastructure model). In a template(details.html file) in Infrastructure app, i want to retrieve all StudentProjects who have their foreign key as the lab whose details are currently being shown. I am unable to bring the student projects created here. Please help someone. I have already tried to use filter but it doesn't work! userprofile/models.py file from django.conf import settings from django.db import models from django.core.urlresolvers import reverse from infrastructure.models import Lab class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=100) type = models.CharField(max_length=100) profile_picture = models.FileField() skills = models.CharField(max_length=1000) def get_absolute_url(self): return reverse('userprofile:index') def __str__(self): return self.name class StudentProject(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=100) project_picture = models.FileField() lab = models.ForeignKey(Lab) mentor = models.CharField(max_length=100) domain = models.CharField(max_length=100) description = models.CharField(max_length=1000) def __str__(self): return self.title def get_absolute_url(self): return reverse('userprofile:index') infrastructure/models.py file from django.db import models from django.core.urlresolvers import reverse class Lab(models.Model): name = models.CharField(max_length=100) department = models.CharField(max_length=100) description = models.CharField(max_length=1000) lab_logo = models.FileField() def get_absolute_url(self): return reverse('infrastructure:details', kwargs={'pk': self.pk}) def __str__(self): return … -
How to configure MySQL with Django
Am trying to use MySQL with Django 2.0, I have installed it using "pip install mysqlclient" and it installed successfully. What do i need to do next? -
Django OperationalError, lacking id column
I am having trouble making my newly created table (blog_sp500_post_noid_sorted) show up. Whenever I attempt to open the table under the admin page, I got the following error message: OperationalError at /admin/blog/sp500_post_noid_sorted/ no such column: blog_sp500_post_noid_sorted.id Request Method: GET Request URL: http://127.0.0.1:8000/admin/blog/sp500_post_noid_sorted/ Django Version: 1.8 Exception Type: OperationalError Exception Value: no such column: blog_sp500_post_noid_sorted.id Exception Location: C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 318 Python Executable: C:\Python27\python.exe Python Version: 2.7.9 Python Path: ['C:\\Python27\\djangogirls\\mysite', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages'] Server time: Sun, 15 Apr 2018 11:30:20 -0700 The table was created by inserting columns from an already existing table in the database using SQLite command. I noticed that an ‘id’ column was always created for models in Django. However, such id column was absent for tables created using SQLite command. Is there any way for Django to ignore the absence of id column or do I have to manually create an id column? -
How do I use workers and background task in django channels 2?
I want to make a background task, it will not be a websocket in a consumers.py, but instead a separate loop that polls for sensor values. I looked at https://channels.readthedocs.io/en/latest/topics/worker.html but i can't seem to find an example of doing this in Channels 2. -
Django 2 multi-table joins?
Python 3.6 / Django 2 I have a Profile model that defines and "extended" User model. I have a Group model that defines some internal, app related groups; and, a ProfileGroupLink model that defines the possible group(s) a profile might belong to. Let's say the tables look like: Profile ---------- id int name_last varchar(32) name_first varchar(32) account_number uuid Group ---------- id uuid name varchar(32) ProfileGroupLink ---------- id int groupLnk uuid foreign key(Group.id)int profileLnk uuid foreign key(Profile.account_number) I have the active user "profile" from: my_profile = Profile.objects.get(user=request.user) I would normally write an SQL query something like: select Group.name from Group as Group inner join Profile as Profile on ? = Profile.id inner join ProfileGroupLink as ProfileGroupLink on Profile.id = ProfileGroupLink.profileLnk and Group.id = ProfileGroupLink.groupLnk order by Group.name and pass the profile id in as a parameter. I am looking at the page: https://docs.djangoproject.com/en/2.0/topics/db/queries/ but I am not getting the double underscore syntax for joins. My current attempt is: groups = Group.objects.all() \ .filter(GroupList__profile=my_profile.account_number) \ .filter(GroupList__group=Group__group_id) but PyCharm flags "Group__group_id" as an unresolved reference. I am importing the models. How do I do this in Django?