Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - updating a field in django
I am new to django and trying to update some data in my model using by using the PUT methed in the views.py. Here is what I've done. @api_view(['PUT']) def check_coupon(request): global kid_id, code, serializer try: code = request.POST['code'] kid_id = request.POST['kid_id'] except KeyError: x = None if request.method == 'PUT': if services.check_coupon(code) == 1: services.update_coupon(code, kid_id) # this updates the data serializer = serializers.CouponSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This creates a new coupon object instead of updating the existing one. How can I update a specific field.My input field in the body are the user id and the code. -
Vagrant port not exposed
I am using an ubuntu/xenial64 vagrant box and following the instructions indicated here to set up a readthedocs server. I am also hard coding a static private net IP in Vagrantfile: config.vm.network "private_network", ip: "192.168.33.10" However, after starting the Django server: (rtd) vagrant@ubuntu-xenial:~/rtd/checkouts/readthedocs.org$ python manage.py runserver [14/Mar/2018 05:22:40] root:120[1581]: INFO Generating grammar tables from /usr/lib/python2.7/lib2to3/Grammar.txt [14/Mar/2018 05:22:40] root:120[1581]: INFO Generating grammar tables from /usr/lib/python2.7/lib2to3/PatternGrammar.txt [14/Mar/2018 05:22:41] root:120[1585]: INFO Generating grammar tables from /usr/lib/python2.7/lib2to3/Grammar.txt [14/Mar/2018 05:22:41] root:120[1585]: INFO Generating grammar tables from /usr/lib/python2.7/lib2to3/PatternGrammar.txt Performing system checks... System check identified some issues: WARNINGS: ?: (1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 and the TEMPLATES dictionary takes precedence. You must put the values of the following settings into your default TEMPLATES dict: TEMPLATE_DEBUG. ?: (guardian.W001) Guardian authentication backend is not hooked. You can add this in settings as eg: `AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend', 'guardian.backends.ObjectPermissionBackend')`. System check identified 2 issues (1 silenced). March 14, 2018 - 05:22:42 Django version 1.9.12, using settings 'readthedocs.settings.dev' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. I am unable to access http://192.168.33.10:8000/ Within the vagrant machine: vagrant@ubuntu-xenial:~$ netstat -ta Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 … -
why am i getting "response code (0) with no response from the server if i try to call riot api?
where as the api url i requested for is (https://matrix.org:8448/_matrix/client/r0/createRoom) -
only one form's submit button working
I have two include statements in my html- {% include "abc_bs3.html" with form=form form_title="Edit" form_btn="Save" form_id="edit" ajax="True" %} {% include "abc_bs3.html" with form=form2 form_title="Add" form_btn="Add" form_id="add" ajax="True" %} So, essentially- two forms on one page. The submit button for only one of the forms is works i.e. either 'Add' works or 'Edit' based on which is first. Not sure why this is happening. Any clues will be helpful. -
CSRF is only checked when authenticated in DRF?
I'm starting to build a django rest framework API for a react application, and we want everything, including the authentication, to be handled via API. We are using SessionAuthentication. If I have an authenticated session, then CSRF works entirely as expected (when auth'd the client should have a CSRF cookie set, and this needs to be paired with the csrfmiddlewaretoken in the POST data). However, when not authenticated, no POSTs seem to be subject to CSRF checks. Including the (basic) login APIView that has been created. This leaves the site vulnerable to login CSRF exploits. Does anyone know how to enforce CSRF checks even on unathenticated sessions? and/or how DRF seems to bypass CSRF checks for login? settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } views.py: class Login(APIView): permission_classes = (permissions.AllowAny,) @method_decorator(csrf_protect) # shouldn't be needed def post(self, request, format=None): user = authenticate( request, username=request.POST['username'], password=request.POST['password'] ) # ... perform login logic ... def get(self, request, format=None): """ Client must GET the login to obtain CSRF token """ # Force generation of CSRF token so that it's set in the client get_token(request) return Response(None) urls.py: urlpatterns = [ url(r'^login/$', views.Login.as_view(), name='login'), ] expected behaviour: login_url … -
ImportError: No module named core django framework
Screenshot of the codeI have virtual environment sample_project and in that i have project mysite App name-core When I run this cmd-./manage.py makemigrations its throwing the above error -
Django Python Requests - Parse text/plain payload
This seems like a stupid question, and probably is. Say that I'm making a request to an API as follows: r = requests.post("http://EXAMPLE.COM/api/randomstring") ## I've blocked out the real URL so false requests aren't made as it's publicly available The specification for this API is that on every request, it generates a random string of 10 letters. If the request is processed successfully, the server should respond with 201 CREATED and a text/plain payload giving the random string from the API database. I have previously tried the following to parse the request, and add it to a locally stored database model: new_word = r.text() Words.objects.create(word=new_word) But this gave the error: TypeError: 'str' object is not callable I then tried simply: Words.objects.create(word=r) When I run this from a client, and then check the local database, it only shows as: word: <Response [201]> This means that obviously the request was successful, and a word is in the text/plain payload. But how do I parse only the word from the payload, so that I am able to save it as (for example): word: hskcudyhft I know how to parse a JSON payload which is probably much trickier than this - which is probably … -
Creating a User Account While Registring
I'll like that everytime an hospital is created, A corresponding User account is created likewise, allowing the newly created account to login.... models.py class Hospital(models.Model): """ Model representing individual Hospitals """ id = models.UUIDField(primary_key=True, unique=True, db_index=True, default=uuid.uuid4, editable=False) hospital_name = models.CharField(help_text="full name of hospital", max_length=200) slug = models.SlugField(max_length=200) hospital_logo = models.ImageField(upload_to='hospital_logo',) hospital_address = models.CharField(max_length=500) hospital_email = models.EmailField(max_length=254) hospital_website = models.CharField(max_length=200) hospital_rc_number = models.PositiveSmallIntegerField() date_added = models.DateField(auto_now=True) forms.py class HospitalForm(forms.ModelForm): """ Forms for Hospital creation """ class Meta: model = Hospital fields = ('hospital_name', 'hospital_address', 'hospital_email', 'hospital_website', 'hospital_rc_number','hospital_logo') widgets = { 'hospital_name': forms.TextInput(attrs={'class': 'form-control'}), 'hospital_address': forms.TextInput(attrs={'class': 'form-control'}), 'hospital_email': forms.TextInput(attrs={'class': 'form-control'}), 'hospital_website': forms.TextInput(attrs={'class': 'form-control'}), 'hospital_rc_number': forms.TextInput(attrs={'class': 'form-control'}), } def save(self): instance = super(HospitalForm, self).save(commit=False) instance.slug = slugify(instance.hospital_name) instance.save() return instance views.py class HospitalCreate(CreateView): model = Hospital form_class = HospitalForm template_name = 'hospital/hospital_add.html' pk_url_kwarg = 'hospital_id' success_url = reverse_lazy('hospital_list') user_form = UserForm -
Django change Model's field type from CharField to JSONField
I am using Django 1.11 , I have been using CharField in Models, and dumping data in it using json.dumps(). I am using mysql database. I want to change CharField to JSONField, according to this answer. Is there any way so that I can modify my field type without loosing the data? Please note that the data in CharField is json dumped. -
Fail sending mail with Django
I tried to send email using django.core.mail and I got the error: Request Method: POST Request URL: http://localhost:8000/accounts/signup/ Django Version: 1.11.10 Exception Type: gaierror Exception Value: [Errno -2] Name or service not known Exception Location: /usr/lib/python2.7/socket.py in create_connection, line 557 Python Executable: /home/lucas/Documentos/projetos/advogados/venv/bin/python Python Version: 2.7.12 After that I tried to send email using just python script like this and worked fine: import smtplib server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login("my@email.com", "mypassword") msg = "YOUR MESSAGE!" server.sendmail("my@email.com", "to@email.com", msg) server.quit() So I created my own Email sender to use with Django: import smtplib from django.conf import settings def send_custom_mail(msg, to, subject): message = 'Subject: {}\n\n{}'.format(subject, msg) server = smtplib.SMTP(settings.EMAIL_HOST, settings.EMAIL_PORT) server.starttls() server.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD) server.sendmail(settings.EMAIL_HOST_USER, to, message) server.quit() And it is still not working and I receive the same error. So I removed the settings vars and used the real values, and it WORKS!!! I realize that the problem was related with settings vars, and I logged them and theyre type, string for host, pass and user and int for port. OK ! I don't know how to check or fix that, other vars like ALLOWED_HOSTS and SECRET_KEY are working fine I'm using decouple lib to remove sensitive data from settings -
How to get the request-id from snmp response
Using wireshark i can see a request-id goes on when i run this program (How to get the value of OID in Python using PySnmp), can i get the request-id number using python program similarly, when i run this program i basically give community:public and version v2c, but in get-response i get request-id, this is what is need to fetch. Please help me out how to do it. Here is the image of snmp response in wireshark. https://i.imgur.com/aH5gO4B.png -
Bokeh plot not showing up in django template
I am trying to embed a bokeh plot into a django template, but the plot is not showing up. What am I doing wrong? views.py from bokeh.plotting import figure from bokeh.models import ColumnDataSource, Axis, NumeralTickFormatter, HoverTool, Range1d, LinearAxis from bokeh.layouts import row, widgetbox, gridplot, column from bokeh.resources import CDN from bokeh.embed import components def customer_view(request, customer_id): data = dict() template = 'dashboard/includes/customer/partial_customer_view.html' customer = get_object_or_404(Customer, customer_id=customer_id) contacts = ContactPerson.objects.filter(Q(customer__customer_id=customer_id)).all() plot = figure() plot.circle([1,2], [3,4]) script, div = components(plot) context = { "customer": customer, "contacts": contacts, "the_script": script, "the_div": div, } data['html_form'] = render_to_string(template, context, request=request) return JsonResponse(data) base.html <head> {% load static %} <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Dashboard</title> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700|Roboto:300,400,500" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"> <link rel="stylesheet" type="text/css" href="../static/styles/css/style.css"> <link rel="stylesheet" href="http://cdn.pydata.org/bokeh/release/bokeh-0.12.14.min.css"> <script src="http://cdn.pydata.org/bokeh/release/bokeh-0.12.14.min.js"></script> {{the_script|safe}} </head> pip freeze --> bokeh==0.12.14 template <div class="graphs"> {{ the_div | safe }} </div> When I inspect the template I can see that the following shows up in the template. <div class="bk-root"> <div class="bk-plotdiv" id="bdbe8a80-d589-4532-9d9d-c7a12bba4aff"> </div> </div> -
How to create backbone of my Django web-application
I have the following problem. I am building a calculation web application using Django. The app will have the following models: User Project ( a user will have one or more projects) System (a project has one or more hydraulic systems) Circuit (a system will have one or more hydraulic circuits) Component (a hydraulic circuit will have one or more hydraulic components) How should I organize my code. Should I create 5 different apps? How to organize my urls.py for the various apps? Basically the problem seems to be that there are 5 nested models. I already implemeted user and project. Currently the mysite.urls is something like: urlpatterns = [ path('', include('core.urls')), # handles the User path('project/', include('project.urls')), path('admin/', admin.site.urls), ] The project.urls is given by: app_name = 'project' urlpatterns = [ path('', views.ProjectIndexView.as_view(), name='index'), path('create/', views.ProjectCreateView.as_view(), name='create'), path('create_project/', views.create_project, name='create_project'), path('<int:pk>/', views.ProjectDetailView.as_view(), name='detail'), path('<int:project_id>/change_project/', views.change_project, name='change_project'), path('<int:pk>/results/', views.ProjectResultsView.as_view(), name='results'), path('<int:pk>/delete_project/', views.ProjectDeleteView.as_view(), name='delete_project') ] So far so good, but how should I next configure the urls to include the System model? If I should create 5 apps, i.e.: Core (handels the user), Project, System, Circuit and Component, should the app folders be on the same level? Or should the app … -
Not able to upload file using django-filer django
I am new to Django and trying to migrate one old python project. In one module while i am trying to upload file it is throwing below error: KeyError: '32' File "django/core/handlers/base.py", line 112, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "django/views/decorators/csrf.py", line 57, in wrapped_view return view_func(*args, **kwargs) File "filer/admin/clipboardadmin.py", line 88, in ajax_upload 'thumbnail': file_obj.icons['32'], Version Django==1.6.8 easy-thumbnails==2.2 django-filer==0.9.4 So how to fix it? -
Exception while resolving variable 'title' in template 'index.html'
Django website works fine in debug mode in local server. But in production it does not work. I checked the logs (0.001) SELECT "blog_entry"."id", "blog_entry"."title", "blog_entry"."image", "blog_entry"."description", "blog_entry"."body", "blog_entry"."slug", "blog_entry"."publish", "blog_entry"."created", "blog_entry"."modified" FROM "blog_entry" ORDER BY "blog_entry"."created" DESC; args=() (0.000) SELECT "work_work"."id", "work_work"."image", "work_work"."header", "work_work"."description" FROM "work_work"; args=() (0.000) SELECT "project_project"."id", "project_project"."image", "project_project"."Header", "project_project"."description" FROM "project_project"; args=() Exception while resolving variable 'title' in template 'index.html'. Traceback (most recent call last): File "/media/sanjeev/Work/source/backend/new/local/lib/python2.7/site-packages/django/template/base.py", line 907, in _resolve_lookup (bit, current)) # missing attribute VariableDoesNotExist: Failed lookup for key [title] in u"[{'False': False, 'None': None, 'True': True}, {u'csrf_token': <SimpleLazyObject: <function _get_val at 0x7fbac8d4f7d0>>, 'user': <SimpleLazyObject: <function <lambda> at 0x7fbac97a8140>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x7fbac8d51190>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'WARNING': 30, 'SUCCESS': 25, 'ERROR': 40}, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x7fbac97a3290>, u'request': <WSGIRequest: GET '/'>}, {}, {u'queryset': <QuerySet [<Entry: Best Action Cameras>, <Entry: 5 Best DSLR Cameras>, <Entry: Blackberry KEYone>, <Entry: BEST SMARTPHONES (2017)>]>, u'project_list': <QuerySet []>, u'bruhh': u'title', u'form': <contactForm bound=False, valid=Unknown, fields=(name;email;comment)>, u'work_list': <QuerySet []>}]" Exception while resolving variable 'confirm_message' in template 'index.html'. Traceback (most recent call last): File "/media/sanjeev/Work/source/backend/new/local/lib/python2.7/site-packages/django/template/base.py", line 907, in _resolve_lookup (bit, current)) # missing attribute VariableDoesNotExist: Failed lookup for key [confirm_message] in u"[{'False': False, 'None': None, 'True': True}, … -
Passing a matplotlib image to render via context in Django
I am trying to render a call to a query, some text and a matplotlib image on a webpage using Django. I have the following views.py file: def getinput(request): if request.method == 'POST': form = get_data(request.POST) if form.is_valid(): down = form.cleaned_data['get_down'] ytg = form.cleaned_data['get_ytg'] yfog = form.cleaned_data['get_yfog'] map_data = next_play.objects.filter(last_dwn__exact=down, last_yfog__exact=yfog, last_ytg__exact=ytg) fig = plot_playoutcomes(map_data) context = {'form': form, 'query_data': map_data, 'img': fig} return render(request, 'play_outcomes/output.html', context) else: form = get_data() return render(request, 'play_outcomes/getinput.html', {'form': form}) This calls a query from my model that it stores in map_data. I then want to plot an image and call plot_playoutcomes(map_data). Here is the code for that: from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure import numpy as np from django.http import HttpResponse, HttpResponseRedirect def plot_playoutcomes(playdata): fig = Figure() canvas = FigureCanvas(fig) ax = fig.add_subplot(111) x = np.arange(-2,1.5,.01) y = np.sin(np.exp(2*x)) ax.plot(x, y) response = HttpResponse(content_type='image/png') canvas.print_png(response) return response Note - that in the function I DO NOT use map_data, but rather plot a simple picture. Here is the template - it displays some text, the image, and the data I queried. <h1>Thanks for entering data!!!!</h1> {{ query_data }} {{ img }} <ul> {% for game in query_data %} <li>{{ game.dwn … -
How can axios get the status code in .catch()?
In the Axios document: axios.get('/user/12345') .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); }); we know we can catch the error in the .catch() method. But when I use the Django-Rest-Framework as the backend API provider. it only provide the data, there is no status in it: You see the error: {username: ["A user with that username already exists."]} but in the browser, we can know the status code: Before asking this question, I have read How can I get the status code from an http error in Axios? this post. But the post seems different with mine. EDIT-1 In my Django-Rest-Framework project: the view: class UserCreateAPIView(CreateAPIView): serializer_class = UserCreateSerializer permission_classes = [AllowAny] queryset = User.objects.all() the serializer: class UserCreateSerializer(ModelSerializer): """ user register """ … -
django tastypie bundle.object returns F('value')
posmenu = POSMenuResource() request_bundle = posmenu.build_bundle(request=request, data = m_new) bundle_data = posmenu.obj_create(request_bundle) Here if i print bundle_data.obj.id it gets the latest value But if i print bundle_data.obj.version it gives F('version') + 1 as result (which is how it is defined in obj_create of the same resource) How to get the exact value instead of function value -
React, react-router, django
I have a SPA-application on React with Redux. React talk with Django only with rest api. Otherwise, frontend and backend - different parts. Also, I know that have another way - standart Django scheme (render to template, when in template - connect with React). Which way is more good? Different parts or Django-way? Sorry, if this question is a strange. Thanks a lot. -
How do i display multiple images uploaded via a formset on my template?
I'm trying to create a site that displays a list of construction projects carried out by my company whereby i want each project on the list to have a gallery of images related to it which i will later loop over in my project details template, i have tried to use formsets but i cant figure out how to loop over the images in the formset to show in the template?can anyone please help me or give me a better approach to my problem? i'm using this approach on this question currently -
in doesnt work for queryset
I have tried to use the built in Groups system in Django to pass through whether a user is part of a group or not to the template: def is_contributor(request): group = Group.objects.get_or_create(name='contributor') return { 'is_contributor': True if group in request.user.groups.all() else False } The following will pass through False even if the user is part of the group. Specifically, if I pass through the following: request.user.groups.all() I get: <QuerySet [<Group: contributor>]> Which leads me to believe that the 'in' in this case is not working over the queryset. Are there limitations to using in over a queryset? Is there a better approach? -
Can't compare string in Django template
Here's my template: <p>{{ instance.video_source }}</p> #"youtube" {% if instance.video_source == "youtube" %} <h1>YOUTUBE</h1> #doesn't print "YOUTUBE" {% endif %} Any idea why the if statement doesn't fire? I've also tried {% if instance.video_source == youtube|stringify %} which is this template tag here: def stringify(obj): return str(obj) and the if statement still doesn't fire. And this also doesn't work {% if instance.video_source == youtube|stringformat:"s" %} <h1>YOUTUBE</h1> {% endif %} Here's the origin of instance.video_source: @property def video_source(self): return "youtube" Any idea why the if statement isn't working? -
Django - Sorting boolean using annotate
Let's imagine I have this model and I would like to sort them by logical operation n1 != n2: class Thing(Model): n1 = IntegerField() n2 = IntegerField() ... def is_different(self): return self.n1 != self.n2 If I sort them by sorted built-in function, I found that it does not return a Queryset, but a list: things = Thing.objects.all() sorted_things = sorted(things, key=lambda x: x.is_different()) Now, if I use annotate sorted_things = things.annotate(diff=(F('n1') != F('n2'))).order_by('diff') it raises the following error: AttributeError: 'bool' object has no attribute 'resolve_expression'. I found a solution using extra queryset: sorted_things = things.extra(select={'diff': 'n1!=n2'}).order_by('diff') but following Django docs (https://docs.djangoproject.com/en/2.0/ref/models/querysets/#extra): Use this method as a last resort This is an old API that we aim to deprecate at some point in the future. Use it only if you cannot express your query using other queryset methods. If you do need to use it, please file a ticket using the QuerySet.extra keyword with your use case (please check the list of existing tickets first) so that we can enhance the QuerySet API to allow removing extra(). We are no longer improving or fixing bugs for this method. Then, what is the optimal way to do it? Thanks! -
Django-material frontend widget override
I'm using material frontend, i'm trying to override widgets as I do that in an admin form, although it seems overridden in my IDE. I cannot get it to work in the frontend. The goal is to replace certain field's widget with a custom one i.e I want range instead of text input. Anyone with experience with Django material that can show me a way to bypass the original rendering of the widgets. -
UPSERT with Django. Many rows
I try to do UPSERT with Django 2.0, Postgres 9.5. My table: \d+ candle Table "public.candle" Column | Type | Modifiers | Storage | Stats target | Description -------------------+--------------------------+-----------------------------------------------------+---------+--------------+------------- id | integer | not null default nextval('candle_id_seq'::regclass) | plain | | mts | timestamp with time zone | not null | plain | | open | numeric(200,40) | not null | main | | close | numeric(200,40) | not null | main | | high | numeric(200,40) | not null | main | | low | numeric(200,40) | not null | main | | volume | numeric(200,40) | not null | main | | pair_timeframe_id | integer | not null | plain | | Indexes: "candle_pkey" PRIMARY KEY, btree (id) "candle_mts_84b62390_uniq" UNIQUE CONSTRAINT, btree (mts) "candle_pair_timeframe_id_3f7b76ce" btree (pair_timeframe_id) Foreign-key constraints: "candle_pair_timeframe_id_3f7b76ce_fk_pair_timeframe_id" FOREIGN KEY (pair_timeframe_id) REFERENCES pair_timeframe(id) DEFERRABLE INITIALLY DEFERRED Implemented it like this: with connection.cursor() as cursor: g = ''' INSERT INTO candle ( pair_timeframe_id, mts, open, close, high, low, volume ) VALUES %s ON CONFLICT (mts) DO UPDATE SET open = EXCLUDED.open, close = EXCLUDED.close, high = EXCLUDED.high, low = EXCLUDED.low, volume = EXCLUDED.volume WHERE candle.pair_timeframe_id = %s; ''' % (data, str(pairs_timeframes_id)) Values might be me many, but in …