Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Model design on alternative ingredients name
I am creating a simple application that captures the name of a product along with their respective ingredients. I have 2 models defined in my Django app for that class Product(models.Model): name = models.CharField(max_length=150, blank=False) class Ingredient(models.Model): # 1 ingredient belongs to many products. products = models.ManyToManyField(Product) name = models.CharField(max_length=150, blank=False) As I was looking at random products and their ingredients, I noticed that there are alternative names of to an ingredient. For example, certain manufacturers would put water as, aqua, h2o, eau, purified water, distilled water and so on. How can I best write a model that is able to capture these alternative names in an efficient manner? I thought of putting in additional fields such as alternativeName1 = models.CharField(max_length=150, blank=True) alternativeName2 = models.CharField(max_length=150, blank=True) alternativeName3 = models.CharField(max_length=150, blank=True) But it doesn't seem like a good application design. -
How to do comapany reverse relation to User queryset in Django?
Background: 1. In my system it has multiple companies 2. One company has 2 companyappid(s). It is an mobile application id. Default one for each company is 3257 and other one is generated by series. 3. I use OneToOne to keep the UserProfile because it is not related to authentication system. Goals: 1. Be able to use out the User who is in the same company of the request(er) 2. Be able to set is_active to False to that user Questions: Is it possible to minimize the query to single one? Attempt: AbstractTimestamp is just an ordinary datetimeField no any other logics class DeactivateViewSete(viewsets.ModelViewSet): permission_classes = (DeactivatePermission,) serializer_class = DeactivateSerializer # TODO: Should be a better way on this. It takes 3 database hits def get_queryset(self): """ Get the User queryset :return: """ company = self.request.user.userprofile.companyappid.company companyappids = CompanyAppID.objects.filter(company=company) userprofiles = UserProfile.objects.filter(companyappid__in=companyappids) ids = [user.id for user in userprofiles] return User.objects.filter(id__in=ids) SourceCode: https://gist.github.com/elcolie/8f37a8ce1ed12d45f7d3ad6f04312a8b https://gist.github.com/elcolie/c002e6a6d33f8739824c6e66796b09d3 https://gist.github.com/elcolie/0e1d990089431521bd7e5c0956d5b4d8 https://gist.github.com/elcolie/e89decac625c0b1dd3016ddfa85ab2c0 -
Django rest Framework: NoReverseMatch error even when pattern name has been defined
I've created a api_root in my views.py @api_view(['GET']) def api_root(request, format=None): return Response({ 'books': reverse('api_book_list'), 'users': reverse('api_user_list') }) Which is referred to by my rest_api.urls.py urlpatterns = [ url(r'', api_root), url(r'^books/$', BookList.as_view(), name='api_book_list'), url(r'^books/(?P<pk>[0-9]+)/$', BookDetail.as_view(), name='book-detail'), url(r'^users/$', UserList.as_view(), name='api_user_list'), url(r'^users/(?P<pk>[0-9]+)/$', UserDetail.as_view(), name='user-detail'), ] My project root urls.py links to the rest_api.urls.py with the following url-config: url(r'^api/v1/', include('rest_api.urls', namespace='api')), Yet, when I visit the /api/v1/ page I get the following error: NoReverseMatch at /api/v1/ Reverse for 'api_book_list' not found. 'api_book_list' is not a valid view function or pattern name. But I've defined the pattern name in my urls.py, does anyone have a idea why Django still wont recognize it? -
django how to make my own password_reset_confirm.html form
I am doing a django project, where i need to reset the user password by email. The django app name is 'dashboard'. All is running fine. Ive created all the templates: password_reset_complete.html, password_reset_confirm.html, password_reset_done.html, password_reset_email.html, password_reset_form.html and password_reset_subject.txt. My password_reset_confirm.html is: {% extends 'login/base.html' %} {% load staticfiles %} {% block content %} <div class="container"> <img class="logo" src="{% static 'dashboard/img/smge/smge.png' %}"><br> {% if validlink %} <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Alterar senha</button> </form> {% else %} <p> Link inválido. Por favor, solicite um novo reset de senha. </p> {% endif %} </div> {% endblock %} My urls.py (from my app 'dashboard') is: from django.conf.urls import url from . import views #from django.contrib.auth_views import views as auth_views from django.contrib.auth import views as auth_views from django.conf.urls import include handler400 = 'views.my_custom_bad_request_view' handler403 = 'views.my_custom_permission_denied_view' handler404 = 'views.my_custom_page_not_found_view' handler500 = 'views.my_custom_error_view' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^login$', views.do_login, name='login'), url(r'^reset/done/login$', views.do_login, name='login2'), url(r'^logout$', views.do_logout, name='logout'), ... And my urls.py (from my project) is: from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth import views as auth_views from django.views.generic.base import TemplateView from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^', include('dashboard.urls', namespace='dashboard', app_name='dashboard')), url(r'^admin/', admin.site.urls), url(r'^', include('django.contrib.auth.urls')), ] … -
Unavailable to render JQuery Datatable with Django
I have a problem trying to render a JQuery Datatable in my Django templates, but it returns nothing (its never entering my "tabla" view). Nevertheless, if i put all the code that is in the "tabla" view, to the "else" statement on my "ordenar" view, then it returns the JSON object perfectly. The problem with the latter, is that I will have two different Datatables on my template, and I don't know how to make the POST request to differentiate between the two. So I decided to put the Datatables requests in different views. views.py def ordenar(request): if request.method == 'POST': if 'var1' and 'var2' and 'var3' in request.POST: #doing something already return HttpResponse("SUCCESS") else: return HttpResponse("NO SUCCESS") return render(request, 'mypage/index.html', {'some':context}) def tabla(request): query = MyModel.objects.all() json = serializers.serialize('json', query, use_natural_foreign_keys=True) return HttpResponse(json, content_type='application/json') template javascript: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.css"> <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap.min.js"></script> <script type="text/javascript"> $(document).ready( function () { $("#mytable").DataTable({ "ajax": { "url": "{% url 'tabla' %}", "type": "POST", "dataSrc": "" }, "columns": [ { "data": "pk" }, { "data": "fields.product" }, { "data": "fields.weight" } ] }); } ); </script> template html: <div class="col-lg-6"> <table class="table table-strip" id="mytable"> <caption><center>My Caption</center></caption> <thead> … -
Django: query many2many self referenced
Currently I have this models: class Group(models.Model): def __str__(self): return(self.name) dependency = models.ManyToManyField('self',related_name='group_rel') name = models.TextField() class Publication(models.Model): name = models.TextField() group = models.ManyToManyField(Group, related_name='group_dependency') I want to query all childrens(groups) for one group. First I get one group: group = Group.objects.filter(pk=1)[0] After I don't know how to get all childrens(groups) from this group: dir(group) ['DoesNotExist', 'MultipleObjectsReturned', 'class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'setstate', 'sizeof', 'str', 'subclasshook', 'weakref', '_check_column_name_clashes', '_check_field_name_clashes', '_check_fields', '_check_id_field', '_check_index_together', '_check_local_fields', '_check_long_column_names', '_check_m2m_through_same_relationship', '_check_managers', '_check_model', '_check_model_name_db_lookup_clashes', '_check_ordering', '_check_swappable', '_check_unique_together', '_do_insert', '_do_update', '_get_FIELD_display', '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_pk_val', '_get_unique_checks', '_meta', '_perform_date_checks', '_perform_unique_checks', '_save_parents', '_save_table', '_set_pk_val', '_state', 'check', 'clean', 'clean_fields', 'date_error_message', 'delete', 'dependency', 'from_db', 'full_clean', 'get_deferred_fields', 'group_dependency', 'id', 'name', 'objects', 'pk', 'prepare_database_save', 'refresh_from_db', 'save', 'save_base', 'seri alizable_value', 'unique_error_message', 'validate_unique'] Note: Publication is this question is not used. I only show it because there are a many2many to group. -
django aws S3 define upload file path and file dynamically
In my Django app, I would like to define upload path and file dynamically when saving to AWS S3. I am able to so far save to S3 directly the file however, I want to set the path and filename it self. So for example, upon upload i want it to be in the S3 path bucketname\employeeid\file_randomnumber.png How can i do something like this ? Below are my code: https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py @api_view(['POST']) def update_employee_image(request): # ----- YAML below for Swagger ----- """ description: update employee image. parameters: - name: employee_id type: integer required: true location: form - name: face_image type: file required: true location: form """ parser_classes = (FileUploadParser,) employee_id = request.POST['employee_id'] face_image_obj = request.data['face_image'] employee = Employee.objects.get(id = employee_id) logging.debug(f"API employee username {employee.username}") #employee.face_image = face_image_obj employee.upload = face_image_obj <--- here is where it assign the file to S3 employee.save() return Response("Employee Updated!", status=status.HTTP_200_OK) https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee') company = models.ForeignKey(Company) username = models.CharField(max_length=30, blank=False) upload = models.FileField(blank=True) <--- S3 field https://gitlab.com/firdausmah/railercom/blob/master/railercom/settings.py (AWS settings) AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } DEFAULT_FILE_STORAGE = 'railercomapp.storage_backends.MediaStorage' https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/storage_backends.py from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = … -
Django Value Error
I am new to Python and Django and having trouble with my project. I am following the "Tango with Django" Ebook and tried to access a jpg file via URL. What happens is that I get this Error Message: File "/home/studpro/.local/lib/python2.7/site-packages/django/contrib/staticfiles/finders.py", line 61, in __init__ prefix, root = root ValueError: need more than 1 value to unpack My settings.py path settings look like this: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static'), # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR,] I am running Django 1.10.08 and Python 2.7 Anyone has a clue what could be the mistake? -
List all objects from two models in one view
I have two models. Campaign and Placement. Every placement object is related to only one campaign object. I want to list all Campaign objects with all placements related. Campaign #1 - Placement #1 - Placement #2 Campaign #2 - Placement #3 - Placement #4 ... How can I do it with one view and one template? Campaign model: class Campaign(models.Model): ACTIVE = 1 INACTIVE = 0 STATUS_CHOICES = ( (ACTIVE, 'Active'), (INACTIVE, 'Inactive'), ) CPC = 'cpc' CPM = 'cpm' CPV = 'cpv' status = models.IntegerField(default=1, choices=STATUS_CHOICES) client_name = models.ForeignKey(Client, on_delete=models.CASCADE) campaign_name = models.CharField(max_length=100) start_date = models.DateField(default=datetime.date.today) end_date = models.DateField(default=datetime.date.today) def __str__(self): name = str(self.client_name) + " - " + self.campaign_name return name Placement model: class Placement(models.Model): ACTIVE = 1 INACTIVE = 0 STATUS_CHOICES = ( (ACTIVE, 'Active'), (INACTIVE, 'Inactive'), ) CPC = 'cpc' CPM = 'cpm' CPV = 'cpv' UNIT_CHOICES = ( (CPC, 'CPC'), (CPM, 'CPM'), (CPV, 'CPV'), ) status = models.IntegerField(default=1, choices=STATUS_CHOICES) campaign_name = models.ForeignKey(Campaign, on_delete=models.CASCADE) publisher_name = models.ForeignKey(Publisher, on_delete=models.CASCADE) start_date = models.DateField(default=datetime.date.today) end_date = models.DateField(default=datetime.date.today) unit_type = models.CharField(default='cpc', choices=UNIT_CHOICES, max_length=3) units = models.IntegerField(default=0) budget = models.IntegerField(default=0) budget_spent = models.IntegerField(default=0) units_delivered = models.IntegerField(default=0) def __str__(self): return str(self.publisher_name) -
Unexpected ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
Operational system: Ubuntu 16.04 Unexpectedly after normal working my MySQL server stopped and now when I enter mysql in command line it shows me this error: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) I use MySQL for my Django project and I don't understand how my Django code could influence on MySQL-server. I didn't change mysql config files for almost month of working on this project. So it's interesting what can be the reason of this error and how it should be solved. I think reinstalling of mysql-server is too hard measure for this. This is the error log: 2017-11-19T12:58:28.515850Z 0 [Note] Binlog end 2017-11-19T12:58:28.515884Z 0 [Note] Shutting down plugin 'CSV' 2017-11-19T12:58:28.515889Z 0 [Note] Shutting down plugin 'MyISAM' 2017-11-19T12:58:28.516156Z 0 [Note] /usr/sbin/mysqld: Shutdown complete 2017-11-19T12:58:58.826621Z 0 [Warning] Changed limits: max_open_files: 1024 (requested 5000) 2017-11-19T12:58:58.826691Z 0 [Warning] Changed limits: table_open_cache: 431 (requested 2000) 2017-11-19T12:58:58.997005Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details). 2017-11-19T12:58:58.998986Z 0 [Note] /usr/sbin/mysqld (mysqld 5.7.20-0ubuntu0.16.04.1) starting as process 30672 ... 2017-11-19T12:58:59.004058Z 0 [Note] InnoDB: PUNCH HOLE support available 2017-11-19T12:58:59.004079Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins 2017-11-19T12:58:59.004083Z 0 … -
Django how to add multiple entries in one put request
This is a question about the methods and ways to tackle the problem rather than the hard code. If you do want to give code answer, that would be welcome. For example, I have a sandwich shop with bulk online orders of sandwiches. Is there a way of doing multiple orders with one request to the server? i.e. Submit each sandwich in turn. Form page -> redirect page -> New Form page. How would you go about letting the client make multiple orders and once the user submits the multiple entry order, how to feed that into Django? Thank you for your time. -
upload image to a folder with model's title django
I am a newbie in django and I want to upload image in an ImageField to folder with the name of the title which is retrieved by a CharField and I get this error on the 8th line while trying to makemigrations: AttributeError: 'CharField' object has no attribute 'model' Here's the code: from django.db import models from django.contrib.postgres.fields import ArrayField class Starter(models.Model): title = models.CharField(max_length=200) price = models.IntegerField() description = models.TextField() image = ArrayField(models.ImageField(upload_to='starter/{}'.format(title)), size=10) class Meta: ordering = ('title', 'price',) def __str__(self): return self.title Anybody knows how to fix it? -
django storages aws s3 delete file from model record
I have based my django aws S3 solution on https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html. Now I am trying to find a way to delete a row in the model that contains the S3 file. I am able to delete the row with .delete() but it doesnt delete in S3. How do I make the delete row to also delete in S3 ? Below are my code: https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py @api_view(['POST']) def delete_employee(request): # ----- YAML below for Swagger ----- """ description: This API deletes employee parameters: - name: employee_id type: integer required: true location: form """ employee_id = request.POST['employee_id'] employee = Employee.objects.get(id = employee_id) logging.debug(f"API employee username {employee.username}") employee.delete() <-- here is where the delete row happens return Response("Employee Deleted!", status=status.HTTP_200_OK) https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee') company = models.ForeignKey(Company) username = models.CharField(max_length=30, blank=False) upload = models.FileField(blank=True) <--- S3 field https://gitlab.com/firdausmah/railercom/blob/master/railercom/settings.py (AWS settings) AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } DEFAULT_FILE_STORAGE = 'railercomapp.storage_backends.MediaStorage' https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/storage_backends.py from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = 'media/yy' file_overwrite = False -
mini-chat using dictionary
I am a beginner in python programming and I want to answer user's input from my dictionary. views.py from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import AnswerForm answer = {'Hi': 'Hello!', 'How are you?': 'I am fine'} def response(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = AnswerForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/thanks/') # if a GET (or any other method) we'll create a blank form else: form = AnswerForm() return render(request, 'answer/answer.html', {'form': form}) def index(request): return render(request, 'answer/index.html', answer) urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^', views.index, name='index'), url(r'^answer$', views.response, name='response'), ] forms.py from django import forms class AnswerForm(forms.Form): answer = forms.CharField(label='answer', max_length=100) index.html <form action="/answer/" method="post"> {% csrf_token %} <label for="answer"></label> <input id="answer" type="text" name="answer" maxlength="100" required /> </form> Also when i input something on input page I get csrf token error: CSRF verification failed. Request aborted./CSRF token missing or incorrect. I need … -
No module named django
When running: (DjangoProject) PS C:\Users\Travinns\Documents\GitHub\HBH site> django-admin.py startproject HBHsite I get the error: from django.core import management ModuleNotFoundError: No module named 'django' I followed this guide and it goes wrong at the 'Lets now create a our first Django project.' step. I already searched around and if I run the following: python -c "import sys; print('\n'.join(sys.path))" I get: C:\Users\Travinns\Envs\DjangoProject\Scripts\python35.zip C:\Users\Travinns\Envs\DjangoProject\DLLs C:\Users\Travinns\Envs\DjangoProject\lib C:\Users\Travinns\Envs\DjangoProject\Scripts c:\users\travinns\appdata\local\programs\python\python35-32\Lib c:\users\travinns\appdata\local\programs\python\python35-32\DLLs C:\Users\Travinns\Envs\DjangoProject C:\Users\Travinns\Envs\DjangoProject\lib\site-packages C:\Users\Travinns\Documents\GitHub\HBH site Django is in C:\Users\Travinns\Envs\DjangoProject\lib\site-packages so this should work. If I run: Python import django django I get: <module 'django' from 'C:\\Users\\Travinns\\Envs\\DjangoProject\\lib\\site-packages\\django\\__init__.py'> Which confirms my statement. What am I missing? Extra info: I am running on Windows. -
django rest framework: customize nested serializer
I have the following Django model structure: class TypeOfIngredient(models.Model): name = models.CharField(max_length=200,unique=True,null=False) slug = models.SlugField(unique=True) class Ingredient(models.Model): name = models.CharField(max_length=200,unique=True,null=False) slug = models.SlugField(unique=True) typeofingredient = models.ForeignKey(TypeOfIngredient, related_name='typeof_ingredient',null=True, blank=True,on_delete=models.PROTECT) Serializer: class IngredientListSerializer(ModelSerializer): class Meta: model = Ingredient fields = '__all__' With the above serializer i see the following api output: "results": [ { "id": 1, "name": "adrak", "slug": "adrak", "typeofingredient": null }, { "id": 2, "name": "banana", "slug": "banana", "typeofingredient": 1 }, How to get "typeofingredient": "fruit" where fruit is the name field of the typeofingredient. What i am getting is the id. I tried nested: class IngredientListSerializer(ModelSerializer): class Meta: model = Ingredient fields = '__all__' depth = 1 Then i get the api output as: "results": [ { "id": 1, "name": "adrak", "slug": "adrak", "typeofingredient": null }, { "id": 2, "name": "banana", "slug": "banana", "typeofingredient": { "id": 1, "name": "fruit", "slug": "fruit" } }, Here is showing all the details of the typeofingredient. Rather than this can i have directly "typeofingredient": "fruit" -
How to GET data by search word Django
I have problem getting the data to the home page. I would like to filter out all the books based on Genre. I'm following the MDN site for this. index.html {% extends "base_generic.html" %} {% block content %} <h1>Local Library Home</h1> <p>Welcome to <em>Local Library</em>, a very basic Django website.</p> <h2>Dynamic content</h2> <form action="" method="get"> <input type="text" name="genre" placeholder="Search"> <input type="submit" value="Search"> </form> {% endblock %} urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^books/$', views.BookListView.as_view(), name='books'), url(r'^(?P<string>[-\w]+)$', views.GenreListView.as_view(), name='index'), ] GenreListView class class GenreListView(generic.ListView): model = Book def get(request, string): try: book = Book.objects.all().filter(genre=string) except Book.DoesNotExist: raise Http404("Book does not exist") return render( request, 'index.html', context={'book': book,} ) I can't figure out what I'm missing or what else I have to do to get all the date based on genre? -
3-legged authorization for twitter in django
I try to make a 3-legged authorization in django with twitter, but my code doesn't work. I get an error massage that says "invalid oauth_verifier parameter" Does anyone have an idea of what I am doing wrong? I think there is something wrong with: resp, content = client.request(access_token_url, "POST") but I don't know what. In my view.py: def settings(request): consumer_key = "xxx" consumer_secret = "xxx" request_token_url = 'https://api.twitter.com/oauth/request_token' access_token_url = 'https://api.twitter.com/oauth/access_token' authorize_url = 'https://api.twitter.com/oauth/authorize' consumer = oauth.Consumer(consumer_key, consumer_secret) client = oauth.Client(consumer) resp, content = client.request(request_token_url, "GET") request_token = dict(cgi.parse_qsl(content)) url_name = "%s?oauth_token=%s" % (authorize_url, request_token['oauth_token']) form = forms.PinForm() user = request.user if request.method == 'POST': form_value = forms.PinForm(request.POST) oauth_verifier = form_value['pin'].value().strip() token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret']) token.set_verifier(oauth_verifier) client = oauth.Client(consumer, token) resp, content = client.request(access_token_url, "POST") access_token = dict(cgi.parse_qsl(content)) print "Access Token:" print access_token return HttpResponseRedirect("/") return render(request, 'test/settings.html' , {'form': form, 'url_name': url_name}) in my settings.html: {% include "test/head.html" %} <div class="container"> <br> </div> <div> <a href="{{ url_name }}" target="_blank">Get Pin from Twitter</a> <br><br> <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Send Pin" name='Pin'> </form> </div> -
How to deploy django with media files?
I am trying to find a simple solution to deploy a django rest api which uses media files which are added via the admin panel. The rest api will be receiving very low traffic and so the simplest cheapest option is preferable. Currently, I am using heroku, however when I add media files through the admin panel and come back to it later the files are no longer there. Here is my settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '****' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['example.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'clothing', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAdminUser', ], 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ), 'DEFAULT_THROTTLE_RATES': { 'anon': '400/day', 'user': '500/day' } } ROOT_URLCONF = 'good_deal.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, … -
Django CreateView - Display only particular objects in foreignkey field
I have a CreateView view that has a bunch of fields that need to be filled by the user when creating a new contact. Now, I want the user to be able to see and choose only from the categories that they'd created. This is the model of Category: class Category(models.Model): class Meta: verbose_name = _('category') verbose_name_plural = _('categories') name = models.CharField(max_length=100, unique=True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) def __unicode__(self): return self.name This is the view: class ContactCreate(LoginRequiredMixin, generic.edit.CreateView): model = models.Contact success_url = reverse_lazy('site:contacts') fields = ['firstname', 'lastname', 'phone1', 'phone2', 'email', 'city', 'category'] template_name = 'site/contacts.html' context_object_name = 'all_contacts' What I need the user to see is a select that has only the categories which include the appropriat profile foreignkey associated with them. I'd be glad to get some help with this. Thank you! -
can't started server for django i'm new in django and interpreter is pycharm
can't start my server for django project i'm using pycharm and faced several issues . further in pictureterminal with commands -
How to relate two object lists?
I have two models related them with a foreign key, pregunta is a question to a especific Comentario (comment). models.py class Comentario (models.Model): titulo = models.CharField(max_length=50) texto = models.CharField(max_length=200) autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE) fecha_publicacion = models.DateTimeField(auto_now_add=True) tag = models.ManyToManyField(Tags, blank=True) def __str__(self): return (self.titulo) class Pregunta (models.Model): descripcion = models.CharField(max_length=150) autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE) fecha_pregunta = models.DateTimeField(auto_now_add=True) comentario_preguntado = models.ForeignKey(Comentario, null=True, blank=True) def __str__(self): return (self.descripcion) I create a view where I want to show only the comments having a question and the questions itself. I create two object list, one with the comments and the other with questions. The problem is that I want to show in the template the first comment and its questions, then the next comment and its questions... I do not know if this should be done in the template or I need to change my view. views.py def responder(request): comment = Comentario.objects.filter(id__in=Pregunta.objects.all().values_list('comentario_preguntado')).filter(autor=request.user) question = Pregunta.objects.filter(comentario_preguntado__in=comment) return render(request, 'home/responder.html', {'comment': comment, 'question': question}) -
How to get inline model in post_save instance (Django Signals)?
I'm using Django (1.11.7) and Signals for some actions on the newly saved model (sending a message to the mail with the info from the model, basically). But only I add to this model one more, connected (ForeignKey) with the main (as inlines=[...] in admin.py) — it does not participate in saving the instance of the main model. My model is: # /tours/models.py class Tours(models.Model): country = models.CharField(...) ... class ToursHotels(models.Model): tour = models.ForeignKey(Tours, ...) cost = models.IntegerField(...) ... @receiver(post_save, sender=Tours) def do_something(sender, **kwargs): tour = Tours.objects.get(id=kwargs.get('instance').id) hotels = ToursHotels.objects.filter(tour_id=tour.id).order_by('cost') ... So, hotels will be empty until I edit this record again. How to do it better? Help me please. -
Reading published python code
I am learning python and django and my friend from school told me I should be worried about obfuscating my project I'm about to deploy.. Is it possible to read published django code? Specifically my views? If so, how? -
Django REST framework: HTML render Generic APIView
I am new to Django REST Framework. What I try to do is to render a Generic APIView (RetrieveUpdateDestroyAPIView) in HTML similarly to the way the ViewSet is automatically rendered in the Browsable API. Following the official documentation, I have in my myApp/views.py: class AnnounceViewSet(viewsets.ModelViewSet): """ API endpoint that allows announces to be viewed or edited. """ queryset = Announce.objects.all() serializer_class = AnnounceSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) def perform_create(self, serializer): # without this, the POST request of the announce doesnt work serializer.save(owner=self.request.user) class AnnounceList(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'myApp/announces_list.html' permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def get(self, request): queryset = Announce.objects.all() return Response({'announces': queryset}) class AnnounceDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Announce.objects.all() serializer_class = AnnounceSerializer renderer_classes = [TemplateHTMLRenderer] template_name = 'myApp/announce_detail.html' permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) In my urls.py: from django.conf.urls import url, include from rest_framework import routers from myApp import views from django.contrib import admin router = routers.DefaultRouter() router.register(r'api/users', views.UserViewSet) router.register(r'api/groups', views.GroupViewSet) router.register(r'api/announces', views.AnnounceViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('myApp.urls')), url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^accounts/', include('allauth.urls')), url(r'^announces/$', views.AnnounceList.as_view(), name='announces-list'), url(r'^announces/(?P<pk>[0-9]+)/$', views.AnnounceDetail.as_view(), name='announce-detail'), When I go the Brwowsable API, through the link /api/announces/3/, I can …