Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reading an SPSS file (.sav or .zsav) inmemory using pyreadstat
I've been developing a Django application. I know that there are some different of reading an SPSS file. One way is using pandas. import pandas as pd file_path = "./my_spss_file.sav" df = pd.read_spss(file_path) Another way is using pyreadstat import pyreadstat df, meta = pyreadstat.read_sav('./my_spss_file.sav') As you can see above, unlike pandas, using using pyreadstat I can get the meta information such as variables and values of labels. So, that is what I am using. The problem with this pyreadstat is that I cannot use it for inmemory read. After uploading an spss file from a browser, each time I have to upload it to a directory and then read the file from there using pyreadstat module. def upload_file(request): result = None # Get the context from the request. context = RequestContext(request) if request.is_ajax(): if "POST" == request.method: global my_df global _explore global base_dir file = request.FILES['file'] file_name = file.name base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) try: my_df = None # Determine the type of the file and get the dataframe if file_name.endswith('.csv'): my_df = pd.read_csv(file, header=0) elif file_name.endswith('.xlsx') or file_name.endswith('.xls'): my_df = pd.read_excel(file, header=0) elif file_name.endswith('.sav') or file_name.endswith('.zsav'): handle_uploaded_file(file, str(file)) file_path = os.path.join(base_dir, "upload\\") + file_name my_df = util.read_spss_file(file_path) def read_spss_file(f_name): df, meta … -
generic class based view CreateView - how to compare the request.user to a certain modelobject.user
Inside my generic CreateView class based view, I want to compare the request.user to a certain modelinstance.user, and if the users dont match, I want to raise a 404 error, how can I achieve this? Which method inside the generic.CreateView should I modify and how? Thanks! -
ERROR while connecting static and media files in django
i have tryng configure my static files but still dont works so as i guess when i run gunicorn service and it takes wsgi file to run in 8000 port also takes settings with allows hosts and databases and i wonder why it cannt read static files when i run server its not django responsible to read static file and i need to set in nginx conf file ? what am doing wrong?thanks web is main file with manage.py my nginx.conf file server { listen 80; server_name examples.com www.example.com; client_max_body_size 4G; charset utf-8; location /media/ { alias /var/www/html/web/media/; } location /static/ { alias /var/www/html/web/static/; } location / { proxy_pass http://127.0.0.1:8000; } production settings STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_DIRS = ("/var/www/html/web", ) -
How can I call in Django template a coordinate of a list's element?
I created a class that has some attributes. One of them is a list that has coordinates as elements. Here's the python code: @attr.s class ProductMetadata: features: list = attr.ib() #some other attrs standard = ProductMetadata( features=[(True ,"Up to 1000 DMs"), (False, "Ludicrous mode"), (False, "Premium Support")], # the other attrs ) And, since I'd like to write a list where the customer can see whereas he can benefit from a feature given his package, here's the code somehow I'd like to write: <ul> {% for feature in product.metadata.features %} <li> <i class="lni {% if the first coordinate of the element is True %}lni-checkmark active"{% else %} lni-close {% endif %}></i>{{ the second coordinate }}</li> {% endfor %} </ul> Here's the result I'd like to get (visually): Also, given that the class name is ProductMetadata, and that the product.attr works when I just use Stripe (without the class), is using product.metadata.attr correct? Thanks a lot! -
Django Dynamic Table Class Objects
I cannot figure out a way in models.py to pull data from the database to populate the objects in another class. models.py: from django.db import models informationtitles = ["title1" , "title2"] class informationtable(models.Model): informationtitle = models.CharField(max_length=30, null = True) class storedinformation(models.Model): pass for dataHeaders in informationtitles: storedinformation.add_to_class(dataHeaders, models.CharField(max_length=30, null = True)) This code works but I would like: informationtitles = ["title1" , "title2"] To be something like: informationtitles = informationtable.informationtitle.objects.all() -
Django Listview pagination; Page is paginated correctly but page_obj not working in template
I am new to Django and trying to refactor my function-based views to CBVs. I got everything else working, and the pagination works(it shows "JOBS_PER_PAGE" jobs on each page), but the only problem is that in the template, page_obj does not work. Although the page has next pages, the page navigator is all greyed out and disabled. page_obj.number doesn't return anything. I looked at other posts, but I couldn't find any useful information. Is there any extra step I need to do to get page_obj to work correctly in the template? urls.py urlpatterns = [ path('', views.landing_page, name='landing-page'), path('search/<int:pk>/', views.SearchView.as_view(), name='search'), path('apply/<int:pk>/', views.apply, name='apply'), path('result/<int:pk>/', views.result, name='result'), path('start/', views.start, name='start'), path('eor/<int:pk>', views.end_of_round, name='end-of-round'), path('closing/<int:pk>', views.closing, name='closing') ] views.py class SearchView(ListView): model = Job context_object_name = 'jobs' template_name = 'simulation/search.html' paginate_by = JOBS_PER_PAGE def setup(self, request, *args, **kwargs): super().setup(request, *args, **kwargs) self.respondent = Respondent.objects.get(pk=self.kwargs['pk']) if self.respondent.is_out_of_money(): self.respondent.increment_round() self.respondent.save() return redirect('simulation:end-of-round', pk=self.respondent.id) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['respondent'] = self.respondent return context def post(self, request, *args, **kwargs): self.respondent.subtract_from_balance(request.POST.get('more_info_fee')) self.respondent.add_to_jobs_more_info(request.POST.get('selected_job')) self.respondent.log_time_spent() self.respondent.increment_stage() self.respondent.save() return redirect('simulation:search', pk=self.respondent.id) search.html {% if is_paginated %} <nav aria-label="..."> <ul class="pagination"> {% if page_obj.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ page_obj.previous_page_number }}">Previous</a> </li> <li class="page-item"> <a class="page-link" href="?page={{ … -
Display Polygon in Leaflet Map from Geodjango
I'm developing a geospatial mapping application using geodjango and django-leaflet which lets users draw a polygon on a map and save that polygon to a model. I thought it would be simple to extract the saved polygon from the model and render it on a Leaflet map embedded in a template. However, I'm having considerable difficulty doing so. This is mostly due to me being a new web developer (I'm especially new to JS). Here's what I have so far: models.py: class newJob(BaseModel): job_name = models.CharField(max_length=64) job_desc = models.CharField(max_length=64) job_loc = models.PolygonField() user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) The spatial data is saved successfully to the model using the form I have created (not shown). I have then created a simple function-based view to pull the required data from the database. I have created a 'raw' object (job_loc) and also serialized the data to geojson to create json_loc (as I'm not sure which is best to work with). views.py: def viewjob(request): req = request.GET job_name = newJob.objects.values_list('job_name', flat=True).get(pk=req['search']) job_desc = newJob.objects.values_list('job_desc', flat=True).get(pk=req['search']) job_loc = newJob.objects.values_list('job_loc', flat=True).get(pk=req['search']) json_loc = newJob.objects.filter(pk=req['search']) json_loc = serialize('geojson', json_loc, geometry_field='job_loc') context = { 'job_name': job_name, 'job_desc': job_desc, 'job_loc': job_loc, 'json_loc': json_loc } print(context) return render(request,'viewjob.html', context) … -
Django NoReverseMatch but parameter is passed in
I know this seems a pretty common error but after spending the best part of 90 minutes searching the site for an answer that helps me I just cannot figure out what's causing it. in my profile.html I have a link to view a users list of followers <a href="{% url 'view_user_followers' viewuser.user.id %}" class="text-white followers-link">Followers: {{ followers_count }}</a> but when I have this link in the page it throws me this error: Reverse for 'view_user_followers' with arguments '(11,)' not found. 1 pattern(s) tried: ['users/view_user_followers$'] the view for this in my views.py is: def view_user_followers(request, user_id): viewusers = Profile.objects.filter(user_id=user_id) following_count = Follow.objects.order_by('-created').filter(user_id=viewusers.user_id).count() followers = Follow.objects.order_by('-created').filter(following_user_id=viewusers.user_id) followers_count = Follow.objects.order_by('-created').filter(following_user_id=viewusers.user_id).count() context = { 'viewusers': viewusers, 'followers': followers, 'following_count': following_count, 'followers_count': followers_count } return render(request, 'accounts/user_followers.html') and in my urls.py I have: urlpatterns = [ path('<int:user_id>', views.profile, name='profile'), path('view_user_followers', views.view_user_followers, name='view_user_followers') ] Whats confusing me most is that also in my views.py for Profile I have: def profile(request, user_id): viewusers = Profile.objects.filter(user_id=user_id) reviews = Review.objects.order_by('-review_date').filter(user_id=user_id) favourites = Favourite.objects.order_by('id').filter(user_id=user_id) does_follow = Follow.objects.filter(following_user_id=user_id, user_id=request.user.id).exists() following = Follow.objects.order_by('-created').filter(user_id=user_id) following_count = Follow.objects.order_by('-created').filter(user_id=user_id).count() followers = Follow.objects.order_by('-created').filter(following_user_id=user_id) followers_count = Follow.objects.order_by('-created').filter(following_user_id=user_id).count() context = { 'viewusers': viewusers, 'reviews': reviews, 'favourites': favourites, 'does_follow': does_follow, 'following': following, 'followers': followers, 'following_count': following_count, 'followers_count': followers_count … -
django-admin fatal error when trying to create files
I installed django simply using pip install und want to create a file, but when I use django-admin, I get an error: Fatal error in launcher: Unable to create process using '"c:\program files\python39\python.exe" "C:\Program Files\Python39\Scripts\django-admin.exe" startproject p1': what is wrong here? All I can read here is, that it is searched for an object that has something to do with python 3.9. I used it, but deinstalled it to install version 3.8, which I am using currently. -
Install Django on puthon 3.8
I try install django on python 3.8 by command pip install django but I get ERROR: Could not find a version that satisfies the requirement django (from versions: none) what can I do? -
Cannot assign “1”: “Plugins.category” must be a “PluginsCategory” instance. Django and ForeignKey
I am trying to save a new record to the database, and an error occurred while writing to the ForeignKey Cannot assign "1": "Plugins.category" must be a "PluginsCategory" instance. What's wrong? models.py class Plugins(models.Model): title = models.CharField(max_length=150, verbose_name='Название') category = models.ForeignKey('PluginsCategory', on_delete=models.PROTECT, related_name='get_category') def get_absolute_url(self): return reverse('urls_view_current_plugins', kwargs={'pk': self.pk}) def __str__(self): return self.title class PluginsCategory(models.Model): title = models.CharField(max_length=150, db_index=True, verbose_name='Наименования категории') def __str__(self): return self.title tags.py def add_plugin_in_db(): plugin = Plugins() plugin.title = 'title' plugin.category = 1 plugin.save(force_insert=True) On the site C:\PythonProject\ServiceCRM3\venv\lib\site-packages\django\db\models\fields\related_descriptors.py, line 215, in __set__ raise ValueError( … ▼ Local vars Variable Value instance <Plugins: Заказы> self <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x000000000438DAF0> value 1 -
Login Django-project
Hello, help me figure out the logic behind the Django ezine. Each student should have many grades in different disciplines. Is there a "tuple" field type in django? -
Python get variable name instead of value
I need to get the variable name instead of the variable value. I have a situation like this: Type1 = 1 Type2 = 2 fields = [Type1, Type2] for field in fields: value = field.__name__ #or something like print(value) Expected result is Type1 Type2 Ty for helping -
Django template run {{ }} without execute
In django template I write <p>"{{sometext}}"</>p. But when it is executed it convert like <p>""</p>. How to avoid this. -
How to pass slug to request.data in list view of Django REST Framework
I have entered a slug in an URL and I want the entered slug as a request.data in some other URL. Specifically, urls.py > router = routers.DefaultRouter() > > router.register(r'courses', CollegeCourseViewSet, > basename='college_course_list') > > urlpatterns = [ > path('api/v1/colleges/<slug:slug>/', include(router.urls)), ] Here I want the college slug as request.data to filter the courses of that college in the ViewSet. views.py > class CollegeCourseViewSet(viewsets.ReadOnlyModelViewSet): > queryset = Course.objects.all() > lookup_field = 'slug' > filter_backends = (SearchFilter, DjangoFilterBackend) > search_fields = 'name' > > def list(self, request, *args, **kwargs): > try: > queryset = self.queryset > queryset = queryset.filter(courses_colleges__college__slug=request.data) > return Response(CourseSerializer(queryset, many=True).data, status=status.HTTP_200_OK) > except queryset is None: > raise Http404 But the request.data is empty when outputted. Is there any specific method to send the request.data to the list function in ViewSet? Thanks in advance. -
Django post save and overwriting not working in m2m field
This is my model : class Size(models.Model): size = models.IntegerField() price = models.FloatField() def __str__(self): return f"{self.size} - {self.price}" class ItemSold(models.Model): dimension_and_price = models.ManyToManyField(Size) and many more... and after I save the model I want to do some logic, so I tried using Django post_save and overwriting save method but they didn't work for me, as m2m field is empty. Then after reading docs and articles I learnt about m2mchange and the problem with that is that it runs function two times def calculate_price(sender, instance,action="post_add", *args, **kwargs): print("It runs two times") m2m_changed.connect(calculate_price, sender=ItemSold.dimension_and_price.through) Please help PS Sorry for bad English -
sqlalchemy relations- sqlalchemy.exc.InvalidRequestError:
I have 2 files in models directory: i want Relation between Member and Bot i cant import Bot to member.py because of Circular Dependencies member.py : from sqlalchemy import Column, String, Date, Integer, select, func, extract from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import column_property, relationship class Member(Base): __tablename__ = 'member' id = Column(Integer, primary_key=True, autoincrement=True) first_name = Column(String) last_name = Column(String) bots = relationship('Bot', back_populates='owner') and bot.py : from sqlalchemy import Column, String, Integer, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from models.member import Member class Bot(Base): __tablename__ = 'bot' id = Column(Integer, primary_key=True, autoincrement=True) title = Column(String) owner_id = Column(Integer, ForeignKey(Member.id)) owner = relationship(Member, back_populates='bots') this error: Traceback (most recent call last): File "/home/hmn/.virtualenvs/tost/lib/python3.8/site-packages/sqlalchemy/ext/declarative/clsregistry.py", line 322, in _resolve_name rval = d[token] File "/home/hmn/.virtualenvs/tost/lib/python3.8/site-packages/sqlalchemy/util/_collections.py", line 729, in __missing__ self[key] = val = self.creator(key) File "/home/hmn/.virtualenvs/tost/lib/python3.8/site-packages/sqlalchemy/ext/declarative/clsregistry.py", line 301, in _access_cls return self.fallback[key] KeyError: 'Bot' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<input>", line 1, in <module> File "<string>", line 2, in __init__ File "/home/hmn/.virtualenvs/tost/lib/python3.8/site-p util.raise_( File "/home/hmn/.virtualenvs/tost/lib/python3.8/site-packages/sqlalchemy/util/compat.py", line 182, in raise_ raise exception sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class Member->member, expression 'Bot' failed to locate a name ('Bot'). If … -
Django REST: How do i return SimpleJWT access and refresh tokens as HttpOnly cookies with custom claims?
I want to send the SimpleJWT access and refresh tokens through HttpOnly cookie. I have customized the claim. I have defined a post() method in the MyObtainTokenPairView(TokenObtainPairView) in which I am setting the cookie. This is my code: from .models import CustomUser class MyObtainTokenPairView(TokenObtainPairView): permission_classes = (permissions.AllowAny,) serializer_class = MyTokenObtainPairSerializer def post(self, request, *args, **kwargs): serializer = self.serializer_class() response = Response() tokens = serializer.get_token(CustomUser) access = tokens.access response.set_cookie('token', access, httponly=True) return response It's returning this error: AttributeError: 'RefreshToken' object has no attribute 'access' The serializer: class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): print(type(user)) token = super().get_token(user) token['email'] = user.email return token But it's just not working. I think I should not define a post() method here like this. I think if I can only return the value of the get_token() function in the serializer, I could set it as HttpOnly cookie. But, I don't know how to do that. How do I set the access and refresh tokens in the HttpOnly cookie? -
Getting information of a model from another model in django
My project is simply a patient will upload an image of his latest medical report that includes blood pressure , hemoglobin and so on , the data will be extracted from the image using ocr . later these data should be shown in a dashboard This is the model for the image upload: models.py class ImageUpload(models.Model): imageTitle = models.CharField(max_length = 150) image = models.ImageField(upload_to=media , max_length=100) created = models.DateTimeField(auto_now=True, auto_now_add=True) and this is the model that will be created as an instance of the last model created: class ImageData(model.Model): haemoglobin = models.FloatField() bloodPressure = models.FloatField() mch = models.FloatField() where haemoglobin , bloodPressure , mch are the data to be extracted . So I have two questions: 1) how can I create an instance of ImageData model as an instance of ImageUpload is created ? 2) I have already a function for the ocr , I tested it manually , however I want to know what is the best way to put this function within this code , foe example is it better to write make this function a method in the ImageUpload class ? for example:- class ImageUpload(models.Model): --------- def get_Image_data(image):#using ocr --------- return text -
Api_key in django rest framework
I want to implement django rest framework that have connection to bot(machine that write by python ) , now I generate api key in my admin panel , but I don't know how can I use it in my bot? -
Django + ReactJS - How to get CSRF cookie for forms
I'm new to Django and ReactJS and am trying to do something fairly standard. But even after reading many blogs and stack overflow questions, I cannot figure out what I am doing differently / wrong? I have a Django server running on localhost:8000 and ReactJS on localhost:3000 The ReactJS has a simple sign-in form. The form will need a CSRF token to do a POST request. But I keep getting a CSRF Cookies not set message. I have installed CORS middleware with the following settings CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = ['http://localhost:3000'] # CORS_EXPOSE_HEADERS = ['Set-Cookie'] # CSRF_TRUSTED_ORIGINS = ['localhost:3000/'] I am not using rest_framework because it seems that it is only needed to serialise objects to JSON and define routes. As I have existing methods and routes for those, I assumed that rest_framework would not be needed I ping the server initially as follows @ensure_csrf_cookie def ping(request): return JsonResponse({'ping': True}, status = 200) As a result, I see a Set-Cookie in the response header. So far, so good. But I cannot access this header - and hence the cookie in ReactJS. CORS_EXPOSE_HEADERS also doesn't seem to work. Plus, it seems Set-Cookie is one of those forbidden headers that can't be … -
Customize django-allauth social login and call back URL (redirect them through a front-end service )
When I sign up/sign in with my social account using django-allauth like http://localhost:8000/accounts/google/login/ Now after doing authentication, Google redirect us back to the below callback URL as http://localhost:8000/accounts/microsoft/login/callback/ I want to change the above URLs to be redirected to the frontend service and then redirect it from there to our backend server. Is there a way around to achieve this? Because due to security reasons I only our frontend server to interact with our back, not any other third part. -
Is there a way to update a foreign key field using an SQL Update Query in Django
I have two classes, and I am attempting to move a field from one to the other as efficiently as possible. The database is large, so it's ideal if we can use an SQL Update query within Django or a direct SQL query. My database is PostgreSQL. Class Order(models.Model): name = models.TextField(null=True, blank=True) address = models.ForeignKey(Address, on_delete=models.PROTECT) Class Address(models.Model): name = models.TextField(null=True, blank=True) I know I can do this manually, but I was hoping to be able to run an SQL Update query like so: Order.objects.all().update(address__name=F('name')) But I'm not able to update a foreign key field using the update command. Any suggestions for an alternative either in Django or directly in SQL - as opposed to just writing out the following - is appreciated. for order in Order.objects.all(): address = order.address address.name = order.name address.save() -
python flask base.html doesn't display {{user.username}
Here is my base.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="{{ url_for('dashboard') }}">SOM</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Dashboard</a></li> <li><a href="#">Settings</a></li> <li><a href="#">Profile</a></li> <li><a href="{{ url_for('logout') }}">Log Out</a></li> </ul> <form class="navbar-form navbar-right"> <input type="text" class="form-control" placeholder="Search..."> </form> </div> </div> </nav> </body> </html> profile.html: {% extends "base.html" %} <h3>{{user.username}}</h3> When I go to the profile page it doesn't display the username but if I type something else there like <h1> Hello </h1> I can see it. -
How to pickle sklearn in Django cache
I would like to cash a my model which comprises of sklearn and a tensorflow models. class KNN: def __init__(self, modelName, neighbors=None, metric="cosine"): self.model = NearestNeighbors(n_neighbors=self.neighbors, metric=metric) self.vg99 = tf.keras.applications.VGG19(weights='imagenet', include_top=False, input_shape=shape_img) I am using the following code to cache it in my Django app: model_name = 'knn_vg99' knn = KNN(model_name) cache_key = model_name cache.set(cache_key, knn) And I am getting the following error: File "/home/projects/searchengine/searchengineenv/lib/python3.7/site-packages/django/core/cache/backends/filebased.py", line 54, in set self._write_content(f, timeout, value) File "/home/projects/searchengine/searchengineenv/lib/python3.7/site-packages/django/core/cache/backends/filebased.py", line 44, in _write_content file.write(zlib.compress(pickle.dumps(value, self.pickle_protocol))) TypeError: can't pickle weakref objects I have tried both FileBasedCache as well as LocMemCache cache methods. Are there any solutions to pickle my model in such a way? Many thanks for your support