Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Youtube API v3 batch request Channels.list Python
I can get the sample code working for channels.list but in the parameters you are limited to fewer than 50 channel IDs. Firstly can I write the channel IDs in a separate file or do I have to paste them all in which would look incredibly ugly with hundreds of channel IDs separated by commas? Secondly, precisely how do I write a batch request for multiple channels.list requests? My basic intent is to get statistics like subscriber counts of a list of youtube channels and subsequently place the json data into a postgres database (I've set the database up fine). -
Hide Django built-in UserCreationForm verifications, and show them when the user fills invalid data
I don't want to display the verifications neither username nor password until a user fills invalid data, how can I do that ?! Here is my user form in forms.py : class UserForm(UserCreationForm): class Meta(): model = User fields = ('username','first_name','last_name','email','password1','password2',) def save(self,commit=True): user = super(UserForm,self).save(commit=False) user.username = self.cleaned_data["username"] user.email = self.cleaned_data["email"] user.first_name = self.cleaned_data["first_name"] user.last_name = self.cleaned_data["last_name"] user.password1 = self.cleaned_data["password1"] user.password2 = self.cleaned_data["password2"] if commit: user.save() return user def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = 'Username' self.fields['first_name'].label = 'First Name' self.fields['last_name'].label = 'Last Name' self.fields['email'].label = 'Email Address' self.fields['password1'].label = 'Password' self.fields['password2'].label = 'Re-enter Password' and here is my registration function : def register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password1) user.save() c_user = user_form.instance.id profile = profile_form.save(commit=False) profile_form.instance.userid = AuthUser(c_user) profile.save() if 'profilepic' in request.FILES: profile.profilepic = request.FILES['profilepic'] profile.save() registered = True else: print(user_form.errors) print(profile_form.errors) else: user_form = UserForm profile_form = UserProfileForm return render(request,'registration/register.html',{'user_form':user_form,'profile_form':profile_form,'registered':registered}) -
Django / Python JSON / GEOJSON string format
I use the following script to serialize the queryset coming from the view it's called from: def json_to_model(object_list): line_json = [] for obj in object_list: #<flight queryset> geojson = [] route = re.split('\W+', obj.route) #separate individual codes for code in route: #XXXX, XXXX, XXXX map_obj_route = [] feature = {"type":"Feature","properties":{"icao": "","iata": "", "name": "", "city": "", "state": "", "country": "", "elevation": ""},"geometry":{"type":"Point","coordinates":['','']}} if code == '': pass else: iata_kwargs = {'iata' : code} icao_kwargs = {'icao' : code} map_object = (MapData.objects.filter(**iata_kwargs) | MapData.objects.filter(**icao_kwargs)).first() map_obj_route.append(map_object) feature["properties"]["icao"] = map_object.icao feature["properties"]["iata"] = map_object.iata feature["properties"]["name"] = map_object.name feature["properties"]["city"] = map_object.city feature["properties"]["state"] = map_object.state feature["properties"]["country"] = map_object.country feature["properties"]["elevation"] = map_object.elevation feature["geometry"]["coordinates"] = [map_object.longitude, map_object.latitude] geojson.append(feature) geojson = ((str(geojson).strip('[]'))) obj.geojson = geojson obj.save() This is the resulting contents of obj.geojson: {'type': 'Feature', 'properties': {'icao': 'KORD', 'iata': 'ORD', 'name': "CHICAGO O'HARE INTL", 'city': 'CHICAGO', 'state': 'IL', 'country': 'United States', 'elevation': 680}, 'geometry': {'type': 'Point', 'coordinates': [-87.90800591666667, 41.97732013888889]}}, {'type': 'Feature', 'properties': {'icao': 'KLAS', 'iata': 'LAS', 'name': 'MC CARRAN INTL', 'city': 'LAS VEGAS', 'state': 'NV', 'country': 'United States', 'elevation': 2181}, 'geometry': {'type': 'Point', 'coordinates': [-115.15225000000001, 36.08005555555556]}} I'm using a helper function to assemble the obj.geojson into a list of variable length depending on the queryset provided by the view … -
CSRF token requirements
I'm looking at a (possibly robust) implementation of OAuth2 which seems to require the session to have an existing token when signing in. Also, the request's token needs to match the session's existing token. Are these meant to be normal requirements? When a user is signing in (e.g., for the first time), neither the request or the session would have a token. How come some token is needed to sign in? Here's the snippet in question: def complete_oauth2_signin(request): next_url = get_next_url_from_session(request.session) if 'error' in request.GET: return HttpResponseRedirect(reverse('index')) csrf_token = request.GET.get('state', None) oauth2_csrf_token = request.session.pop('oauth2_csrf_token', None) if csrf_token is None or csrf_token != oauth2_csrf_token: return HttpResponseBadRequest() -
URL configuration and 404 error
I'm working on a personal Django project and I have 404 error, but I can't figure out why. I tried the following configuration: Urls.py url(r'composer/(?P<slug>.+)$', views.articles_plats_composer, name='articles_plats_composer'), My views: def articles_plats_composer(request, slug): sous_categories_articles = get_object_or_404(Sous_Categories_Article, slug=slug) articles = sous_categories_articles.article_set.all() return render(request, "commander-suite-composer.html",{'sous_categories_articles':sous_categories_articles, 'articles':articles}) And my templates: <a href="{% url 'articles_plats_composer' article.slug %}"></a> With this configuration it works. When i tried with only an id, it works (same kind of code). But when, I try to have a slug and id url with the following code, I get 404 error. My URLs file url(r'composer/(?P<slug>.+)-(?P<id>\d+)$', views.articles_plats_composer, name='articles_plats_composer'), My views: def articles_plats_composer(request, slug, id): sous_categories_articles = get_object_or_404(Sous_Categories_Article, slug=slug, id=id) articles = sous_categories_articles.article_set.all() return render(request, "commander-suite-composer.html",{'sous_categories_articles':sous_categories_articles, 'articles':articles}) And my templates: <a href="{% url 'articles_plats_composer' article.slug article.id %}"></a> I don't understand why, separately, it works, but when i combine them, it doesn't work... Thank you in advance for your help Singertwist -
Django error: "didn't return an HttpResponse object"
I want to test a performance of my WebSite. I developed a Django Project, and i still using the internal webserver of Django. I have a page which request a data from webserver with a fix time interval. I do this with ajax. It's working fine. Code bellow: $.ajax({ type: 'GET', url: 'refresh', success: function(data){ //refresh the display data } }); In a django view, a process code and return a JsonResponse: def refresh(request): if request.is_ajax(): reg = Registers.objects.latest('pk') opmode = OperationMode.objects.latest('pk') opdata = reg.serialize() opdata['OpMode'] = opmode.OpMode opdata['TrendStarted'] = opmode.TrendStarted return JsonResponse(opdata,safe=False) The question is: when i type http://endpoint/operation/referesh in REST request in SOAPUI the Django returns: "The view WebSite.operation.views.refresh didn't return an HttpResponse object. It returned None instead" I want receive a JSONResponse returned of Django. How i make this request in SOAPUI? -
How can I select the user with two different cases in the same two columns
Given a table below, how can I select the user with a first language of en and secondary of ja using django filter? I have to get the users without duplicates. So below, I'm expecting to get uid 1 and 3. id uid is_first en 1 true jp 1 false jp 2 true en 2 false en 3 true jp 3 false es 3 true Here's my attempt but it returned empty. UserLanguage.objects.filter((Q(language_in=['en'], is_first=True) & Q(language_in=['jp'], is_first=False)) I tried to do it from the User with the lookup in but empty results. User.objects.filter((Q(user__languages__language__in=['en'], user__languages__is_first=True)) & (Q(user__languages__language__in=['jp'], user__languages__is_first=False)) -
Onelogin with Django: Receiving a GET when I would expect a POST
I followed the tutorial to deploy single sign-on with OneLogin over my Django app and when I click on the login button, the request I receive from OneLogin is not a POST as expected, but a GET. Then the library raises a OneLogin_Saml2_Error: "SAML Response not found, Only supported HTTP_POST Binding". At this moment I am stuck since the documentation doesn't give any useful information on this, so I would welcome any tips. -
How to get all objects based on date in Django
I have 3 simple models in my application: class Product(models.Model): name = models.CharField(max_length=200) price = models.IntegerField(default=0) class Order (models.Model): date = models.DateField(blank=True) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True ) product = models.ManyToManyField(Product) quantity = models.PositiveIntegerField(default=0) I have many orders with the same date, like this: 1. 2017-11-09 | Apples | 5$ 2. 2017-11-09 | Bananas | 2$ 3. 2017-11-09 | Pears | 3$ As you can see, there is actually one order (based on the date) with 3 different products. How can I get that single order with all of its products and prices? So the end result would be something like this: 2017-11-09 | Apples | 5$ | Bananas | 2$ | Pears | 3$ I'm using sqllite3 -
How to translate django User?
I found questions about how to use translation and how to rewrite django User model, but I want just to translate django User, not rewrite at all. How could I do this? -
Django: restrict user access to their own objects only
Im' using @ligin_required to force users to authenticate before they create any object. but the problem is all authenticated user has access to update objects by object pk, even objects which created by other users.how can I limit user to access to their own objects only? -
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 …