Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to convert image data so it can be JSON serializable and vice versa
How can i make image data JSON serializable and then convert it back so it can be saved as a image. I get the error <InMemoryUploadedFile: image.jpg (image/jpeg)> is not JSON serializable def imageFileView(request): form = ImageFileForm(request.POST or None, request.FILES or None) if request.method == 'POST': if form.is_valid: image = request.FILES.get('image') image_file = image return redirect('picxs:create') def imageView(request): img_file = request.session.get('image_file') img_temp = NamedTemporaryFile('w') img_temp.write(img_file) img_temp.flush() form = SaveImageForm(request.POST or None, request.FILES or None) if request.post == 'POST': if form.is_valid: instance = form.save(commit=False) instance.image.save(img_filename, File(img_temp), save = True) -
User login system is not hashing and comparing password with record Django
I am working on a project and I have created the user login features for new users. I am having an issue with the login system once the user has created an account. The issue is that django is hashing the password when the new account is created. I think that when I try logging into one of the accounts, it is not hashing the password and then checking to see if the passwords match. Is that what is going on or is it something that i am doing.. Here is the views.py file: def login_page(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data username = cd['username'] password = cd['password'] valid_user = User.objects.get(username=username) if valid_user: if password == valid_user.password: request.session['username'] = username return redirect('/') else: message = 'Password does not match the username' else: message = 'Invalid Username' parameters = { 'message':message, 'form':form, } return render(request, 'tabs/login.html', parameters) else: form = LoginForm() message = 'Login Below' parameters = { 'form':form, 'message':message, } return render(request, 'tabs/login.html', parameters) html file: {% extends "base.html" %} {% block content %} <h1>Login</h1> <p>{{ message }}</p> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" name="submit" value="submit"> </form> {% endblock %} … -
Class has no objects member
def index(request): latest_question_list = Question.objects.all().order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = {'latest_question_list':latest_question_list} return HttpResponse(template.render(context, request)) The first line of that function gets an error on Question.objects.all() -->E1101: Class 'Questionhas no objectsmember` Im following the Django documentation tutorial and they have the same code up and running. I have tried calling an instance. Question = new Question() and using MyModel.objects.all() Also my models.py code for that class is this... class Question(models.Model): question_text = models.CharField(max_length = 200) pub_date = models.DateTimeField('date published') def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) def __str__(self): return self.question_text To no avail I still have this error. I have read about pylint and ran this... pylint --load-plugins pylint_django Which didn't help, even tho the github readme file says... Prevents warnings about Django-generated attributes such as Model.objects or Views.request. I ran the command within my virtualenv, and yet nothing. So any help would be great -
Django makemigrations error with translation
I just add translation to a project, reading Django official documentation as reference, the project was working ok, and I add translation to a bunch of line before I test them. I'm using: ugettext_lazy as _ and in my models _('field name') or verbose_name=_('some text') as specified in doc pages. The issue is that I'm getting the following error at run makemigrations: AttributeError: type object 'Code' has no attribute 'replace' One of my models is named Code. I searched for 'Code' string in my IDE and I couldn't find any logical issue as per doc. Here is the function trowing the error: File "/Users/yorsant/Django/lib/python3.6/site-packages/django/utils/translation/trans_real.py", line 338, in gettext return do_translate(message, 'gettext') File "/Users/yorsant/Django/lib/python3.6/site-packages/django/utils/translation/trans_real.py", line 314, in do_translate eol_message = message.replace(str('\r\n'), str('\n')).replace(str('\r'), str('\n')) AttributeError: type object 'Code' has no attribute 'replace' I believe one of _('some text') is generating the error due to is missing something, but I can't find it. How to find the line of code where the error is generated? -
django fullcalendar doesn't appear
I'm using full-calendar from this(https://www.creative-tim.com/product/full-calendar?page=4#comments). The calendar works very well until yesterday. But today, the calendar doesn't appear suddenly. What's wrong?? I tried to git clone the other code calendar worked. But nothing change. Just there is the selecting box of day, week and month. But If I click the day, week, month box, the red color doesn't remove. My CDN. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap- theme.min.css"> <link rel="stylesheet" href="{% static 'css/main.css' %}"> <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/base/jquery- ui.css"/> <link href='{% static "css/fullcalendar.css" %}' rel='stylesheet' /> <link href='{% static "css/fullcalendar.print.css" %}' rel='stylesheet' media='print' /> <!-- JS--> <script src="http://code.jquery.com/jquery-latest.min.js"></script><!-- 1.11.1 --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"> </script> <script src='http://fullcalendar.io/js/fullcalendar-2.1.1/lib/jquery.min.js'> </script> <script src='http://fullcalendar.io/js/fullcalendar-2.1.1/lib/moment.min.js'> </script> <script src="http://fullcalendar.io/js/fullcalendar-2.1.1/lib/jquery-ui.custom.min.js"></script> <script src='http://fullcalendar.io/js/fullcalendar-2.1.1/fullcalendar.min.js'></script> <!-- <script type="text/javascript" src="{% static 'js/jquery-1.10.2.js' %}"> </script> --> <script type="text/javascript" src="{% static 'js/fullcalendar.js'%}"> </script> <script type="text/javascript" src="{% static 'js/main.js' %}"></script> My part of schedule.html var calendar = $('#calendar').fullCalendar({ header: { left: 'title', center: 'agendaDay,agendaWeek,month', right: 'prev,next today' }, editable: true, firstDay: 1, // 1(Monday) this can be changed to 0(Sunday) for the USA system selectable: true, defaultView: 'month', axisFormat: 'h:mm', columnFormat: { month: 'ddd', // Mon week: 'ddd d', // Mon 7 day: 'dddd M/d', // Monday 9/7 agendaDay: 'dddd d' }, titleFormat: { month: 'MMMM … -
Error - NOT NULL constraint failed: posts_post.object_id
I have managed to provide the initial data in my form and its showing in the form, I tested them by priniting the form.cleaned_data and still doing good, My challenge is now saving that information to save the form. class UserPostCreatView(CreateView): form_class = PostModelForm template_name = 'posts/post_form.html' def get_initial(self): # Get the initial dictionary from the superclass method initial = super(UserPostCreatView, self).get_initial() user_slug = self.kwargs.get('user_slug') # print (user_slug) user_content_type = ContentType.objects.get_for_model(authomodel.User) auth_user = get_object_or_404(authomodel.User, user_slug=user_slug) auth_user_id = auth_user.id # Copy the dictionary so we don't accidentally change a mutable dict initial = initial.copy() initial = { "content_type": user_content_type, "object_id" : auth_user_id, } return initial def form_valid(self,form): return reverse('homepage:user_wall', kwargs={"user_slug": self.kwargs.get("user_slug")}) def post(self, request, *args, **kwargs): self.object=None """ Handles POST requests, instantiating a form instance with the passed POST variables and then checked for validity. """ # object = self.get_object(request) form = self.get_form() if form.is_valid(): # Here was testing, it prints the right information about the initial data of the form print (form.cleaned_data) ??????? return self.form_valid(form) else: return self.form_invalid(form) def get_form_kwargs(self): """ Returns the keyword arguments for instantiating the form. """ kwargs = { 'initial': self.get_initial(), } if self.request.method in ('POST', 'PUT'): kwargs.update({ 'data': self.request.POST or None, 'files': self.request.FILES or None}) … -
Adding more associations with foreign key
I have two models: Question and UserEdus. UserEdus can vote on Question. After a vote, Question stores a list of associated UserEdusthat voted. I am not sure how to create and add upon this association. Is saying Question can have many UserEdus the correct way to think about this problem? This is what I have so far. class Question(models.Model): title = models.CharField(max_length=500, null=False) content = models.TextField(max_length=10000, null=False) author = models.ForeignKey('UserEdus', null=False) solution_found = models.BooleanField(default=False, null=False) points = models.IntegerField(default=1, null=False) post_date = models.DateField(default=date.today) class UserEdus(models.Model): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) bio = models.TextField(max_length=400, help_text="Enter your bio details here.") votes = models.ForeignKey(Question, null=True) Upon hitting an upvote button this view is called, def upvote(request,pk): question = get_object_or_404(Question, pk=pk) question.points += 1 request.user.useredus.votes_set.add(question) question.save() This will return error 'UserEdus' object has no attribute 'votes_set' What am I doing wrong? The docs follow this pattern. -
Query using Joins in Django
class Students(models.Model): id = models.BigAutoField(primary_key=True) admission_no = models.CharField(max_length=255) roll_no = models.CharField(unique=True, max_length=50, blank=True, null=True) academic_id = models.BigIntegerField() course_parent_id = models.BigIntegerField() course_id = models.BigIntegerField() first_name = models.CharField(max_length=20) middle_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) user_id = models.BigIntegerField() date_of_birth = models.DateField(blank=True, null=True) date_of_join = models.DateField(blank=True, null=True) class Courses(models.Model): id = models.BigAutoField(primary_key=True) parent_id = models.IntegerField() course_title = models.CharField(max_length=50) slug = models.CharField(unique=True, max_length=50) tenant_user = models.ForeignKey('Users', models.DO_NOTHING, default='') course_code = models.CharField(max_length=20) course_dueration = models.IntegerField() grade_system = models.CharField(max_length=10) is_having_semister = models.IntegerField() is_having_elective_subjects = models.IntegerField() description = models.TextField() status = models.CharField(max_length=8) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) class Meta: managed = True db_table = 'courses' def __unicode__(self): return self.course_title class StudentProfileSerializer(ModelSerializer): class Meta: model = Students depth = 0 fields = '__all__' The first two tables/class contains the course and student table and the third contains the serializer. Can anyone please help how to query using the joins in django. I need to fetch the course_title from Courses table and first_name from Students table. -
when using django rest frameworks viewset views and model serializers do you need to write tests?
When using django rest framworks viewsets and model serializers do you need to write tests? Custom implemented code that uses djangos or django rest frameworks base classes such as API view or serializer, I can see needing to write tests for, but when you use the model serializer or the viewset which are tightly connected to each other and require minimal code from us do we write tests? I want to keep to test driven development, but I have no idea how I would write tests for these cases. -
How can I add extra data to a ModelMultipleChoiceField?
I'm making a calorie counter. The user can pick from a list of Dishes (easy with a ModelMultipleChoiceField), but they also need to specify how many servings of each Dish they had, where the serving_size is a field of my Dish model. Basically, I want it to look like this: The problem is that in order to display the strings "4 oz servings" and "slices", I need access to the Dish model when the field is rendered. What's the best way to do this? I've got 2 rough ideas so far: Create a custom Widget that will render as a checkbox AND a number input field. When the data gets deserialized, it becomes something like this: {"dish": <Dish model>, "servings": 2.5} Just use the regular CheckboxSelectMultiple widget, but add the Dish model itself to the template's context. That way I can do something like this: {% for dish in form.fountain_dishes %} {{dish}} I ate <input type="number"> {{dish.context.serving_size}} {% endfor %} However, I'm not sure how to make my clean method handle this unexpected data. -
Django - filtering out already rated restaurants in yelp like app
Consider the following database model class User: id = models.BigAutoField(primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) class Restaurant: id = models.BigAutoField(primary_key=True) title = models.CharField(max_length=50) class Rating: id = models.BigAutoField(primary_key=True) by_user = models.ForeignKey(to='User', on_delete=models.PROTECT, related_name='written_ratings') for_restaurant = models.ForeignKey(to='Restaurant', on_delete=models.PROTECT, related_name='received_ratings') score = models.SmallIntegerField() # make sure only one vote per user per restaurant class Meta: unique_together = ('by_user', 'for_restaurant') For a given User, we can obtain a list of Restaurant that we have not yet rated by performing the following query (that I have learned from my last post) eligible_restaurants = Restaurant.objects.exclude(rating__by_user_id=my_id) But what happens when the Ratings don't point directly at the Restaurants - but rather at an intermediate Profile object? class User: id = models.BigAutoField(primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) class Restaurant: id = models.BigAutoField(primary_key=True) title = models.CharField(max_length=50) current_profile = models.OneToOneField(to='Profile', on_delete=models.PROTECT, related_name='+') # the `+` means to not generate a related name class Profile: # this is here acting as an intermediate between # `Restaurant` and `Rating` so that we can keep track # of all reviews - deleting/remaking would simply be # creating a new `Profile` and setting the `Restaurant` # to point to it instead - the old one will act as a # historical … -
Sublime Text 3 IDE and Python Django
I can't find any good references that explain exactly what I see in the IDE. I currently use VSCode, and have been looking to move out from VSCode for Python development. It seems everywhere I look, SublimeText 3 is a preferred IDE. I installed this guys stack and right away I started looking for answers regarding what was being displayed. I slapped together this little test app from Django's website. My question is, what are the white dots to the left, and the white rectangles around text? -
What side should a django 'many-to-many' relationship reside on
Lets say I have a recipe website with two basic models, 'User' and 'Recipe' class User(models.Model): username= models.CharField() email = models.CharField() class Recipe(models.Model): name = models.CharField() description = models.CharField() I would like to add the functionality so that users can 'favorite' a recipe. In this case, I need to use a many-to-many relationship. My question is, how do I decide which model to add the relationship to? For example, each user could have a list of 'favorite' recipes: class User(models.Model): favorites = models.ManyToManyField(Recipe) Alternatively, each recipe could have a list of users who Favorited the recipe: class Recipe(models.Model): user_favorites = models.ManyToManyField(User) What is considered the best practice? Is either one better for query performance? -
django.db.utils.ProgrammingError: cannot cast type text[] to jsonb
I was trying to include JSONField in my model: from django.contrib.postgres.fields import JSONField class Trigger(models.Model): solutions = JSONField(blank=True, null=True) However, when I try to migrate the database, it gives the following error: django.db.utils.ProgrammingError: cannot cast type text[] to jsonb LINE 1: ...ALTER COLUMN "solutions" TYPE jsonb USING "solutions"::jsonb What could be done here? -
Error while installing mysqlclient on Fedora25
I am trying to install mysqlclient in my virtual environment which runs on python3.5.2 but it always throws error as: (venv) [kevran@localhost mysite]$ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.3.10.tar.gz Complete output from command python setup.py egg_info: /bin/sh: mysql_config: command not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-m92fr1vk/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/tmp/pip-build-m92fr1vk/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/tmp/pip-build-m92fr1vk/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-m92fr1vk/mysqlclient/ ` -
Django Admin Model ArrayField Change Delimiter
My model looks like this: from django.contrib.postgres.fields import ArrayField class Trigger(models.Model): solutions = ArrayField(models.TextField(blank=True, null=True), blank=True, null=True, help_text='some helpful text') This allows me to enter a list of solutions separated by a comma by default. For example: I can enter in that textfield: 1. watch out for dust., 2. keep away from furry animals., This does create a list of two separate string items. However, if a solution text itself contains a comma, for example: 1. cockroaches, polens and molds might be harmful. This will create two separate solution lines, because of the existence of a comma in that sentence. How do I tell django to use a different delimiter than comma as it would be almost certainly a part of sentences. How can I use a separator like '|'? I looked inside the arrayfield class, but it doesn't allow any separator. -
error deploying a turtle app to heroku
running heroku logs returns: : __import__(module) 2017-07-16T19:52:44.838597+00:00 app[web.1]: File "/app/Main.py", line 1, in <module> 2017-07-16T19:52:44.838598+00:00 app[web.1]: import turtle # modules 2017-07-16T19:52:44.838598+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/turtle.py", line 107, in <module> 2017-07-16T19:52:44.838599+00:00 app[web.1]: import tkinter as TK 2017-07-16T19:52:44.838600+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.5/tkinter/__init__.py", line 35, in <module> 2017-07-16T19:52:44.838600+00:00 app[web.1]: import _tkinter # If this fails your Python may not be configured for Tk Do i need to specify im using tkinter in my requirements.txt file? if so, how? my requirements.txt file reads: autopep8==1.3.2 dj-database-url==0.4.1 gunicorn==19.7.1 pycodestyle==2.3.1 virtualenv==15.1.0 thanks -
How do install Pootle on MAMP PRO
MAMP PRO supports WSGI but the Pootle instalation guide to run on a webserver starts from a previous configuration using a virtualenv. I'd like to know how can i install Pootle manually already using apache. -
Need clarification on running python application over LAN
I don't have much experience when it comes to programming in Python & Perl but that is something that I am planning to pursue full time now. I am getting into Flask/Python model & it seems to be getting along fine in the initial stages. However, based on my ultimate goal, I've a small lingering doubt. Is there a way to run python application as a web application on a simple desktop computer & use that app over the LAN ? If yes, what will be the process for that ? I mean, I understand that frameworks like flask/django/bottle run their own server instance which results in the execution of such web apps. In this way they are practically acting as IIS/Apache. Correct ? The reason for this question is that this app will be accessed by only 4-5 individuals & we all are a part of the same team. -
Django game session. Loggining and requests
What is a proper way to start a "game" session in Django for mobile game like Clash of Clans? I suppose there is a way to login to the server, start a session, build needed class instances like Player, Base, Resources etc. and work with them. Right now I have a problem with periodical requests to the server. I use login code like below, and I wold like to know how can I make a specific instance of CURRENTUSER class to work with in any next requests: @csrf_exempt def rungame(request): user = login(request) if user: *_MAKE_INST_OF_CURRENTUSER_FROM_request.user.profile_* return HttpResponse('Successfully logged as %s!'%user.username) return HttpResponse('Error: Unsuccessfull loginning!') Now I want to work with that logged user, let say CURRENTUSER: @csrf_exempt def getstate(request): return JsonResponse(CURRENTUSER.getstate()) I would like to underline that CURRENTUSER is a custom class with it's own specific methods. It is not inherited from models.Model and it is not a standard Profile like request.user.profile Thanks! -
Monitor celery tasks launched from task
I have a celery task(super task) which further launches different celery tasks (sub tasks) @app.task def super_task(): do_heavy_work() @app.task def sub_tasks(): do_something() def do_heavy_work(): results = group(sub_tasks.s() for i in xrange(100))() # Problem # Once code reach below line any tasks in pending state will # remain in pending state until below code executes for _ in xrange(some_value): if not all(r.ready() for r in results): time.sleep(30) else: break super_task.delay() Question How can track the status of all the sub tasks either with some signals or any other functionality without keeping them in pending state -
display image instead of path in ModelForm in a fresh view in django
I know the way to display image in Admin views for a model's list display and edit view. But, I need the image to display in a different view I have created for end user - to be able to upload more/delete existing photos/images under his id. These are the code changes I have made. It works perfect for Admin views; but not for my custom views. Model Definition: class Photo(models.Model): artist = models.ForeignKey(Artist, on_delete=models.CASCADE) upload = models.ImageField(upload_to=user_directory_path) stars = models.FloatField(default=0) def __str__(self): # return self.artist.last_name+','+self.artist.first_name return mark_safe('<img src="%s" style="width:100px;" />' % self.upload.url) def image_img(self): if self.upload: return mark_safe('<img src="%s" style="width:100px;"/>' % self.upload.url) else: return '(Sin imagen)' image_img.short_description = 'Thumb' image_img.allow_tags = True Views.py: class PhotosetForm(ModelForm): class Meta: model = Photo fields = ('upload', 'image_img') readonly_fields = ('image_img') exclude = ['artist', 'stars'] def photoset_update(request, pk, template_name='portfolios/photoset_form.html'): this_artist = get_object_or_404(Artist, pk=pk) PhotoInlineFormset = inlineformset_factory(Artist, Photo, fields=('upload',)) photoset = PhotoInlineFormset(request.POST or None, request.FILES or None, instance=this_artist) if photoset.is_valid(): photoset.save() return redirect('portfolios:index') return render(request, template_name, {'formset':photoset,}) Form.html: <form method="post" class="form-horizontal artist_form" enctype='multipart/form-data'>{% csrf_token %} <div class="row"> {{ formset.management_form }} {% for photo in formset %} <div class="well"> {{ photo }} </div> {% endfor %} </div> <input type="submit" class="btn btn-primary btn-block" value="Save" /> </form> … -
Which backend language to learn first? [on hold]
Which one do you guys recommend learning first, PHP, Ruby, DJANGO, etc? I've learnt and mastered the front end - HTML5, CSS3, JavaScript, JQuery, Ajax, etc - for those who are wondering. Also, as a web programmer, is it ideal to use a CMS service such as WordPress? Or should we be able to make our own? Thank you. -
Get id/name in request.POST Django
i'am trying to get the id of the clicked li element but i don't get it i need some help here ,and thanks in advance models.py: base_tags = ["foo","boo","voo"] if request.method == "POST" : tag = request.POST[("id","")] blogpages = BlogPage.objects.live().filter(tags__name__in=[tag]) return #.... index.html: <form id="content" method="post"> <ul class="nav nav-tabs" role="tablist"> {% csrf_token %} {%for tag in base_tags %} <li name="id" value="{{tag.id}}" onclick="content.submit();" role="presentation"><a href="#{{tag}}" aria-controls="{{tag}}" role="tab" data-toggle="tab">{{tag}}</a></li> {% endfor %} </ul> </form> -
Why to use Django?
I am confused why to and when to use Django foe we development. If i want to develop a site where Db interactivity is more then is it good to use Django.? If possible please share a link for tutorials also