Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 1.8 + DRF 3.4 + Django Filters 1.0.1 Won't Work on ViewSets Methods
I'm trying to use django-filters with django-rest-framework to implement get/url/params based filters, but it won't work with viewsets and shows no error. If I use a generics.ListAPIView for example, the filter works flawlessly! My project code: Models.py class OrderFeedBack(BaseModel): """ Receive the customer rating, vendor and staff feedback about a order. Once the vendor or the customer has written his feedbacks, they can't change it. Developer: gcavalcante8808 """ rating = models.IntegerField() customer_feedback = models.CharField(max_length=255, null=True, blank=True) vendor_feedback = models.TextField(null=True, blank=True) staff_feedback = models.TextField(null=True, blank=True) order = models.ForeignKey("Order") locked = models.BooleanField(default=False) Filters.py class OrderFeedBackViewSet(viewsets.ViewSet): authentication_classes = (TokenAuthentication, SessionAuthentication) permission_classes = (IsAuthenticated,) filter_class = (OrderFeedBackFilter,) filter_backend = (filters.DjangoFilterBackend,) filter_fields = ('id', 'locked') search_fields = ('id', 'order',) def list(self, request): """ List all Order Feedbacks. --- serializer: app.api_v1.serializers.OrderFeedBackSerializer omit_serializer: false responseMessages: - code: 401 message: AuthenticationNeeded - code: 200 message: List of Feedbacks. """ data = OrderFeedBack.objects.all() serializer = OrderFeedBackSerializer(data, many=True) return Response(serializer.data) Serializers.py class OrderFeedBackSerializer(serializers.ModelSerializer): order = serializers.PrimaryKeyRelatedField(queryset=Order.objects.all()) class Meta: model = OrderFeedBack Even, if I drop the FieldSet class from "filter_class" or try to use "filter_class = OrderFeedBackFilter" it won't works as well.I have the following libraries installed in my virtualenv (and setUp in my settings.py): Django==1.8.18 DjangoRestFramework==3.3 Django-Filters==1.0.1 Django-Crispy-Forms I'm … -
template does not exist at /(given url)
>it worked on localhost but in production it is showing this error,plz someone resolve it. TemplateDoesNotExist at /tcapp/tcpage app/urls.py ` from django.conf.urls import url from .import views urlpatterns = [ url(r'^tcapp/tcpage', views.tcpage, name='tcpage'), url(r'^tcapp/tcappretrive', views.tcappretrive, name='tcappretrive'), url(r'^tcapp/home',views.tcpage,name='tcpage'), url(r'^tcapp/work',views.work,name='work'), url(r'^tcapp/s&c',views.support,name='support'), ] templates: home.html work.html s&c.html` TemplateDoesNotExist at /tcapp/tcpage. -
Converting Django model data to variables usable in Javascript
I am new to programming and to SO. I have a question about developing with Django / Python. I am trying to use django variables into a javascript script. My model is like this: class Business(models.Model): business_name = models.CharField(max_length=200) lat = models.FloatField(default=0) lng = models.FloatField(default=0) I am creating a Django app that sends the businesses data to a template def index(request): business_list = Business.objects.all() context = {'business_list': business_list} return render(request, 'kitemap/index.html', context) I would like to transform the list of django objects into a list of objects usable in javascript but i can't manage to do so...i tried the code below but did not work. Could you please help? Thanks for (var i = 0; i < {{ business_list|length }}; i++) { var school = []; business[0] = {{ business_list.i.lat }}; business[1] = {{ business_list.i.lng }}; business[2] = {{ business_list.i.business_name }}M businesses[i] = business; } -
Setting session variables vs setting variable in browser cookie (Django app)
I need to clear a concept. I'm tracking unauthenticated users in my Django web app via setting a temp_id that's set in the request.session dictionary as soon as a new user hits the web app's landing page. The code is is simply: temp_id = request.session.get('temp_id',None) if not temp_id: request.session['temp_id'] = get_temp_id() So far so good. Apart from saving a temp_id in request.session, another technique I could have used is setting a browser cookie explicitly for unauthenticated users like so: if not request.session.exists(request.session.session_key): request.session.create() The concept I'd like to clarify is are these approaches equivalent? I feel they are. My reasoning is that a browser cookie is merely a reference to a Session stored in the DB. And if cookies were turned off, matching a Session for that user would be impossible. Thus, regardless of whichever approach I take, I'll be relying on the browser's ability to store a cookie. Or in other words, both methods of allotting a temp_id to an unauthenticated user are, under the hood, quite similar. The only difference is that browser cookies are less secure than session variables. Can someone point out whether this line of thinking is correct? Or is my approach wrong? I'm essentially … -
Django time convert format
I am trying to convert time into specific format using following code: datetime.datetime.strptime(timezone.now() + timedelta(days=14), '%Y-%m-%dT%H:%M:%S.%f%z') I am getting error that the first parameter has to be string. I also tried using this code datetime.datetime.strptime(str(timezone.now() + timedelta(days=14)), '%Y-%m-%dT%H:%M:%S.%f%z') But then I am getting following error: time data '2017-06-04 14:26:18.941458+00:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z' Can someone suggest how can I convert to the specific format. Thanks! -
Saving file created inside the view to the backend (Django)
I have the following model : def upload_to(instance, filename): return os.path.join('/%s/' % instance.user.username, filename) class UserAudioAnswer(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) question = models.ForeignKey(Question) audio_file = models.FileField(upload_to=upload_to) translated_english_answer = models.TextField(null=True, blank=True) my_points = models.IntegerField(default=-1) def __unicode__(self): return self.question.text Inside my view I am recording an audio file from the user as follows: def start_recording(r,request): print("Reached start recording metho. About to start recording") with sr.Microphone() as source: print("Say something!") audio = r.record(source,duration=5) return audio My MEDIA_ROOT is defined as below: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_in_env", "media_root") So in this media_root folder I have to create a folder with the user name and then save the file inside it. I created the upload_to function to save my file there. I have done the following: 1) user_audio_answer = UserAudioAnswer() user_audio_answer.audio_file.save = (random_file_name,File(f)) user_audio_answer.audio_file = settings.MEDIA_ROOT+"/"+request.user.username+"/"+random_file_name+".flac" but it does not save anything. 2) user_audio_answer.audio_file = settings.MEDIA_ROOT+"/"+request.user.username+"/"+random_file_name+".flac" It saves the path of the file but the path starts from /Users/username/desktop and it goes on. What is the correct way to save the file to my backend, the way I am doing it?` -
Django - can not send email to multiple recipients
I'm trying to send mail to multiple recipients but I keep getting this error validation: I'm using django-multi-email-field package and not certain this solution would help. Please, see where I went wrong and guide me the right way. Really appreciate your help! Django: 1.10 and Python: 3.6 mail.py from multi_email_field.forms import MultiEmailField class mailHandler(forms.Form): subject = forms.CharField(required=False) receiver = MultiEmailField(label='Send to') message = forms.CharField(widget=forms.Textarea(attrs={'cols': 50}), required=False) def __init__(self, *args, **kwargs): super(mailHandler, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_class = 'form' self.helper.layout = Layout( Field( None, Div( HTML(''' {% if messages %} {% for message in messages %} <center><p {% if message.tags %} class="alert alert-{{ message.tags }}" {% endif %}>{{ message }} <button type="button" name="message" class="close" data-dismiss="alert" aria-hidden="true">&times;</button></p> </center>{% endfor %}{% endif %} '''), Div('subject', Field('receiver', placeholder='Email address', required=True), 'message', FormActions( Submit('submit', 'Send', css_class='btn btn-lg btn-block'), ), ), ), ), ) views.py class mailPost(FormView): success_url = '.' form_class = mailHandler template_name = 'post/post.html' def form_valid(self, form): messages.add_message(self.request, messages.SUCCESS, 'Email Sent!') return super(mailPost, self).form_valid(form) def form_invalid(self, form): messages.add_message(self.request, messages.WARNING, 'Email not sent. Please try again.') return super(mailPost, self).form_invalid(form) def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): sender = "noreply@domain.com" receiver = form.cleaned_data.get('receiver') subject = form.cleaned_data.get('subject') … -
How to load 2 datamaps in a single HTML page?
I have been trying to use datamaps with django but the problem is that whenever I try to load more than one datamap it throws an error stating Uncaught TypeError: Cannot read property 'world' of undefined It seems that the js does not know which js file to use for which scope. Currently my code for world is var series1 = {{ mapContainer.0|safe }} var dataset1 = {}; var onlyValues1 = series1.map(function(obj){ return obj[1]; }); var minValue1 = Math.min.apply(null, onlyValues1), maxValue1 = Math.max.apply(null, onlyValues1); var paletteScale1 = d3.scale.linear() .domain([minValue1,maxValue1]) .range(["#000000","#FF0000"]); series1.forEach(function(item) { var iso1 = item[0], value1 = item[1]; dataset1[iso1] = { numberOfThings: value1, fillColor: paletteScale1(value1) }; }); new Datamap({ element: document.getElementById('international_map'), projection: 'mercator', scope: 'world', responsive: true, fills: { defaultFill: '#F5F5F5' }, data: dataset1, geographyConfig: { borderColor: '#000000', highlightBorderWidth: 2, highlightFillColor: function(geo) { return geo['fillColor'] || '#F5F5F5'; }, highlightBorderColor: '#fc0000', popupTemplate: function(geo, data) { if (!data) { return ; } return ['<div class="hoverinfo">', '<strong>', geo.properties.name, '</strong>', '<br>Count: <strong>', data.numberOfThings, '</strong>', '</div>'].join(''); } } }); And my country specific code is like this var series2 = {{ mapContainer.1|safe }} var dataset2 = {}; var onlyValues2 = series2.map(function(obj){ return obj[1]; }); var minValue2 = Math.min.apply(null, onlyValues2), maxValue2 = Math.max.apply(null, onlyValues2); var … -
Django Url Redirection
I have a problem with my project & I hope that you will help me figure it out.The main problem is that my project is a one-single page template, so I don't have so many views , but I want to know , how to redirect to my homepage from django.conf.urls import url from django.contrib import admin from iubestete import views as iubestete_views urlpatterns = [ url(r'^$', iubestete_views.index), url(r'^',iubestete_views.index,name="portal"), url(r'^admin/', admin.site.urls), ] here is my urls.py file , which function should I import or what should I do? I mean, I want to know for example, if a person types "http://127.0.0.1:8000/adsnjiwadi/" ,how can I redirect that link to my homepage(index.html)?Thank you so much & I hope that you'll have a great day:) Peace:) -
How can i serialize manytomany django models using DRF
How can i get products name and id instead of pro_id and ord_id in output ? but not in string type. for example : "name : somebook" is not a valid option for me. I just working on this for 2 days without break and i think im missing a little detail but i cant find what is it. Output i want [ { "order_id": 1, "totalquantity": 12, "totalprice": 56, "userid": 1, "customerAddress": "evka1", "customerPhone": "539", "trackNo": 12034, "products": [ { "name": "somebook", "id": 1, "quantity": 6 }, { "name": "someotherbook", "id": 2, "quantity": 6 } ] } ] Output i get [ { "order_id": 1, "totalquantity": 12, "totalprice": 56, "userid": 1, "customerAddress": "evka1", "customerPhone": "539", "trackNo": 12034, "products": [ { "pro_id": 2, "ord_id": 1, "quantity": 6 }, { "pro_id": 3, "ord_id": 1, "quantity": 6 } ] } ] Order model class Order(models.Model): order_id = models.AutoField(primary_key=True) totalquantity = models.IntegerField(default=0, null=True) totalprice = models.IntegerField(default=0, null=True) userid = models.IntegerField(default=0, null=True) trackNo = models.IntegerField(default=0, null=True) billNo = models.IntegerField(default=0, null=True) customerAddress = models.CharField(max_length=30,default="nil", null=True) customerPhone = models.CharField(max_length=30,default="nil", null=True) Order Serializer class OrderSerializer(serializers.ModelSerializer): products = ProductOrderSerializer(many=True, read_only=True) class Meta: model = Order fields = ('order_id', 'totalquantity', 'totalprice', 'userid', 'customerAddress', 'customerPhone', 'trackNo', 'products') Product Model class … -
How can I put XML in a HTML template? python/Django
I want to put my variable user_serialized_xml in my HTML template, but I am not sure how can I do it :/ This is my views.py > def user_xml(request): > context = {} > > user_serialized_xml = serializers.serialize("xml", Usuario.objects.all()) > context['user_serialized_xml'] = user_serialized_xml > return render_to_response('profile_xml.html', context) And this is my HTML template (yes, really short!): <!DOCTYPE html> {{{user_serialized_xml}} It gives me this error: Could not parse the remainder: '{user_serialized_xml' from '{user_serialized_xml' Thank you! -
JQUERY, select ID
Generally we create a form. By the 'add-question-btn' i add a new question to a form. We can add at once a lot of questions, as a an owner (author) we have to decide what is a 'type' of answers by selecting from dropdown list. var num_question_options = [0]; var num_questions = 1; $('#add-question-btn').click(function () { $('.questions').append( '<div class="questions-div" id="question-' + num_questions + '">' + '<label id="question-label" for="question-text">id:' + num_questions + '</label>' + '<input class="form-control" id="question-text" type="text" placeholder="Pytanie"/>' + '<div class="select-select-type">' + '<div class="dropdown">' + '<select title="type" class="select-type form-control" id="select-' + num_questions + '">' + '<option value="text">Krótka odpowiedz</option>' + '<option value="radio">Wielokrotny wybór</option>' + '<option value="checkbox">Pola wyboru</option>' + '<option value="menu">Menu</option>' + '<option value="scale">Skala liniowa</option>' + // tego na razie nie bedzie // '<option value="table">Siatka wielokrotnego wyboru</option>' + '<option value="date">Data</option>' + '<option value="hour">Godznia</option>' + '</select>' + '</div>' + '<ul id="answers" class="list-unstyled"></ul>' + '</div>' ); num_question_options[num_questions] = 0; num_questions++ }); Depending on selected answer type we should receive a place for typing possible answers (as author). This is my function detecting a change in selected option. The problem is: How to find in select ID inside that function to know to which question sth should be appended. $(document).on('change','select',function(){ var select_val = this.value; var … -
Save several images with form in django
Whats the best way to save several images in django? I have Article modal with 2 fields: description and image. I tried next code but my currect form allows user to upload only one image file. I need form where user can create article with several images. Maybe someone can advice good examples or apps. I would be very grateful for any help. models.py: class Article(models.Model): description = models.TextField(_('Description')) image = models.FileField(upload_to='images//%Y/%m/%d/') forms.py: class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ('description', 'image') views.py: def article_add(request): data = dict() if request.method == 'POST': article_form = ArticleForm(request.POST, request.FILES) if article_form.is_valid(): article = article_form.save(commit=False) ****** article.save() data['form_is_valid'] = True articles = Article.objects.all context = {'articles': articles} context.update(csrf(request)) data['html_article'] = render_to_string('project/article_list.html', context) else: data['form_is_valid'] = False else: article_form = ArticleForm() context = {'article_form': article_form} data['html_article_form'] = render_to_string('project/article_add.html', context, request=request) return JsonResponse(data) article_add.html: {% load widget_tweaks %} <form method="post" action="{% url 'article_add' %}" class="article-add-form dropzone"> {% csrf_token %} {% for field in article_form %} <div class="form-group{% if field.errors %} has-danger{% endif %}"> <label class="form-control-label" for="{{ field.id_for_label }}">{{ field.label }}</label> {% render_field field class="form-control" %} {% for error in field.errors %} <div class="form-control-feedback">{{ error }}</div> {% endfor %} </div> {% endfor %} <button type="submit">Submit</button> … -
Enable CORS in Django 1.11
I am using Django 1.11 and it seems that the python module django-cors-headers is till Django 1.10. In the Django documentation, they mention to use this module or write custom middleware. I did not find any information online about writing cors middleware for Django 1.11 and the examples for previews versions did not work. Any ideas? Thank you! -
Django two tables join without foreign key defined in models
I am having two tables Prop and Location and App name is property. I tried joining two tables like this. joined = Prop.objects.all().extra(tables=["property_location"], where=["project = p_name OR alias LIKE '%' || project || '%'"]) But I am getting columns only from prop table. I want all the columns for both the tables. The raw sql query mentioned below is working fine, but I need the ORM query for the same SELECT * from property_prop INNER JOIN property_location ON property_prop.project = property_location.p_name OR property_location.alias LIKE '%' || property_prop.project || '%' -
Elasticsearch dsl Term Filter not working with string Field
I am trying to apply term filter elastic search index data using elasticsearch_dsl python client but it's not working with string field. This is my ES index data: s = Search(using=es, index='idx_object', doc_type='ip').source(include=['id', 'status', 'username']) [{u'_score': 1.0, u'_type': u'ip', u'_id': u'79', u'_source': {u'status': u'PUBLISHED', u'username': u'jackie@example.com', u'id': 79}, u'_index': u'idx_object'}, {u'_score': 1.0, u'_type': u'ip', u'_id': u'84', u'_source': {u'status': u'PUBLISHED', u'username': u'julia@example.com', u'id': 84}, u'_index': u'idx_object'}, {u'_score': 1.0, u'_type': u'ip', u'_id': u'73', u'_source': {u'status': u'PUBLISHED', u'username': u'brad@example.com', u'id': 73}, u'_index': u'idx_object'}, {u'_score': 1.0, u'_type': u'ip', u'_id': u'82', u'_source': {u'status': u'PUBLISHED', u'username': u'julia@example.com', u'id': 82}, u'_index': u'idx_object'}, {u'_score': 1.0, u'_type': u'ip', u'_id': u'65', u'_source': {u'status': u'PUBLISHED', u'username': u'george@example.com', u'id': 65}, u'_index': u'idx_object'}, {u'_score': 1.0, u'_type': u'ip', u'_id': u'78', u'_source': {u'status': u'PUBLISHED', u'username': u'julia@example.com', u'id': 78}, u'_index': u'idx_object'}, {u'_score': 1.0, u'_type': u'ip', u'_id': u'62', u'_source': {u'status': u'PUBLISHED', u'username': u'brad@example.com', u'id': 62}, u'_index': u'idx_object'}, {u'_score': 1.0, u'_type': u'ip', u'_id': u'96', u'_source': {u'status': u'PUBLISHED', u'username': u'brad@example.com', u'id': 96}, u'_index': u'idx_object'}, {u'_score': 1.0, u'_type': u'ip', u'_id': u'70', u'_source': {u'status': u'PUBLISHED', u'username': u'brad@example.com', u'id': 70}, u'_index': u'idx_object'}, {u'_score': 1.0, u'_type': u'ip', u'_id': u'80', u'_source': {u'status': u'PUBLISHED', u'username': u'george@example.com', u'id': 80}, u'_index': u'idx_object'}] Now if I apply a filter in id integer field it's working. s = Search(using=es, … -
Error with collectstatic while deploying Django app to Heroku
I'm trying to deploy a Django app to Heroku, it starts to build, download and installs everything, but that's what I get when it comes to collecting static files remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 199, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 115, in collect remote: for path, storage in finder.list(self.ignore_patterns): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 112, in list remote: for path in utils.get_files(storage, ignore_patterns): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/utils.py", line 28, in get_files remote: directories, files = storage.listdir(location) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 397, in listdir remote: for entry in os.listdir(path): remote: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_955b171c774667db8cab1dfc1ff5a690/staticfiles' remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: … -
Cannot load static JS and CSS files in Django Project with GAE
I'm following instructions for a Django app from the link: https://cloud.google.com/python/django/flexible-environment My deployed (flex environment) app is successfully able to run, fetch all static images from the Cloud Storage bucket, however the JS and CSS files won't load. When I right click on my .html files, I can see the links are correct, e.g.: <link href='http://storage.googleapis.com/<BUCKET>/static/rest_framework_swagger/css/print.css' media='print' rel='stylesheet' type='text/css'/> If I manually paste this link into the browser, it loads the file just fine. Like I said, the static images are accessible but the CSS and JS files are not. Any idea what I need to do? -
Django CSRF Verification failed for admin panel
I started a fresh Django 1.11 project with one app, one model and one admin panel. Locally, everything works. When I deploy it to Amazon EC2 and try to log in to the admin panel, I get a 403 (CSRF verification failed. Request aborted.). I inspected with Chrome's network utility the request, and I noticed that in my Request Header I have: Cookie:csrftoken=hFhzOJPMOhkNWWWfRtlMOEum9jXV8XXWnOtw3OwZm2En9JUqYRVq632xyZfwSpzU while in my Form Data I have: csrfmiddlewaretoken:RHNpPfOHhg42FZnXmn9PZgNm3bN40C41XQZm4kvUP1oCSMl8tLJthFlxsR5FK4GZ Should these two be the same? In my understanding they do, but when I try the same in my local environment, I see they're also not the same, but there it is working fine and I get the same token back in the Response Header as was sent in the Request Header, so I assume they don't need to be exactly the same? Note: I do not have a secure connection (https) at the moment, but will work on that after this is fixed. I already tried/checked the following: Setting CSRF_COOKIE_DOMAIN (http://stackoverflow.com/a/42115353/1469465) Clear all cookies in my browser (http://stackoverflow.com/a/29574563/1469465) The variable CSRF_COOKIE_SECURE is not set and hence False (http://stackoverflow.com/a/29574563/1469465) My favicon is loaded correctly (http://stackoverflow.com/a/42021886/1469465) I have a DNS pointing to my EC2 instance, and have that subdomain in … -
Why do Django have too many login redirects when using @login_required decorator?
I have searched for similar questions and answers for the question.I expect the home page to be displayed after authentication by a django-allauth view.But why do i have too many login redirects when using @login_required decorator?" Can you please explain the cause and the solution for the redirect loop? The code for the redirect loop is HTTP/1.1'' 302. I looked up from the Django documentation that @login_required decorator does the following: If the user isn’t logged in, redirect to /accounts/login/, passing the current absolute URL in the query string as next, for example:/accounts/login/?next=/polls/3/. If the user is logged in, execute the view normally. The view code can then assume that the user is logged in. I want authenticated users to proceed to home page, while redirecting not logged in users to accounts/login page. Part of my settings.py : LOGIN_URL='/accounts/login/' LOGIN_REDIRECT_URL='/' My views.py : from django.shortcuts import render from django.template import RequestContext from django.contrib.auth.decorators import login_required # Create your views here. @login_required def home(request): context={} template='home.html' return render(request, template,context) My urls.py : from django.conf import settings from django.conf.urls.static import static from django.conf.urls import url, include from django.contrib import admin from profiles import views as profiles_views urlpatterns=[ url(r'^admin/',admin.site.urls), url(r'$',profiles_views.home,name='home'), url(r'^accounts/',include('allauth.urls')), -
Django model filter with dynamic fields-vlues list
If there is a way to pass a list of values which vary in size depending on the values send by the user. This is a fundamental requirement in a user query. For an example, suppose a model as follows which have 3 fields. class MyModel(models.Model) Fiedl1 //say an int field Field2 //int field Field3 //char field In the user search form all fields are optional and there can be three combinations that user can query for particular objects. User do not set any field in the form (could be handle by default url) User only set values for two fields only. user set all values for the query. (similar to 2) My understanding is that pass only available fields in the POST request will do the trick. How can I do that? I look for correct and less coding solution for this. -
How to send image from angular 2 for ImageField in restful API?
Recently i am working to upload image from angular 2 and saving it in django. for that purpose, i have made restful django API. that API is working and upload image in folder and saves path of image in attribute . Now, where i am confuse is, in which format should i send image to django. like i select file from angular 2 and convert it in base64. but it not working. here are my files. Model.py from django.db import models from time import time def get_name(instance,filename): return "uploaded_files/%s_%s"%(str(time()).replace('.','_'),filename) # Create your models here. class Mobile(models.Model): SNR_Name= models.CharField(max_length=20) SNR_Model= models.CharField(max_length=20) SNR_RAM= models.CharField(max_length=20) SNR_InternalMemory= models.CharField(max_length=20) SNR_CompleteName= models.CharField(max_length=200, default="---") SNR_ScreenSize= models.CharField(max_length=20) SNR_ExternalMemory= models.CharField(max_length=20) SNR_ProcessorSpeed= models.CharField(max_length=20) SNR_Other= models.CharField(max_length=200) SNR_Available=models.CharField(max_length=50,default="") SNR_Link= models.CharField(max_length=1200,default="http.shopnroar.com") SNR_Price =models.DecimalField(max_digits=8,decimal_places=2,default=00) SNR_date = models.DateTimeField(auto_now_add=True, blank=True) SNR_Thumbnail=models.FileField(upload_to=get_name, blank=True) class Meta: unique_together = (('SNR_Name', 'SNR_Model','SNR_RAM','SNR_Link'),) def __str__(self): return self.SNR_Name+' , '+self.SNR_Model+' , '+self.SNR_RAM+' , '+self.SNR_ProcessorSpeed+' , '+self.SNR_InternalMemory+' , '+self.SNR_ExternalMemory+','+self.SNR_CompleteName+' , '+self.SNR_ScreenSize+' , '+str(self.SNR_Price)+' , '+self.SNR_Other+','+self.SNR_Available+' , '+self.SNR_Link+' , '+str(self.SNR_Thumbnail) and Serilizer.py from rest_framework import serializers from .models import Mobile class Mobile_Serializer(serializers.ModelSerializer): class Meta: model=Mobile fields=('SNR_Name','SNR_Model','SNR_RAM','SNR_ProcessorSpeed' , 'SNR_InternalMemory','SNR_ExternalMemory','SNR_CompleteName','SNR_ScreenSize','SNR_Price','SNR_Other','SNR_Available','SNR_Link','SNR_Thumbnail') and my view.py def add_Mobiles(request): if request.method == 'POST': serializer = Mobile_Serializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_406_NOT_ACCEPTABLE) else: return Response(status=status.HTTP_400_BAD_REQUEST) when … -
xadmin django reload no defined
i use python 3.5 django 1.11 and trying xadmin 0.5 i install succedfully by pip xadmin. 1- set up appinstalled with xadmin, crispy_forms, reversion 2- set up urls url(r'^xadmin/', include(xadmin.site.urls)) 3-trying python manage.py syncdb 4- error message: reload not defined 5- make change to import from importlib import reload and delete # sys.setdefaultencoding("utf-8") 6- now error message: app doesnt load ... anyone can help me to setting xadmin thank you! -
deploy django application on apache server
I'm new to django and deploying apps. I tried to follow this tutorial. Everything worked great exept that by the end, instead of the django app I got the depault apache2 page. (If it's matter, I work on ubuntu). Any suggestions? maybe firewall or something? I'm pretty lost... -
Python Data Scrapping
I'm dealing with Some data and need to know how to normalise these Data. Suppose how to deal with iPhone 7 and Apple iPhone 7, Apple iPhone Seven as all are same and l must store a single instance of that.