Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't load css and js files from static directory. was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff)
My project was working perfectly fine, i don't know what happened. I didn't even make any changes to front end, i was working on back end. On reloading my website to check a feature, suddenly all of my css disappeared. On checking the console, there were messages like: The resource from “http://127.0.0.1:8000/static/events/css/profile.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). 127.0.0.1:8000 The resource from “http://127.0.0.1:8000/static/events/css/nav.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). .......... Some cookies are misusing the recommended “SameSite“ attribute 2 The resource from “http://127.0.0.1:8000/static/events/css/events.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). 127.0.0.1:8000 Loading failed for the <script> with source “http://127.0.0.1:8000/static/events/src/navbar.js”. 127.0.0.1:8000:276:1 The resource from “http://127.0.0.1:8000/static/events/src/navbar.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff) I am giving all the resources in an obvious way: {% load static %} {% extends 'app/base.html' %} <link rel="stylesheet" type="text/css" href="{% static 'events/css/home.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'events/css/events.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'events/css/post_form.css' %}"> <script type="text/javascript" src="{% static 'events/src/navbar.js' %}"></script> ........ I have no idea what went wrong all of a sudden Can someone please help me with this!! -
Django ImageField Default Image
In my project I want to allow users to upload profile picture. I am using imagefield but the default option is not working and hence I am getting an error. **models.py** class Profile_Pic(models.Model): user = models.OneToOneField(User,null=True,on_delete=models.CASCADE) profile_pic = models.ImageField(null=True,blank=True,default='images/logo.png',upload_to='images') @property def default(self): if self.profile_pic: return self.profile_pic.url else: return 'logo.png' class Meta: db_table = 'Profile_Pic' **views.py** @login_required def profile(request): user = request.user.profile_pic form = Photo(instance=user) context = {'photo': form} return render(request, 'datas/profile.html', context) **settings.py** STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'admin_car/static/media') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'admin_car/static/images') ] **profile.html** <div style="text-align: left;position:absolute;top:50px;left:16px;float: left"> <img class="image" src='{{ user.profile_pic.profile_pic.url }}' style=" height: 200px; width: 200px" alt="logo.png"> <style> img { border-radius: 50%; } </style> Is there any way where I can add a default picture whenever a new user is created? Any help would be appreciated. -
django2.1,Use mysql to custom login,MySQL: "Field 'id' doesn't have a default value"
I try to custom login Django2.1 with Mysql,and I got this error: Field 'id' doesn't have a default value.But I had set ID is 'auto_increment' and 'not null': Where am I wrong?By the way, it is OK with sqlite3.So weird. This is my models.py: from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.contrib.auth.models import AbstractUser @python_2_unicode_compatible class AliUser(AbstractUser): userid = models.CharField(max_length=20, default='') # user Id empid = models.CharField(max_length=100, default='') sso_token = models.CharField(max_length=36) # SSO Token token_time = models.DateTimeField(auto_now=True) def __str__(self): return self.first_name Here is my backends.py: from django.contrib.auth.backends import RemoteUserBackend from naxxramas.models import AliUser as User class AliSSOUserBackend(RemoteUserBackend): def authenticate(self, request, userId, empId, first_name='', last_name='', email=''): if not userId or not empId: # not my company user return None user = None try: user = User.objects.get(empid=empId) self.create_unknown_user = False except User.DoesNotExist: pass if self.create_unknown_user: user, created = User.objects.update_or_create( empid=empId, defaults={ 'username': email.split('@', 1)[0], 'empid': empId, 'userid': userId, 'first_name': first_name or last_name or '', # first_name may be null 'last_name': last_name or '', 'email': email, }) if created: user = self.configure_user(user) return user if self.user_can_authenticate(user) else None And this is my views.py,i found it may wrong at "auth_login": from django.conf import settings from django.contrib.auth import authenticate, … -
UniqueConstraint and ignore case sensitive
I would like to use this code: constraints = [ models.UniqueConstraint(fields=['name', 'app'], name='unique_booking'), ] but name and app (both of them) should not check case sensitive so "FOo" and "fOO" should be marked as the same app. How to do it? -
Is there a way to run django constantly on the server to update a database based on live data
I am developing a virtual stock market application on django and came upon the following problem. In any stock market application, there is an option of limit buy, stop loss and target sell. This essentially means to buy a share if it ever touches a price which is lower than the current price, to sell a share if it touches a very low price and to sell a share if it touches a high price respectively. For this, the server needs to constantly monitor the live data coming in from the API of a particular stock and perform the action if it happens. However, during this time no one may be making any requests on the site so how do I get django to monitor the prices of the stocks every 5 seconds or so to check if the order needs to be executed or not? -
How to redirect to another page after admin login (Django)
I'm working on an administration page in Django and I want to redirect an user to another page than the basic one, for example : localhost:8000/admin/my-app/table/ instead of localhost:8000/admin/. How can I do that ? Thanks for your help. -
Django how to pass a dictionary as a value to the Response of a GET request and make sure that the Django Rest Web App for API still works
I have an application and want to pass a dictionary as a value to the response of a GET request when the user does a GET request on /inventory/item_mast/. The response that the user should get is: { pk:1, item_name: "laptop" item_cat_name: {id:1,name:"techonology"} } The model that I have is: class Item_Mast(AbstractBaseModel): pk = models.AutoField(primary_key=True) item_name = models.CharField(max_length=50) item_cat_mast = models.ForeignKey("inventory.Item_Cat_Mast", on_delete=models.SET_NULL, null=True) def __str__(self): return self.item_name The serializer I have is: class Item_Mast_Serializer(serializers.ModelSerializer): item_cat_mast = IdNameField(id_field='pk',name_field='item_cat_name', queryset=Item_Cat_Mast.objects.all()) class Meta: model = Item_Mast fields = '__all__' I have written a Custom Serializer to return data for ForeignKey fields in the format {id:"some_id",name:"some_name"}. The code for it is: class IdNameField(serializers.RelatedField): def __init__(self, *args, **kwargs): id_field = kwargs.pop('id_field', None) name_field = kwargs.pop('name_field', None) super(IdNameField, self).__init__(*args, **kwargs) self.id_field = id_field self.name_field = name_field def to_representation(self, obj): return { 'id': getattr(obj,self.id_field), 'name': getattr(obj,self.name_field), } def to_internal_value(self, data): try: if(type(data) == dict): try: return self.get_queryset().get(**{self.id_field:data["id"]}) except KeyError: raise serializers.ValidationError('id is a required field.') except ValueError: raise serializers.ValidationError('id must be an integer.') else: return self.get_queryset().get(**{self.id_field:data}) except: raise serializers.ValidationError('Obj does not exist.') The view is: class Item_Mast_ListView(mixins.ListModelMixin,GenericAPIView): queryset = Item_Mast.objects.all() serializer_class = Item_Mast_Serializer This works and the response of the GET request is the desired data, however … -
copy .sql file data into postgresql database table my_table in python and Django
In my project folder I have somedata.sql file and I want to insert data from that somedata.sql file into table mytable in postgresql database. So, How can I insert somedata.sql file data into mytable in postgresql database. somedata.sql INSERT INTO public.mytable( id, webservice_id, name, alias, enabled, "Logo", "Link", "SEOName", cashback, addeby, addedon, advertiser_id) VALUES (6, 4, 'Newegg', 'Newegg', 1, 'http://www.some.com/', 'http://www.some.com/', 'Newegg.com', '1', 0, '2019-05-03 16:30:35.000000', '1'), (8, 3, 'HobbyTron.com', 'HobbyTron.com', 1, 'http://www.some.net/', 'http://www.some.com/', 'HobbyTron', '2', 0, '2019-05-03 16:30:35.000000', '1'); mytable is model in models.py class mytable(models.Model): webservice_id = models.IntegerField() name = models.TextField(max_length=128) alias = models.TextField(max_length=64) enabled = models.IntegerField() Logo = models.TextField(max_length=2000) Link = models.TextField(max_length=200) SEOName = models.TextField(max_length=200) cashback = models.IntegerField(null=True, blank=True) addeby = models.IntegerField() addedon = models.DateTimeField(editable=False) advertiser_id = models.TextField(max_length=50) -
I have an issue that how can I convert flask to django by following condition
I am doing this project first time. I have to manage a multithreaded queue in my django app. User sends request to app will automatically added(append) to queue. If user is at first location then 30 seconds time is alloted to that first user and it will redirected to main page while other users are waiting in queue (other page will showing you are in queue) till first user will terminate his session. After terminating first user, second user automatically getting to first and alloted 30 seconds and redirected to main page. exited user will redirected to exit page. Please help me to solve this problem in django -
How to set read only property to entire Django forms based on session user
I have created a form that can be used to update/create/view records. When a user selects a record that record data is rendered in the form. So that user will able to view/edit the form. The problem statement here is that if a record is created by some other user then the session user will not able to edit (only the creator should have access to edit). I am thinking to write a logic so that when the record is created by the session user then only he/she will edit. Otherwise, the user will just view the record using the same form. Below is my view file current_blog = Blog.objects.get(pk=blog_id) init_dict = { "blog_title": current_blog.blog_title, "blog_description": current_blog.blog_description, "last_modified": current_blog.last_modified } form = NewBlog(initial=init_dict) return render(request, "myblog/blog.html", {"new_blog": form}) form.py class NewBlog(forms.Form): blog_title = forms.CharField(label="Form Title", max_length=250, widget=forms.TextInput( attrs={"class": "form-control", "placeholder": "Enter title here"} )) blog_description = forms.CharField(label="Blog Description", widget=forms.Textarea( attrs={"class": "form-control", "placeholder": "Enter blog Description"} )) blog.html {% for field in new_blog %} <div class="col-sm-12"> <fieldset> {{ field.label }} {{ field }} <div class="text-danger">{{ field.errors }}</div> </fieldset> </div> {% endfor %} -
Implementing Djoser and JWT in Django for user authentication
I am implementing user authentication in my first Django app. I decided to follow a tutorial from here. I just finished the implementation, and it happens that when I add the following route path('api/app', include('app.urls')),to the url.py, I get the following error, which crashes t he platform: .... File "/Users/frankydoul/opt/anaconda3/lib/python3.8/site-packages/django/urls/resolvers.py", line 123, in _check_pattern_startswith_slash if regex_pattern.startswith(('/', '^/', '^\\/')) and not regex_pattern.endswith('/'): RecursionError: maximum recursion depth exceeded while calling a Python object Removing it let the platform running. Is anybody familiar with the error please ? -
zappa deployment : [ERROR] CommandError: Unknown command: 'create_pg_db'
I followed the tutorial on https://romandc.com/zappa-django-guide/walk_database/ and pip installed the package, added the value to installed apps, configured the aws aurora postgres then when I do zappa manage project_name create_pg_db I get [ERROR] CommandError: Unknown command: 'create_pg_db' Traceback (most recent call last): File "/var/task/handler.py", line 609, in lambda_handler return LambdaHandler.lambda_handler(event, context) File "/var/task/handler.py", line 243, in lambda_handler return handler.handler(event, context) File "/var/task/handler.py", line 408, in handler management.call_command(*event['manage'].split(' ')) File "/var/task/django/core/management/init.py", line 105, in call_command raise CommandError("Unknown command: %r" % command_name)[END] did I miss anything, what can I do to fix this? -
Django/Daphne, got NotImplementedError calling asyncio.create_subprocess_exec( under WINDOWS
I am using Django 3.2 with Daphne 3.0.2, Python 3.8.9 under Windows 10. Trying to call proc = await asyncio.create_subprocess_exec( python_exe, bridge_script, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT, ) Gives me following error: Exception Type: NotImplementedError Exception Location: c:\python\python38\lib\asyncio\base_events.py, line 491, in _make_subprocess_transport When serving Django/ASGI with daphne. Under Linux everything runs fine. Serving under Windows with Python runserver also everything fine, Just daphne & windows gives me the error. Thanks for any help. -
Python and markdown I can't print inside html
I'm using Django and this is my python code import markdown def link(request): output = markdown.markdownFromFile('entries/CSS.md') print(output) this is my html code ` Encyclopedia <h1>All Pages</h1> {{ link }} below is inside CSS.md I want it to print inside my html page inside {{ link }} `CSS CSS is a language that can be used to add style to an HTML page.` > [![I'm having this message][1]][1] -
ngrok: DJango and nodejs: how to add multiple ports
How can i add multiple ports I have nodejs and django application webapp: image: "python-node-buster" ports: - "8001:8000" command: - python manage.py runserver --noreload 0.0.0.0:8000 networks: - django_network node: image: "python-node-buster" ports: - "3000:3000" stdin_open: true networks: - node_network ngrok: image: wernight/ngrok:latest ports: - 4040:4040 environment: NGROK_PROTOCOL: http NGROK_PORT: node:3000 NGROK_AUTH: "" depends_on: - node - webapp networks: - node_network - django_network networks: django_network: driver: bridge node_network: driver: bridge Assuming i get the url for node at http://localhost:4040/inspect/http http://xxxx.ngrok.io and in my nodejs application, i want to access http://xxxx.ngrok.io:8001 for apis How to configure this -
Backend python online game (Гонки для двоих)
Всем привет Стоит задача сделать бекенд для игри гонки на двоих. Клиент будет написан на unity Подскажите что можно использовать для такой задачи. Всем спасибо. -
How to change content with ajax in django
I have a django template as follows <div class="container"> <section class="main"> <h1>Check the chart below</h1> <form> {% csrf_token %} <div class="switch"> <input id="chk" type="checkbox" class="switch-input" /> <label for="chk" class="switch-label">Switch</label> </div> </form> <div class="main_graph"> {% if main_graph %} {{ main_graph.0|safe }} {% else %} <p>No graph was provided.</p> {% endif %} </div> </section> </div> <script type="text/javascript"> $(document).on('click', '#chk', function (e) { $.ajax({ type: 'POST', url: '/home', data: { chk: $('#chk').prop('checked'), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function (data) { $('.main_graph').load(document.URL + ' .main_graph'); } }); }) </script> This is my views def home(request): const_list = pd.read_csv('./const.csv').Const.unique() part_list = pd.read_csv('./part_list.csv').abbr.unique() all_list = pd.read_csv('./all_list.csv').All.unique() chked=request.POST.get('chk', '') if chked == 'true': print(chked) my_graph = main_graph(all_list, len(const_list)) else: print('this is a test') my_graph = main_graph(part_list, len(const_list)) context={'main_graph':my_graph, 'const': const_list} return render(request, 'home.html', context) The main_graph function takes a list and an int value as parameters for creating a bar graph with plotly. The list will be for populating the y-axis and the int value is a range for the x-axis. The graph is created properly. Now I want to change the graph on the click of a button. For this purpose, I created a toggle switch which when clicked will send activate an ajax function. When I … -
How to run a python file in command promt when a button is clicked is on a webpage
I am trying to make a local webpage which later on will be deployed, in which when a button on the html webpage is clicked, it opens up a commend prompt window and run the program. I have tried to implement it this using django framework. I have added the python file to the project library for it to be accessible, I have implemented it in the following way in views.py file, def beast(request): out = run(sys.executable, ['beast.py'], shell=True) return render(request,'page2.html') No input is to be given to the python file. It compiles and runs, but when the button is clicked t gives out a TypeError - bufsize must be an integer Please let me know what can be done for it to work -
Forward & Back Buttons that can Increase or Decrease Current Date in a Django View Repeatedly
I have a view that displays a teacher's daily schedule based on what day it is. If it's Monday then all that teacher's Monday students and lesson times are displayed along with radio buttons for attendance to be recorded. By default the view starts on the current day. I want to install back and forward buttons in templates/teacher.html that will decrease or increase the date by one day per click. Tried passing 'back' or 'forward' as string path converters. For example, in views.py there'd be an if today = 'back' I would use datetime.timedelta(days=-1) to decrement the date by 1. However, that strategy seems to only be meant for making a one time change. In this strategy the first time the user clicks the Back Button the URL reads: localhost...:teacher/id/back Which works. But if the user clicks back again the URL reads: localhost...:teacher/id/backback And then I get an error. I want the user to be able to change the date back or forward as many times as desired. I've tried storing the date into a session variable, but Django Templates don't seem to provide a way to update a session variable from HTML. Or, do they? Anyway, I'm open to … -
Django form inside a page which is a form too
Help please, I have my RaodNetwork model which hold the Project model as Foreign Key. I Would like : 1 - One we are inside a project, select automatically the foreign key of this project without no ned to select it manually 2 - to create a road network instance and display (add) it inside a project. Here is my project page (pk=1) with my roadnetwork instance views.py def create_network(request, pk): """A roadnetwork depends on a project. It must be created un side the project""" project = Project.objects.get(id=pk) form = RoadNetworkForm(initial={'project':project}) if request.method =='POST': form=RoadNetworkForm(request.POST, instance=project) if form.is_valid(): form.save() return redirect('home') context = {'form':form} return render(request, 'roadnetwork.html', context) class RoadNetwork(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) simple = models.BooleanField(default=False) locked = models.BooleanField(default=False) #representation = path nb_nodes = models.IntegerField() nb_edges = models.IntegerField() name = models.CharField('Network Name', max_length=200, blank=False) comment = models.TextField() tags = models.TextField() def __str__(self): return "{}".format(self.name) class Project(models.Model): owner = models.ManyToManyField(User) # define as FK and add a user as ManyToManyField public = models.BooleanField(default=False) name = models.CharField('Project Name', max_length=200, null=False) comment = models.TextField() def __str__(self): return "{}".format(self.name) urlpatterns=[ path('project/<str:pk>/', project_pagination, name = 'project'), path('network/<str:pk>/', create_network, name = 'create_network'), ] -
Is there any method to get rid of this error. (1062, "Duplicate entry '2' for key 'customer_customerprofile.user_id'")?
I have to create a field called location from the lat and on like in this program. The location is printing out correctly, but there is a duplicate entry error while saving. I need to update the user_id to id when the post function works. Since it is saved twice, the duplicate entry error is showing. def post(self, request, format=None): serializer = CustomerSerializer(data=request.data) if serializer.is_valid(): serializer.save() lat = serializer.data.get('latitude',None) lon=serializer.data.get('longitude',None) lat_1=float(lat) lon_1=float(lon) location=Point((lat_1,lon_1),srid=4326) print(location) id=serializer.data.get('user') print(id) v=CustomerProfile(location=location,user_id=id) v.save() return Response({"message":"Customer Profile Updated Successfully","data":serializer.data}, status=200) return Response({"message":"Customer registration failed!!","data":serializer.data}, status=400) -
Django: prefetch related with sort by runs multiple queries
I am using prefetch_related. When i want to sort the prefetch results, then it generates again sql, class UserActivity(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name= 'user_logging_details', on_delete=models.CASCADE ) ip_addess = models.CharField(max_length=40) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) users = User.objects.prefetch_related('user_logging_details').all() for user in users: users_activity = user.user_logging_details.all() # this does not generate any sql ## VS ## users_activity = user.user_logging_details.all().sort_by('ip_addess') # this generates many sqls and defeats the purpose of prefetch related How can sort the prefetch results. What is the correct way to do this. -
Get GET url parameters in class-base views for Django 3.2
I found a similar question, but it was for Django 1.5, and I don't think it worked for me. class SearchedPostListView(ListView): model = Post template_name = 'blog/search.html' # <app>/<model>_<viewtype>.html paginate_by = 2 context_object_name = 'posts' def get_context_data(self, *args, **kwargs): context = super(SearchedPostListView, self).get_context_data(*args, **kwargs) query = self.kwargs.get('q') context['posts'] = Post.objects.filter(Q(title__icontains=query) | Q(author__username__icontains=query) | Q(content__icontains=query)) context['categories'] = Categories.objects.all return context This is my code. I am trying to search through all the posts on my website, and I'm showing any posts that have the query in the title. So, if I type in the URL localhost:8000/search?q=foo, then it has to show me the posts that contain the word foo in its title. But I'm not able to access the GET parameters. How do I access the GET parameters in Django 3.2? -
Django JSONDecodeError
I am working on a code that receives reading from a temperature sensor using ES8266 and the Arduino code is working fine sending the reading in JSON format. received data on the Django server looks like this {'sensorType': 'Temperature', 'reading': '87.00'} when I open the URL that loads the view I get this error "JSONDecodeError at /sensor Expecting value: line 1 column 1 (char 0)". this is the function that receives the data in views @csrf_exempt def index(request): print("\n") data = json.loads(request.body) type = data.get("sensorType", None) reading = data.get("reading", None) print(data) print(type) print(reading) sensor = Sensor() sensor.SensorType = type sensor.Reading = reading sensor.save() return HttpResponse("Hello") -
how to extract function name from a code string pythonic way?
I have a code string as follows code = '\n function factorial( n ){\n\n let a=1;\n\t\tfor(let c=1; c<=n; c++){\n\ta=a*c;\n\t\t}\n\n\treturn a;\n }\n\n\n ' The name of the function is after function keyword and before the first '('. I know how to solve this problem but i was wondering whether there is a short pythonic way to extract function name from the given code string. I appreciate any insights. Thanks!