Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ADD multiple objects with form
I'm trying to do something which I would think is quite common, but I'm just really unsure how to realise it. I have modal 'Requirement'. Every requirement has there own name and unique code. I want to show form with REQUIREMENTS_CHOICES list with checkboxs. User can select checkboxes which requirements they need. How to make it in Django? models.py: class Requirement(models.Model): code = models.UUIDField(_('Code'), primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(_('Name'), max_length=250, choices=REQUIREMENTS_CHOICES) REQUIREMENTS_CHOICES = ( ('A', 'Name A'), ('B', 'Name B'), ('C', 'Name C'), ) -
Favorites are not being returned back to template? Django
On the list the page the user is able to select which aircraft that they want to favourite. I've set it up correctly, but it doesn't seem to be returning anything. Does anyone know where the error could be? Accounts/view.py @login_required def add_aircraft_to_favorites(request, aircraft_id): aircraft_in_favorites = FavoritedAircraft.objects.filter( user__id=request.user.id, aircraft__id=aircraft_id).count() > 0 if aircraft_in_favorites: return JsonResponse({'error': 'already favorited'}, status=409) aircraft = Aircraft.objects.get(pk=aircraft_id) favorited_aircraft = FavoritedAircraft.objects.create( user=request.user, aircraft=aircraft) return JsonResponse({'favorited_aircraft': favorited_aircraft.id}, status=201) @login_required def remove_aircraft_from_favorites(request, aircraft_id): FavoritedAircraft.objects.get(user__id=request.user.id, aircraft__id=aircraft_id).delete() return JsonResponse({}, status=204) View for summary page def account_overview(request): fav_aircraft = FavoritedAircraft.objects.get(user__id=request.user.id) return render(request, 'account/account_overview.html', {'favAircraft':fav_aircraft}) List Template (user can view and favorite their posts) .... </div> {% if user.is_authenticated %} <button class=" favorite btn btn-default {% if aircraft.id in favorited_aircraft_ids %}added{% endif %}" data-aircraft-id="{{ aircraft.id }}"><span class="add">Add</span><span class="remove">Remove</span> Favorite</button> {% endif %} </div> ........ {% block js %} <script> var favorited_aircraft_ids = {% if favorited_aircraft_ids %}{{ favorited_aircraft_ids | escapejs }}{% else %}[]{% endif %}; </script> <script src="{% static 'js/aircraft/favorite.js' %}"></script> {% endblock %} Summary page Template (favorites displayed here) <div class="row aircraft"> {% if favAircraft %} {% for favorite in favAircraft %} <div class="col-lg-offset-0 col-md-4 col-sm-3 item"> <div class="box"><a href="{{ favorite.aircraft.get_absolute_url }}"><img src="{{ favorite.aircraft.image.url }}" width="200px" height="200px" alt="{{ favorite.aircraft.title }}"/></a> <h3 class="name"><a href="{{ … -
Dango - navigate hyperlink to a folder on disk
I would like to click on a hyperlink in my Django template that navigates to an arbitrary URL such as file:///C:/my_dir/folder This URL works if I paste it directly into the address field of a browser, but does nothing if I click on a hyperlink in my Django app that resolves to that URL. I've also tried implementing it using the template - view protocol for Django but in my view neither of these seem to work return HttpResponse(html_filepath)orreturn render(request, html_filepath, context) -
Is it possible to create a google map location from external app?
I'm tired goggling to get my answer. Actually i have a Django apps where have an entry form like google map new location creation form. I wanna entry this form and want to save data to my database along with to create new location to maps.google.com. I used some plug-ins which stores value to database but they actually doesn't create new location to google map. I need some suggestion. -
Django how to tie device to user using token
I have a django app that uses the Django REST Framework with the Django OAuth Toolkit and django-rest-framework-social-oauth2. Each user has a raspberry pi that can come with a preloaded token. When users login to the website for the first time they are asked to enter the token that they got and is associated with the device. The device then should be tied to the user and is supposed to download configuration linked to the user profile. I was thinking that I could create an oauth client_id/secret for each device, and only give the user the client_id, and tie the credentials to their account once they enter it. The device could then access an API endpoint and see user specific data. Is there any way to do this? Any other suggestions to solve this problem would also be welcome! -
Range Slider in Django form to select integer value
I want to select duration as an integer between 2 to 24 hours. I tried to use rangeslider.js but It is showing me text input box. models.py class AppointmentDetail(models.Model): duration = models.PositiveIntegerField(default=12, help_text='value 2 to 24', validators=[MaxValueValidator(24),MinValueValidator(2)]) Forms.py class AppointmentForm(forms.ModelForm): class Meta: model = AppointmentDetail fields = [duration] widgets = {'duration': forms.TextInput(attrs={'class': 'duration-input'}),} HTML File. <!Doctype HTML> <html> <head> <script src="jquery.min.js"></script> <script src="rangeslider.min.js"></script> <script> $(function (){ $('.duration-input').rangeslider({ }); }); </script> </head> <body> <p> Duration: {{form.duration}} </p> </body> </html> -
how to convert a text to dict in order to iterate it in python?
What i am trying to do is to iterate. I have this line of code in one column in a table in my database: [{u"item": 5, u"quantity": 2},{u"item": 6, u"quantity": 1}] i assign this to a variable order so i have: order = [{u"item": 5, u"quantity": 2},{u"item": 6, u"quantity": 1}] then i want to iterate it. I am trying the follow: for o in order.items(): product = o['item'] ... it doesn't work. How can i convert it? for order in orders: ord = order.shopping_cart_details # [{u"item": 5, u"quantity": 2},{u"item": 6, u"quantity": 1}] temp = {'order_id': order.id, 'movies': ord['item'], 'created': order.created} full_results.append(temp) i get string indices must be integers -
Multiple object types references in Django
We are currently running with the following configuration to avoid other issues so for the question, let's assume this is a must and we can not change the Models part. So, at first, we had the following models: class A(Model): b = ForeignKey(B) ... set of fields ... class B(Model): ... Then we added something like this: class AVer2(Model): b = ForeignKey(B) ... ANOTHER set of fields ... Assuming an object in B can only be referenced by either A or AVer2 but never both, is there a way to run a query on B that will return, in runtime, the correct object type in the query result (and the query has both types in it)? You can assume that an object of type B holds the information regarding who's referencing it. I am trying to avoid costly whole-system code changes for this. Thanks! -
What to do to run makemigrations/migrate on heroku when deploying changed models from github?
I have deployed app from github repository to the heroku account of my customer as collaborator but this time I had to add some new models. However I realized that when I deploy my changes from github heroku does not run makemigrations and migrate. I I read some answers on stackoverflow and understood this is how it is supposed to be. However my question is what should I do ? What is the best practise to deploy change models to heroku app. (I assume it is not deleting and recreating my app again since customer already has data there.) -
Python scripting for Bitbucket server API access
Anyone know how to access branch related operations pull,push,clone and also take backup of branch,repository as zip or tar file etc of Atlassian Bitbucket server 4.14 installed on local machine using python script I tried bitbucket-api module of python but it supports only Cloud REST API of Bitbucket...? -
Store two types of value in single Django model field
I am learning django by creating a polling application. For starters I have three models User, Question and Choices. class User(....): .... Questions_voted = models.ManyToManyField(Question) .... this means that a user to vote for as many questions as he wants. Next is The Question Model which is simple and just store question text and number of people voted for it. class Question(models.Model): question_text = models.CharField(max_length=500) vote_count = models.IntegerField(...) next is Choices which have a choice_text and refers to the question it belongs to. class Choice(models.Models): choice_text = models.CharField(models.Model) question = models.ForeignKey(Question,...) Now I want to store information about what choice a user selected for a question. It is very clear when you think of it but I am stuck because of lack of knowledge of types of fields in django models. -
Deploying Django, Gunicorn, Nginx, Virtualenv on Digital ocean gives me 502 Bad Gateway & Gunicorn can't read Secret Key
I've been trying to deploy for 2 days now and It seems like I can't get it to work even though I went through many articles, StackOverflow questions, and Digital Ocean Tutorials. My main tutorial is this one: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04?comment=47694#create-and-configure-a-new-django-project when I bind my gunicorn file (see command below) and go to my_ip_address:8001 everything works fine gunicorn --bind 0.0.0.0:8001 vp.wsgi:application But at the part where I created and edited my gunicorn.service file: sudo nano /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=tony Group=www-data WorkingDirectory=/home/tony/vp/vp/ ExecStart=/home/tony/vp/vpenv/bin/gunicorn --workers 3 --bind unix:/home/tony/vp/vp/vp.sock vp.wsgi:application [Install] WantedBy=multi-user.target And my nginx file (I replaced my ip address with my_ip_address for privacy) sudo nano /etc/nginx/sites-available/vp server { listen 80; server_name my_ip_address; location = /facivon.ico { access_log off; log_not_found off; } location /static/ { root /home/tony/vp; } location / { include proxy_params; proxy_pass http://unix:/home/tony/vp/vp/vp.sock; } } I get a bad gateway 502 error. Even after reloading everything: (vpenv) ~/vp/vp$ sudo systemctl daemon-reload (vpenv) ~/vp/vp$ sudo systemctl start gunicorn (vpenv) ~/vp/vp$ sudo systemctl enable gunicorn (vpenv) ~/vp/vp$ sudo systemctl restart nginx So I checked the status of gunicorn: (vpenv) ~/vp/vp$ sudo systemctl status gunicorn And get the error: gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed … -
UnboundLocalError at / local variable 'instance' referenced before assignment
I'm making a simple django form that will take a tweet by its id, and print out the corresponding tweet. I cannot figure out why it is giving me this error. form = TweetForm(request.POST or None) if form.is_valid(): instance = form.save(commit = False) instance.save() print instance.tweet_id tweet = api.get_status(instance.tweet_id) print tweet.text tweet_text = tweet.text -
Prevent Django from logout through url before hitting enter
So I have created a Django-app with a login form and using login(request, user) in my view.py to login the user. This is the main page and has the location mypage.com. I also created another function in my view.py called log_out: def log_out(request): logout(request) return redirect('/') This function is used to log out a user using the url: mysite.com/logout as defined in my url.py: url(r'^logout/', views.log_out, name='log_out'), This is working to log out the user, however the user is being logged out as I'm typing in the logout-url into the address-field of my browser, and before hitting enter to go to that endpoint. I would like it to not log out the user when typing in the url, and wait until I'm "entering" the site. Can anyone help me with this one? -
Django ManyToMany relationship details
I want to build a website in which users can send words to each other using Django. When a user deletes a word, that word will be deleted for only that user. I have a working website; the only problem is when a word is deleted, it is deleted for all users. How can I fix this problem, is it a problem which is related to ManyToMany relationships? Django word model: from django.db import models from datetime import datetime from django.contrib.auth.models import User class Word(models.Model): definition = models.CharField(max_length=350) turkish = models.CharField(max_length=50) english = models.CharField(max_length=50) users = models.ManyToManyField(User) creator = models.CharField(max_length=50) def __str__(self): return self.english def summary(self): return self.definition[:50] + "..." The share view function: @login_required def send(request): users_list = User.objects.all().exclude(username=request.user.username) user = request.user small = user.username.title() send_to_str = request.POST['user'] sent_word_str = request.POST['word'] send_to = User.objects.get(username=send_to_str) sent_word = Word.objects.get(id=sent_word_str) if not users_list: sendmessage = 'You have no friends' else: sendmessage = '' sent_word.users.add(send_to) words = Word.objects.filter(users=user).order_by('-english') return render(request, 'intro.html', {'sendmessage': sendmessage, 'words': words, 'small' : small}) The delete view function: @login_required def delete(request): if request.method == 'POST': current_id = request.POST['word_id'] current_word = Word.objects.get(id=current_id) current_word.delete() messages.add_message(request, messages.INFO, 'Succesfully deleted.') return redirect('translater:home') else: return render(request, 'intro.html', {'message': 'there is a problem'}) Redirected to … -
Efficient way in Django Models to store Items Purchased in a Transaction for a Commerce Store
I've created two simple Django Models. One model simply holds the bill details. The other one holds the list of items purchased in that Bill, linked through a foreign key relation. I'm stuck at a problem of creating a very large database with this implementation. Model Classes : class Bill(models.Model): seller_id = models.ForeignKey(User , related_name = 'bill') amount = models.DecimalField(max_digits = 7 , decimal_places = 2) customer_id = models.ForeignKey(User , related_name = 'bill') and class BillItems(models.Model): bill = models.ForeignKey(Bill , related_name = 'items') product = models.ForeignKey(Product , related_name = 'items') quantity = models.DecimalField(max_digits = 6 , decimal_places = 3) Now as I see it , after some time my database(MySql) would have a very large number of Bill Items' instances. Is there a better way to implement such a structure? OR Is there a way to optimize this structure? Thanks and Regards. -
How to change “true/false” checkboxes in Django ModelForm
Hello again friends, I added checkboxes to the model. How to change “true/false” to “yes/no”? I do not want to Radio buttons or select option. models.py class Order(models.Model): paid = models.BooleanField(default=False) forms.py from django import forms from .models import Order class OrderCreateForm(forms.ModelForm): class Meta: model = Order fields = ['paid'] It's important to me, even though it's a little thing, I would appreciate your help. -
Djano Rest Framework - Extra Data at Save on Update
I am experiencing some strange behaviour using the .save(field = 'value') on the perform_update event using Django Rest Framework inside view.py. I am updating a specific field, adding logic and adding additional data to the serializer before saving data in the model/database based on a the customer's response/api call. Each time I test by setting an PUT (update) as 'yes' and then 'no', the .save() randomly works. I think sometimes the save() happens before the variable gets set and passed to .save(). I am fairly new to Django and Python so I may not be doing this correctly. I have also tried declaring variables and then passing those variables into .save(field='created variable') but I still get the same strange behaviour. Here is my code: def perform_update(self, serializer): # Change depending on customer's repsonse. # customer_acceptance is "yes" or "no" from front end print(serializer.instance.customer_acceptance) if serializer.instance.customer_acceptance == 'yes': serializer.instance.creditor_status = 'accepted' serializer.instance.agreement_acceptance = 'yes' if serializer.instance.customer_acceptance == 'no': serializer.instance.creditor_status = 'customer_rejected' serializer.instance.agreement_acceptance = 'no' if serializer.is_valid(): print(serializer.instance.creditor_status) serializer.save( customer_response_date = datetime.datetime.now() ) -
Django recursive query on non-symmetrical Many-to-Many to the same model
I'm offering services to companies (many-to-many between Service and Company). To structure my services, I use a tree-like structure using Django's many-to-many field. So, a service can contain multiple other services. The question: how can I retrieve all services a company has? Using company.services, I only get the services directly related to that company. I need the directly related ones + included_services (in a recursive way). class Company(models.Model): services = models.ManyToManyField(Service) class Service(models.Model): name = models.CharField(max_length=255) included_services = models.ManyToManyField("self", blank=True, symmetrical=False) -
Autogenerate seats in django mode
I'm developing a bus reservation website using Django. I have two model files in different Django apps. One of the model class is Bus and another one is seats. There is capacity integerfield in bus class. I want that when a bus is created in the database, automatically a loop runs and creates the seats equal to the capacity in the bus class. Maybe you'll get a clearer view after looking at my models files. \src\book\models.py from django.db import models from django.contrib.auth.models import User from web.models import Bus, Route class Booking(models.Model): class Meta: verbose_name_plural = "Booking" user = models.ForeignKey(User) #session = models.ForeignKey(sessions.Sessions) name = models.CharField(max_length=50) gender = models.CharField(max_length=10, choices=(('Mr', 'mr'), ('Mrs', 'mrs'), ('Ms', 'ms'),)) age = models.IntegerField() email = models.EmailField() phone = models.IntegerField() bus = models.ForeignKey(Bus, default='') def __str__(self): return self.name class Seat(models.Model): class Meta: verbose_name_plural = "Seat" for seats in range(1,int(float(Bus.capacity)+1.0)): id = models.AutoField(primary_key=True) bus = models.ForeignKey(Bus) def __str__(self): return str(self.id) class Ticket(models.Model): class Meta: verbose_name_plural = "Ticket" seat = models.ForeignKey(Seat) bus = models.ForeignKey(Bus) route = models.ForeignKey(Route, default='') def __str__(self): return str(self.id) \src\web\models.py from django.db import models from django.core.exceptions import ValidationError class Route(models.Model): class Meta: verbose_name_plural = "Routes" BUSFROM = ( ('Delhi', 'Delhi'), ('Jaipur', 'Jaipur'), ('Ajmer', 'Ajmer'), ) BUSTO … -
django-rest-auth registration/verify-email/ not working
I just download demo from official dhango-rest-auth site and tried to use but some API endpoint not working. I successfully signup (register) user with restful API, i get key in response: `{"key":"e96496ecb7fbe85d5ab60fe5d5f9a15b33a967fe"}` and user exists (when i check in database) and i also get email with verification link, but when i try to verify its email with rest api: `curl -X POST http://127.0.0.1:9003/rest-auth/registration/verify-email/ -d "key=e96496ecb7fbe85d5ab60fe5d5f9a15b33a967fe"` i am getting: `{"detail":"Not found."}` Where i am making mistake. This is just demo i didn't do anything just install, set sending email, host and run server. Also when i click on link in email it opens page with confirm button and when i click on confirm i get: `Using the URLconf defined in demo.urls, Django tried these URL patterns, in this order: ^$ [name='home'] ^signup/$ [name='signup'] ^email-verification/$ [name='email-verification'] ^login/$ [name='login'] ^logout/$ [name='logout'] ^password-reset/$ [name='password-reset'] ^password-reset/confirm/$ [name='password-reset-confirm'] ^user-details/$ [name='user-details'] ^password-change/$ [name='password-change'] ^password-reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$ [name='password_reset_confirm'] ^rest-auth/ ^rest-auth/registration/ ^account/ ^admin/ ^accounts/profile/$ [name='profile-redirect'] ^docs/$ [name='api_docs'] The current path, accounts/login/, didn't match any of these.` Why this also doesn't work? This is demo where i am making mistake? Please help! -
Django generate page with components
I have one idea but I don't know figure out how this should work. I have page class: class Page(object): title = None slug = None inMenu = False parent = None # place for register parent page # array of components in page # { componentName: 'carousel', htmlConent: '', images: ['slide_01.jpg', 'slude_02.jpg'] } #(from carousel model) components = [] template = Template ('index.html') I have the components now as a templateTags in django what I need is render page class with all components and args. For example: {% extends 'base.html' %} {% block content %} {% for component in page.components %} {% render_component component%} {% endfor %} {% endblock %} have you try something like that? I don't know how exactly render the templateTags from the array with args. Could someone help me with this?. -
In Django, how can I change the settings variable dynamically by taking the value from the database?
I am using the google smtp server to send mail.For that I need to set two variables EMAIL_HOST_USER and EMAIL_HOST_PASSWORD in settings.py file. I want to take the values for both of the variables from the database to allow the user to enter the email id from the web. -
Create custom abstract view class inheried from APIView
I am working in DJango with DJango REST Framework module. For each model I make, I have a view: class CustomAPIView(APIView): renderer_classes = (JSONRenderer, ) permission_classes = (IsAuthenticated, ) @csrf_exempt def post(self, request): raw_data = serializers.SearchStateSerializer(data=request.data) if raw_data.is_valid(): searched_data = serializers.ShowStateSerializer(data=serializers.State.objects.extra(where=raw_data.data['where'], order_by=raw_data.data['order_by']), many=True) return JsonResponse(paginate_data(searched_data=searched_data, request_data=raw_data), status=status.HTTP_202_ACCEPTED) else: return JsonResponse(raw_data.errors, status=status.HTTP_400_BAD_REQUEST) In this code, there are 3 constraints that change: SearchStateSerializer ShowStateSerializer State(Model) So I want to create an abstract in which I only specify these 3 things and the view works. How can I do this? I searched a lot but with no luck. It is must that these 3 constraints are supplied or it will throw error. -
Mocking forms in view unit tests
I can't seem to be able to mock the behaviour of a form when unit testing views. My form is a simple ModelForm and resides in profiles.forms. The view is (again) a simple view that checks whether the form is valid and then redirects. views.py from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from profiles.forms import ProfileForm def home(request): form = ProfileForm() if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): profile = form.save() return HttpResponseRedirect(reverse("thanks")) My test looks like this: class TestViewHomePost(TestCase): def setUp(self): self.factory = RequestFactory() def test_form(self): with mock.patch('profiles.views.ProfileForm') as mock_profile_form: mock_profile_form.is_valid.return_value = True request = self.factory.post(reverse("home"), data={}) response = home(request) logger.debug(mock_profile_form.is_valid.call_count) # "0" is_valid is not being called on the mock, which means ProfileForm is not patched. Where did I make a mistake?