Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
update previous table on mysql with new column?
i have created a django app and add some model fields on models.py 1.logo 2.shirt and their attributes are pid, name and org then i added a new attribute price to them. and execute command python manage.py makemigrations and python manage.py sqlmigrate myapp 0002. before adding new attribute/field to logo/shirt i have added some logo and shirt object from django administration page. and after updating logo/shirt i.e. adding new attribute price i got error with previous object Exception Type: OperationalError Exception Value: (1054, "Unknown column 'buapp_logo.price' in 'field list'") what can i do for it ? -
Heterogeneous python2 / python3 django on apache2
I've 2 django projects running on a debian jessie server with mod_wsgi from debian repos, on a system apache2 / virtualhosts. Those projects are both running with python 2.7 in virtualenvs. I'm currently working on a new project (django 1.11) which is written for python 3.5, to prepare django abandon of python 3 : the older apps will be migrated later. So I've to host heterogeneous python setups on the same apache server. I've read that virtualenv installed mod_wsgi (via pip install) provides a way to accomplish the kind of setup : using the virtualenv' installed mod_wsgi to serve django app, and use the debian-wide apache2 server to proxies the django app. My questions: Does somebody have already done this ? I think I've to write some systemd service files, where can I find some specific examples ? What about the static / media files ? apache2 or mod_wsgi ? (In my old setups, media and static are directly served by apache2) Thanks for your help ! -
Can't remove objects from ManyToMany relations
Good day. I create new field on my User model. blocked_users = models.ManyToManyField('self', verbose_name=_('blocked users'), symmetrical=False, related_name='blocked_by', blank=True) So I wanna get blocked users: In [18]: User.objects.first().blocked_users.all() Out[18]: <UserQuerySet [<User: admin>, <User: test@mail.com>, <User: i_uglev>, <User: denisdvornikov6697>] Now I clear that and try again: In [21]: User.objects.first().blocked_users.clear() In [22]: User.objects.first().blocked_users.all() Out[22]: <UserQuerySet [<User: admin>, <User: test@mail.com>, <User: i_uglev>, <User: denisdvornikov6697>]> WHAT I try did it from django-admin and got same result. What's wrong? Thanks for your attention. -
Saving User foreign key upon creation of related model
My Category model is related to User, but I can't find a way to store the logged in user's id into user_id field in Category. Category models.py: class Category(models.Model): user = models.ForeignKey(User, default=None) name = models.CharField(max_length=32, unique=True) views.py: class CategoryList(APIView): ... def post(self, request): """ Create a new Category :param request: :return: Category """ user_id = request.user.pk serializer = CategorySerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=HTTP_201_CREATED) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) I can access request.user.pk and see it's correctly shown, but I can't figure out how I can store this value when creating a new category. -
Upload to rackspace with django
I have a image upload website : I want to upload my users photo(user upload image) to rackspace.com But i dont have any information about upload to this site. Tell me a way to upload my image to this server. -
How to insert data into database using prepared statement query in Django and python
I need one help. I need to insert form data into sqlite3 db using prepared statement query in Django and Python. I am explaining my code below. models.py: class Meeting(models.Model): """In this class the columns for Meeting table has declared""" room_name = models.CharField(max_length=200) from_date = models.DateTimeField(default=datetime.now, blank=True) to_date = models.DateTimeField(default=datetime.now, blank=True) no_seat = models.CharField(max_length=200) projector = models.CharField(max_length=200) video = models.CharField(max_length=200) created_date = models.DateTimeField(default=datetime.now, blank=True) Here I have already created the table by migrating. I am explaining my views.py below. import sqlite3 def insert(request): """ This function helps to insert all booking data into database """ conn = sqlite3.connect("db.sqlite3") cursor = conn.cursor() if request.method == 'POST': location_name = request.POST.get('lname') rname = request.POST.get('rname') seat = request.POST.get('seat') projector = request.POST.get('projector') video = request.POST.get('video') location_name = location_name[0:255] rname = rname[0:255] seat = seat[0:10] from_date = request.POST.get('from_date') to_date = request.POST.get('from_date') Here I need all data should save into DB by running prepared statement query. Please help me. -
Fetch Data from html form to use it in views.py-Django
I am new to django so bear with me.I am trying to build a simple web app to fetch the current weather.Problem is I am not able to fetch the pincode entered in my HTML form and use it in my views.py file. As I told u I am new to django so please try to explain it the most simple way. Thanks. -
Parsing JSON incoming to a Webhook
I'm trying to build a webhook that receives JSON being POSTed from a third party service, Messagebird. In their documentation they have an example of an outgoing query: GET http://your-own.url/script ?id=e8077d803532c0b5937c639b60216938 &recipient=31642500190 &originator=31612345678 &body=This+is+an+incoming+message &createdDatetime=2016-05-03T14:26:57+00:00 My webhook is being built with Python in Django, and this is what I have in my views.py: from django.shortcuts import render from django.views.decorators.http import require_POST from django.http import HttpResponse from .models import UserText @require_POST def webhookmb(request): usrtxt = json.loads(request.body.decode("utf-8")) UserText.objects.create( id = usrtxt['id'] recipient = usrtxt['recipient'] originator = usrtxt['originator'] body = usrtxt['body'] createdDatetime = usrtxt['createdDatetime'] ) return HttpResponse(200) Essentially, it is supposed to read the JSON into a file and then map those fields to a model. I get an error "JSONDecodeError: Expecting value: line 1 column 1 (char 0)". Is this because json.loads is trying to read the file and the first like starts with GET? Do I need to skip this line? Or is there another way to go about this? -
django using update view on the same page or as pop-up
when the class view is used like using UpdateView the page is changed to another Url as per the urls.py can we just display Update view o the same page or as a pop-up on the same page -
Django request.path not working in inclusion tag template
I tried to use request.path in the inclusion tag template, but the url does not show up. The request.path does work properly when used in parent template, and the inclusion tag works properly in all other places. I enabled 'takes_context' in the inclusion tag, but I don't know if and where I should specify any path-specific context in the views.py. Currently I use render() method to output the logic from my views.py: def DJ_LastDay(request): p = Post.objects.latest('Day') posts = Post.objects.filter(Day=p.Day) return render(request, 'blog/DJ_LastDay.html', {'DJ_LastDay_posts': posts}) Snippet of my inclusion tag: from django import template register = template.Library() @register.inclusion_tag('blog/index_table.html', takes_context=True) def DJ_LastDay(context): return {'posts': context['DJ_LastDay_posts']} Snippet of my inclusion tag template (DJLD, DJLW, DJLM, DJLQ, and DJLY are all url shortcuts I enabled in the parent template, and they work fine outside the inclusion template): {% if request.path == DJLD %} Last Day {% elif request.path == DJLW %} Last Week {% elif request.path == DJLM %} Last Month {% elif request.path == DJLQ %} Last Quarter {% elif request.path == DJLY %} Last Year {% endif %} I just needed to detect the current path for a conditional check to display the proper string in my template. Any help is … -
OperationalError: no such table (can't find solution)
Many questions here with same issue, and I followed the instructions to solve the issue in all those questions but failed. My problem started when I changed a table name, I had one record in that table, I didn't delete that record and used makemigrations, and then migrate. I received an error of "no such table", then I followed some instructions, including: flush (to drop the tables) deleted migration folder, and recreated it with init file clear migration history using fake zero None of the above worked for me, I can make the migration, but when I migrate, at first instance it says no changes detected, when I make migration again, then migrate, it says no such table exists (always mentions the table that I changed the name of) I'm wondering if there are any other solutions I can try. -
UNIQUE constraint failed - Django
I am unable to solve this problem. I have seen the similar queries posted but none of the answers helped. my Models: class MyUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), max_length=254, unique=True) contact_number = models.IntegerField(_('contact number'), validators=RegexValidator(r'^\+?1?\d{9,10}$'), null=True, blank=True) .... On migration the error that appears: django.db.utils.IntegrityError: UNIQUE constraint failed: user_profile_myuser.contact_number Please help. -
HttpResponseRedirect after login form not redirecting to profile
I'm trying to get a local copy of a Django site working. The production site works just fine on login, but my local instance doesn't redirect to the profile page after completing the login form. This is the login_page view: def login_page(request): profile_page = HttpResponseRedirect('profile') if request.user.is_authenticated(): return profile_page form = LoginForm(request.POST or None) if request.POST and form.is_valid(): user = form.login(request) if user: login(request, user) return profile_page return render(request, 'login.html', {'form': form}) This is what the debug output of the server shows: Performing system checks... <function home_page at 0x7f77ad696c08> System check identified no issues (0 silenced). July 08, 2017 - 03:21:39 Django version 1.9.1, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [08/Jul/2017 03:21:49] "GET / HTTP/1.1" 200 3276 [08/Jul/2017 03:21:50] "GET /login HTTP/1.1" 200 2370 [08/Jul/2017 03:21:57] "POST /login HTTP/1.1" 302 0 [08/Jul/2017 03:21:57] "GET /profile HTTP/1.1" 302 0 [08/Jul/2017 03:21:57] "GET /login?next=/profile HTTP/1.1" 200 2370 After the above, the browser is left at http://127.0.0.1:8000/login?next=/profile and just displays the standard login page. Again, identical code is working on the same version of Django in production (though running through gunicorn/nginx instead of django-admin runserver), so it makes me think that there's something in my Django … -
preventing hardcoded url to delete in django
I have a link and button inside it that deletes a record associated with the button <a href="{% url 'parts:stock_delete' stock.id %}"> <button class="delete" type="submit" name="delete_btn" style="position: absolute; right: 40px;" >Delete</button></a> but I want the record to be deleted only when the button is pressed but not when URL is typed in the address bar like: http://127.0.0.1:8000/parts/stock_delete/16/ what can be done for this? -
How install Django with Postgres, Nginx, and Gunicorn on MAc
I try install Django with Postgres, Nginx, and Gunicorn on Mac OS Sierra 10.12, but without success. Whats is the correct way ? -
DJANGO REST API not generating right PK
Working on Django REST API in which a dog is shown to a user based on preferences (age, gender, size). A user can either like or dislike a dog. They are then shown the next dog (assuming they haven't seen it yet) based on their set preferences. My issue is that a user is shown the first dog based on preferences, but when they go to click either like or dislike it is not moving to the next dog. So as an example for dog 1 my api at api/dog/1/liked/next is resulting in a not found error where the PK is showing as -1 or undefined. Ok here are my models: class Dog(models.Model): name = models.CharField(max_length=255) image_filename = models.CharField(max_length=255, default='') breed = models.CharField(max_length=255, default='Unknown Breed') age = models.IntegerField() gender = models.CharField(choices=GENDER, max_length=1) size = models.CharField(choices=SIZE, max_length=2) @property def get_image_url(self): return self.image_filename.name def __str__(self): return self.name class UserDog(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) dog = models.ForeignKey(Dog, on_delete=models.CASCADE) status = models.CharField(choices=STATUS, max_length=2) class Meta: unique_together = ('user', 'dog') def __str__(self): return '{} {} {}'.format(self.user, self.dog, self.get_status_display()) class UserPref(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) age = models.CharField(max_length=7, default='b,y,a,s') gender = models.CharField(max_length=3, default='m,f') size = models.CharField(max_length=8, default='s,m,l,xl') def __str__(self): return '{} preferences'.format(self.user) And View corresponding … -
Jobtastic/Celery/RabbitMQ - AsyncResult is always PENDING
I am using Django, Celery, and Jobtastic to try to set up some tasks that I will be polling for on my main webapp. I am using RabbitMQ as my broker. The problem is that while the tasks show up properly after starting Celery, attempting to get the status as shown below: def get_state(request, task_id): if request.is_ajax(): task = AsyncResult(task_id) data = task.result or task.state print(data) json_data = json.dumps(data) return JsonResponse(json_data) I am unable to get any other status but PENDING. My terminal shows that the task has completed yet I still get a PENDING status. I have tried changing the backend below under CELERY_RESULT_BACKEND to multiple backends, including DJCelery, AMQP, and RPC. They all show up properly when launching Celery so I know they are being registered. I also try to start Celery with the --pools=solo option, as suggested for Windows platforms but have not had any luck with that either. Below is my celery.py file where I initialize the celery app. from __future__ import absolute_import import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'arbitrage.settings') from django.conf import settings # noqa app = Celery('arbitrage') # Using a string here … -
How can I customize a nested serialized list of django model objects to be key/value pairs instead?
lets say I have models like so: class Device(models.Model): name = models.CharField(max_length=100,null=True) model = models.CharField(max_length=100,null=True) lab = models.ForeignKey(Lab,null=True, related_name='devices') class Lab(models.Model): name = models.CharField(max_length=100) Where a lab can have multiple devices. When I create serializers I am able to get something back like this: {'name':'My Lab','devices':[{'name':'Device 1','model':'iPhone'},{'name':'Device 2','model':'iPad'}]} However, what I would like to get back is key/value pairs instead of a list of devices, like so: {'name':'My Lab','devices':{'Device 1':{'model':'iPhone'},'Device 2':{'model':'iPad'}}} I'm imagining I have to use the SerializerMethodField to make this work, but I am having trouble figuring it out. -
Django-template "text|linebreaks" not working with css "overflow-wrap: break-word"
I'm trying to implement both: css break-word and jinja linebreaks, but only linebreaks seem to work. Is it possible to make those two things working together? template.html: <p style="overflow-wrap: break-word">{{ text|linebreaks }}</p> -
Django Sessions via Memcache: Cannot find session key manually
I recently migrated from database backed sessions to sessions stored via memcached using pylibmc. Here is my CACHES, SESSION_CACHE_ALIAS & SESSION_ENGINE in my settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache', 'LOCATION': ['127.0.0.1:11211'], } } SESSION_CACHE_ALIAS = 'default' SESSION_ENGINE = "django.contrib.sessions.backends.cache" Everything is working fine behind the scenes and I can see that it is using the new caching system. Running the get_stats() method from pylibmc shows me the number of current items in the cache and I can see that it has gone up by 1. The issue is I'm unable to grab the session manually using pylibmc. Upon inspecting the request session data in views.py: def my_view(request): if request.user.is_authenticated(): print request.session.session_key # the above prints something like this: "1ay2kcv7axb3nu5fwnwoyf85wkwsttz9" print request.session.cache_key # the above prints something like this: "django.contrib.sessions.cache1ay2kcv7axb3nu5fwnwoyf85wkwsttz9" return HttpResponse(status=200) else: return HttpResponse(status=401) I noticed that when printing cache_key, it print with the default KEY_PREFIX whereas for session_key it didn't. Take a look at the comments in the code to see what I mean. So I figured, "Ok great, one of these key names should work. Let me try grabbing the session data manually just for educational purposes": import pylibmc mc = pylibmc.Client(['127.0.0.1:11211']) # Let's try key … -
how to add custom js into ALL admin models? django
as this url mentioned https://docs.djangoproject.com/en/dev/topics/forms/media/#assets-as-a-static-definition I know that and it does work by adding each custom js into each model one by one BUT is there a way to add into ALL models so I do not have to add each model one by one? -
Django: Facebook Bot, send automatic messages
Hello my question is how I can send automatic messages to my users by Facebook with a bot, I do my bot with this tutotial: https://abhaykashyap.com/blog/post/tutorial-how-build-facebook-messenger-bot-using-django-ngrok My aplication is an intelligent security house system so I want to send a message when, for example, the levels of temperature are so high or something like that, the only thing that I want to know is this part of send the message to the correct FB user. -
Allowing users to change order of list of items
I am trying to allow users to create a list of items with their categories in the order they want. For some reason categories are appearing in the order users are choosing. But, items are showing in a random order! even though I am using the same code for them! models.py class Category(models.Model): user = models.ForeignKey(User) title = models.CharField(max_length=250) order = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(10)]) class Item(models.Model): user = models.ForeignKey(User) category = models.ForeignKey(Category) title = models.CharField(max_length=250) order = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(10)]) views.py def items_list(request): category = Category.objects.filter(user=request.user).order_by("order") item = Item.objects.filter(user=request.user).order_by("order") return render(request, 'restaurant/meal.html', {"items": item, "categories": category}) Any help would be much appreciated. -
How can i create combining a multiple model into a single form and increasing the variable of a model?
I am creating a classical questionnaire form, but using the generic function. I've just added an interviewer to a sample from Django training sites. My codes are like this; polls/model.py class Question(models.Model): pollster = models.ForeignKey('auth.User', related_name='questioner', verbose_name='SelFly') question_text = models.CharField(max_length=200,verbose_name='Soru Metni') pub_date = models.DateTimeField(verbose_name='Yayınlanma Tarihi',auto_now_add=True) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text polls/viewss.py def polls_create(request): form=QuestionForm(request.POST or None) if form.is_valid(): poll=form.save() return render(request,'polls/index.html',{}) else: context={ 'form':form, } return HttpResponseRedirect(reverse('polls:index')) polls/forms.py class QuestionForm(forms.ModelForm): class Meta: model=Question fields='__all__' class ChoiceForm(forms.ModelForm): class Meta: model=Choice fields = '__all__' FormSet = inlineformset_factory(QuestionForm, ChoiceForm, form=QuestionForm,extra=2) polls/urls.py url(r'^/create/$',polls_create,name='create'), templates/polls/form.html <h1> Form </h1> <form method="post"> {{ form.as_p }} </form> I want to create a form similar to the one on that site. Insert button must be made for multiple selections https://medium.com/@adandan01/django-inline-formsets-example-mybook-420cc4b6225d enter image description here -
Getting the many-to-many fields of a many-to-many object
If I have the user-group relation as a ManyToMany relationship, and a group-team relation as a ManyToMany relationship, how would I find the user-team relation as a query object? For example if I had a models.py like this: class Group(models.Model): name = CharField(max_length=100) class User(models.Model): username = models.CharField(max_length=100) groups = models.ManyToManyField(Group, blank=True) class Team(models.Model): teamname = models.CharField(max_length=100) groups = models.ManyToManyField(Group, blank=True) I know I can do it by creating a for loop like follows, but it would be much more useful given django's architecture to have it as a query object. My ugly solution: user = User.objects.get(username="Ed") users_teams = [] user_groups = Group.objects.filter(user=user) for group in user_groups: group_teams = Team.objects.filter(group=group) for team in group_teams: user_teams.append(team) So this would give me a list query objects that I could associate with a user, but it isn't as easy to use as a single query set the contains query objects for each user-team relation. Any ideas?