Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to sync local Django sqlite3 data with Heroku's postgres database?
I have a Django website served by Heroku with a model storing data about projects that I've worked on in the past. I already ran makemigrations and migrate locally before pushing to heroku with git and running heroku run python3 manage.py migrate. So, my database models and fields are synced, but I'm asking about the field values. Whenever I update the value of a field for a model instance locally, I want it (the data) to sync with Heroku, and vice versaβsync values I've updated on Heroku in the admin panel with my local sqlite3 database. Is there a command for updating the values of the database itself, or am I missing something? Because I've looked all over the internet for the last hour for how to do this one thing. Side note: I also want the command I'm looking for to sync newly created instances, not just data for existing model instances. -
Python3 Django issues regarding paths and custom decorators
Rather new to Django first time using is. Python is not my strong point in a web context - i'm having issues with my custom decorator I made that will decode the jwt from all requests. decorators.py from django.core.exceptions import PermissionDenied import jwt def verify_token(function): def wrap(request, *args, **kwargs): if request: print('========='.format(request)) jwt.decode(request, 'secret', algorithms=['HS256']) else: raise PermissionDenied wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap views.py from .User_Predictions.PredictionService import PredicitonController from django.http import JsonResponse from rest_framework.views import APIView from .decorators import verify_token class UserPredictions(APIView): @verify_token def generate_full_report(request): _predction = PredicitonController() results = _predction.compile_complete_predition() return JsonResponse(results, safe=False) urls.py from django.urls import path from .views import UserPredictions urlpatterns = [ path('compilePredictions/', UserPredictions.generate_full_report, name='generate_full_report') ] . βββ Analytics β βββ __init__.py β βββ __pycache__ β β βββ __init__.cpython-37.pyc β β βββ settings.cpython-37.pyc β β βββ urls.cpython-37.pyc β β βββ wsgi.cpython-37.pyc β βββ settings.py β βββ urls.py β βββ wsgi.py βββ authentication β βββ admin.py β βββ apps.py β βββ __init__.py β βββ migrations β β βββ __init__.py β βββ models.py β βββ tests.py β βββ views.py βββ biometrics β βββ admin.py β βββ apps.py β βββ bodyfatPrediciton.py β βββ Config.py β βββ __init__.py β βββ models.py β βββ templates β β βββ β¦ -
Django template won't render form errors
After a user has submitted a form with data that fails validation, form.errors in fact collects those errors as I've been debugging the issue. However when I render the page after a POST request, the errors will not be parsed in HTML alongside the fields where errors occur. What needs to change in order for the validation errors to render in the template when user data doesn't pass validation? # view that renders the template @login_required(login_url="/accounts/sign_in/") def new_profile(request, username): form = ProfileForm() import pdb; pdb.set_trace() if request.method == 'POST': user_profile = ProfileForm(request.POST) if user_profile.is_valid(): user_profile.cleaned_data.update(user=request.user) Profile.objects.create(**user_profile.cleaned_data) return HttpResponseRedirect( reverse("accounts:profile", kwargs={'username': username}) ) return render(request, 'accounts/create_profile.html', {'form': form}) # create_profile.html {% extends 'layout.html' %} {% block body %} <form action="{% url 'accounts:new_profile' username=user %}" method="post"> {% csrf_token %} {{ form }} <button type="submit">Submit</button> </form> {% endblock %} -> if request.method == 'POST': (Pdb) n -> user_profile = ProfileForm(request.POST) (Pdb) n -> if user_profile.is_valid(): (Pdb) p user_profile.errors {'birth': ['Enter a valid date.'], 'bio': ['Add more detail to your bio.']} -
How to group products by sellers in django
I am working on a multivendor ecommerce project for academic perspective.I am very beginner in Django. I am struck into this problem.Pls someone help. Here is the models for my Order. In the Order model i have items which is a Many to Many relationship with OrderItem. In OrderItem there is a field item which relates to the Product model. The product model holds the seller information and price. I want my products show on the order-summary grouped by the seller. And create different invoices for each of the sellers. But cannot find how to do that. I want to do something like the following snippet: Seller 1: Invoice Id- ____ Total Price:____ , ProductName - Quantity- Price, ProductName - Quantity- Price, ProductName - Quantity- Price Seller 2: Invoice Id- ____ Total Price:____ ,ProductName - Quantity- Price, ProductName - Quantity- Price The models for my Order app: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) billing_address = models.ForeignKey( 'BillingAddress', on_delete=models.SET_NULL, blank=True, null=True) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) class Product(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) price = β¦ -
When to use render and when to use redirect if you want to create login with session
so i want to make a login with a session , but i dont know when to use render or when to use redirect , here's the code def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') guest = User.objects.get(username=username) role = guest.role user = authenticate(username=username, password=password) if user is not None: if role == 'Business Analyst': login(request, user) request.session['username'] = username return render(request,'index.html',{"username":username}) #return redirect('/home') elif role == 'Admin': login(request, user) request.session['username'] = username #return redirect('/manageuser/') elif role == 'Manager': login(request, user) request.session['username'] = username # return redirect('/approvallist/') elif role == 'Segment Manager': login(request, user) request.session['username'] = username #return redirect('/approvallist/') else: messages.error(request, "Invalid username or password!") else: messages.error(request, "Invalid username or password!") form = AuthenticationForm() return render(request,"login.html",{"form":form}) def index_view(request): #if request.session.has_key('username'): # username = request.session['username'] # return render(request,'index.html',{"username":username}) #else: # return render(request,'login.html',{}) return render(request,'index.html') am i doing this right? about the use of return render? or i must use return redirect? -
Spanning two multi-valued relationships in the same query [Django]
I can span foreign key relationships in django filters like this: brand_asset__business_unit__in=user.owner_for_business_units.id If the last item returns multiple values, I can use __in and all() brand_asset__business_unit__in=user.owner_for_business_units.all() How do I span two m2m relationships in a Teachers have a m2m relationship with I looked through the documentation but it deals with spanning one m2m relationship. -
Getting multiple queryset list of single model
I have a model say: class Abc(models.model): .... ..... Now When performing query(let go all the imports): print(Abc.objects.all()) I am getting multiple list of querySet: Output as <QuerySet [<Abc: ...>, <Abc: .....> , .....]> <QuerySet [<Abc: ...>, <Abc: .....> , .....]> I have to User so I am getting 2 different QuerySet. How can I get all the user's querySet in single list, Wanted output as: <QuerySet [<Abc: ...>, <Abc: .....> , .....]>, <QuerySet [<Abc: ...>, <Abc: .....> , .....]> or in a single list <QuerySet [<Abc: ...>, <Abc: .....> , .....]> But from my knowledge a model should list all the querySet in single list , why am I getting multiple list ? Image of my model and error -
Plotting a timestamp with django and matplotlib
I'm having some trouble creating a view in django, I'm trying to make a web app which will read in from a csv and then display the plot, however the time axis I need to plot from the csv is not a float it is a string, then way I have it here I'm not sure how to plot this timestamp: def showMe(request): fig = Figure() canvas = FigureCanvas(fig) x, y = np.loadtxt('/Users/name/Desktop/garden_app/stored.csv', delimiter=',', dtype={'names': ('time','moisture'), 'formats': ('|S1', np.float)}, unpack=True) plt.plot(x, y, align='center', alpha=0.5, label='Name') plt.ylabel('moisture') plt.xlabel('time') plt.title('Moisture V. Time') buf = io.BytesIO() plt.savefig(buf, format='png') plt.close(fig) response = HttpResponse(buf.getValue(), content_type = 'image/png') return response The csv file I have looks like this: moisture,time,pump,light,temperature 1023,2019-10-27 17:22:27.367391,running,5V,25 Celsius 1023,2019-10-27 17:22:30.402280,running,5V,25 Celsius ... The "ValueError: could not convert string to float: 'time'" comes from the 'formats': ('|S1', np.float) on line 4, I'm just not sure how to change this where one is a number and the other is the timestamp. -
Bulk Update of model fields baseds on user input in admin site
In django, let's say I have a model with an integerfield called "RouteNumber" in my model. I manage all the model entries in the django admin site and I want to assign a route number to more than 100 entries at a time. How can I do that based on a user input? I was thinking using an admin action that would request a number and that all the queryset would be assigned this value In my model.py: class Person(models.Model): Name = models.CharField("Nom du parent", max_length=40, default="") RouteNumber= models.IntegerField("NumΓ©ro de route", default=None, blank=True, null=True) In my admin.py: def assign_route_number # This is where I'm lost ==== number = user_input("Enter a route number") # ======== for obj in queryset: obj.RouteNumber = number obj.save() However I don't know how to get the user input. Is there an easy way to get that? Thank you for your answers -
Django error 'ManagerDescriptor' object has no attribute 'filter'
I am relatively new to django and am running into the error 'ManagerDescriptor' object has no attribute 'filter' when retrieving view 'dashboard' -- below is my view and model. Can anyone point me in the right direction here? Thanks! #views.py def dashboard(request): tabledata_totals = '' if not request.user.is_authenticated: return redirect(settings.LOGIN_URL, request.path) else: orgs = Profile.objects.values_list('assigned_org_ids', 'view_group').get(user_id=request.user.id) tabledata_totals = org_totals.objects.filter(org_id__in=orgs[0].split(',')).aggregate( sum('open_supplement_count'), sum('open_estimate_count'), sum('open_measurement_count'), sum('total_open_count'), sum('supplement_sent_to_ins'), sum('revised_scope_received_additional_items_needed'), sum('homeowner_permission_needed'), sum('three_calls_to_adjuster_without_response'), sum('spoke_to_adjuster'), sum('missing_documents_required_for_supplementation'), sum('wWaiting_on_a_revised_scope'), sum('estimate_created_and_sent_to_customer'), sum('deal_in'), sum('supplement_complete'), sum('eagleview_measurements'), sum('confirmed_received'), sum('confirmed_assigned_to_adjuster'), sum('additional_documentation_needed') ) return render(request, 'HTML/dashboard.html', {'data': tabledata_totals}) #models.py @login_required(login_url='/login/') class org_totals(models.Model): organization = models.CharField(max_length=100, blank=True, null=True) org_id = models.SmallIntegerField(primary_key=True) open_supplement_count = models.SmallIntegerField(blank=True, null=True) open_estimate_count = models.SmallIntegerField(blank=True, null=True) open_measurement_count = models.SmallIntegerField(blank=True, null=True) total_open_count = models.SmallIntegerField(blank=True, null=True) Supplement_Sent_to_Ins = models.SmallIntegerField(blank=True, null=True) Revised_Scope_Received_Additional_Items_Needed = models.SmallIntegerField(blank=True, null=True) Homeowner_Permission_Needed = models.SmallIntegerField(blank=True, null=True) three_Calls_to_Adjuster_Without_Response = models.SmallIntegerField(blank=True, null=True) Spoke_to_Adjuster = models.SmallIntegerField(blank=True, null=True) Missing_Documents_Required_for_Supplementation = models.SmallIntegerField(blank=True, null=True) Waiting_on_a_Revised_Scope = models.SmallIntegerField(blank=True, null=True) Estimate_Created_and_Sent_to_Customer = models.SmallIntegerField(blank=True, null=True) Deal_In = models.SmallIntegerField(blank=True, null=True) Supplement_Complete = models.SmallIntegerField(blank=True, null=True) Eagleview_Measurements = models.SmallIntegerField(blank=True, null=True) Confirmed_Received = models.SmallIntegerField(blank=True, null=True) Confirmed_Assigned_to_Adjuster = models.SmallIntegerField(blank=True, null=True) Additional_Documentation_Needed = models.SmallIntegerField(blank=True, null=True) class Meta: managed = False db_table = 'org_open_totals' -
Django filter based on start date and end date for single day
I have a query start_date = '2019-11-17' end_date = '2019-11-18' events = Event.objects.filter(start_date__gte=start_date,end_date__lte=end_date) This doesn't return any result.. I tried direct mysql query, even this doesn't return any results, SELECT * FROM `events` where start_date >= '2019-11-17' and end_date <= '2019-11-18' Any idea where I am wrong? In my database I have these 3 rows, -
NEED TO UNDERSTAND BETTER THE FORMS IN DJANGO
SO AM NEW TO DJANGO, AND I KNOW HOW TO CREATE FORMS AND DEPLOY THEM ON TEMPLATES, SO FAR SO GOOD, BUT NOW HERE IS WHERE IT GETS ME CONFUSED I KNOW I CAN USE THE CRISPY_FORMS TO MAKE IT LOOK BETTER, BUT WHAT IF I WANT TO USE PLACEHOLDERS IN THE FORMS THAT I HAVE CREATED.... HOW DO I DO THAT? -
Slow Django Page - Doesn't Appear to be caused by SQL
I'm trying to debug a slow Django listview page. The page currently displays all tests (133), as well as the latest result for each test. There are approximately 60,000 results, each result having a FK relationship to a single test. I've optimized the SQL (I think) by selecting the latest result for each test, and passing it in as a prefetch related to my tests query. Django Debug Toolbar shows that the SQL is taking ~350ms, but the page load is ~3.5s. If I restrict the list view to a single test though, the SQL is ~7.5ms, and page load is ~100ms. I'm not fetching anything from S3 etc, and not rendering any images or the like. So my question is, what could be causing the slowness? It seems like it is the SQL, since as the result set grows so does page load, but maybe rendering of each item or something similar? Any guidance on what to look into next would be appreciated. -
return render(request, "index.html", {'index': "<div> dfdafadfasdsad </div>"})
I'm trying to append some html onto my index.html template from a view in django. This is my views.py from django.shortcuts import render from django.http import HttpResponse from .models import Greeting # Create your views here. def index(request): # return HttpResponse('Hello from Python!') return render(request, "index.html", {'index': "<div> dfdafadfasdsad </div>"}) However it is just outputting the index.html without the added html. What am I doing wrong? -
Django 2 multi model update view
I'm having a really hard time trying to get an update view class to work. I'm trying to make a cooking recipe app. I found an example of a createview that handles multiple models. im trying to write an update view, but. When ive plugged in my url, the page renders blank with no records. I think the problem is withthe context data, but my experiance with djagno is very limited. my class is below class RecipeUpdateView(UpdateView): model = Recipe form_class = RecipeForm success_url = '/recipe/' def get(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) ingredient_form = IngredientFormSet() instruction_form = InstructionFormSet() return self.render_to_response( self.get_context_data(form=form, ingredient_form=ingredient_form, instruction_form=instruction_form)) def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) ingredient_form = IngredientFormSet(self.request.POST) instruction_form = InstructionFormSet(self.request.POST) if (form.is_valid() and ingredient_form.is_valid() and instruction_form.is_valid()): return self.form_valid(form, ingredient_form, instruction_form) else: return self.form_invalid(form, ingredient_form, instruction_form) def form_valid(self, form, ingredient_form, instruction_form): self.object = form.save() ingredient_form.instance = self.object ingredient_form.save() instruction_form.instance = self.object instruction_form.save() return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form, ingredient_form, instruction_form): return self.render_to_response( self.get_context_data(form=form, ingredient_form=ingredient_form, instruction_form=instruction_form)) Can any one help me out with this? Many thanks Ben -
creating superuser returns "no such table: accounts_user"
I am creating a rest API using Django-rest-auth, and I have a custom user model in an app named accounts. the problem is after making migrations when I try creating a superuser in the console after I input the email in the email field, I get a bunch of errors telling me "no such table: accounts_user" my settings.py INSTALLED_APPS = [ ... 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', 'accounts', ] # to use old_password when setting a new password OLD_PASSWORD_FIELD_ENABLED = True LOGOUT_ON_PASSWORD_CHANGE = False ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USER_EMAIL_FIELD = 'email' ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_LOGOUT_ON_GET = True # UNSURE ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1 ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400 # 1 day in seconds ACCOUNT_LOGOUT_REDIRECT_URL ='api/accounts/rest-auth/login/' LOGIN_REDIRECT_URL = 'api/accounts/rest-auth/user/' SOCIALACCOUNT_EMAIL_VERIFICATION = 'none' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'opeyemiodedeyi@gmail.com' EMAIL_HOST_PASSWORD = '9j@4lifE' DEFAULT_FROM_EMAIL = 'opeyemiodedeyi@gmail.com' DEFAULT_TO_EMAIL = EMAIL_HOST_USER EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/' REST_AUTH_SERIALIZERS = { "USER_DETAILS_SERIALIZER": "accounts.api.serializers.CustomUserDetailsSerializer", } REST_AUTH_REGISTER_SERIALIZERS = { "REGISTER_SERIALIZER": "accounts.api.serializers.CustomRegisterSerializer", } models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.utils import timezone class UserManager(BaseUserManager): def _create_user(self, email, fullname, password, is_staff, is_superuser, **extra_fields): if not β¦ -
How to properly filter or exclude based on a parameter in Django?
I can do this in Django: query = {field_name: value} if include: return queryset.filter(**query) else: return queryset.exclude(**query) That's bad because there's a fair bit of duplication, and it's rather verbose. I can also do this, which is much simpler: return queryset._filter_or_exclude(not include, field_name=value) But that's also bad, because I'm calling a protected method. Is there a way to combine the best of both? return queryset.filter(exclude=not include, field_name=value) is not a thing. -
How do I get a specific value from an object through foreign key connection in django?
guys! I got the following table and want to get all scad files from objects of Model3D where part of is not null and has the same id as Model3D. Model3D is an 3D printer object that may consists of more than just one part and has therefore the "part of" attribute that holds the id of the original model. class Model3D(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=300) description = models.CharField(max_length=500) original_Model = models.ForeignKey('Model3D', on_delete=models.CASCADE, null=True) creation_Date = models.DateTimeField(auto_now=True) stl_File = models.FileField(null=True, upload_to='models/stlFiles') scad_File = models.FileField(null=True, upload_to='models/scadFiles') parameter_id = models.ForeignKey('Parameter', on_delete=models.CASCADE, null=True) part_of = models.ForeignKey('Model3D', related_name="part_of_model3d", on_delete=models.CASCADE, null=True) I tried the following: part_models_scad_files = Model3D.objects.filter(part_of__isnull=False).select_related(id=self.id) but how do i get the scad files and not only the objects? Thanks for your help, I really want to learn more! -
Django NoReverseMatch when i try add href to the navbar
Hey i learning django from Youtube channel https://www.youtube.com/watch?v=6PX_eVxg5jM But i have a problem. When I add another link in the navigation in base.html I get this error. NoReverseMatch at / Reverse for 'post-new' with no arguments not found. 1 pattern(s) tried: ['post/new/(?P<pk>[0-9]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'post-new' with no arguments not found. 1 pattern(s) tried: ['post/new/(?P<pk>[0-9]+)/$'] Exception Location: C:\Users\kacpe\dev\blog\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 673 Python Executable: C:\Users\kacpe\dev\blog\Scripts\python.exe Python Version: 3.7.5 Python Path: ['C:\\Users\\kacpe\\dev\\blog\\blog', 'C:\\Users\\kacpe\\dev\\blog\\Scripts\\python37.zip', 'C:\\Users\\kacpe\\dev\\blog\\DLLs', 'C:\\Users\\kacpe\\dev\\blog\\lib', 'C:\\Users\\kacpe\\dev\\blog\\Scripts', 'c:\\python37\\Lib', 'c:\\python37\\DLLs', 'C:\\Users\\kacpe\\dev\\blog', 'C:\\Users\\kacpe\\dev\\blog\\lib\\site-packages'] Server time: Pon, 18 Lis 2019 00:37:52 +0100 This is what the rest of my files look like. base.html <!DOCTYPE html> {% load static %} <html lang="pl"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'myblog/main.css' %}"> {% if title %} <title>Django Blog - {{ title }}</title> {% else %} <title>Django Blog</title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="{% url 'myblog-home' %}">Django Blog</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse β¦ -
Problem with upload image from android(retrofit) to django
I would like to send a photo from android app to django. I use django rest framework as backend. When i post through postman everything works and I get 201. But when i try through android, I get 400. Where is the problem? Thanks for help in advance My model: class Photo(models.Model): file = models.FileField(blank=False, null=False) My django view: def post(self, request, *args, **kwargs): parser_classes = (FileUploadParser,) file_serializer = PhotoSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) Retrofit request: @Headers("content-type: multipart/form-data;") @POST("upload") fun checkItem(@Body image: MultipartBody.Part): Observable<CheckDto> That's how i send my photo from android app: val requestFile: RequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file) val body: MultipartBody.Part = MultipartBody.Part.createFormData("file", file.toString(), requestFile) val requestInterface = ApiClient.getClient().create(ApiInterface::class.java) myCompositeDisposable?.add(requestInterface.checkItem(body) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe({ result -> Log.d("Request", result.toString()) }, { error -> error.printStackTrace() }) ) -
VS Code: Python Interpreter can't find my venv
I've been stuck on this for a few days, kindly help me if you can. I have my venv folder on my root project folder. When I try to set the Python Interpreter, it shows me only the Python installed in my machine and not the one in my root folder. It was working fine until I formatted my PC and installed windows 10 64 bits. (was running on windows 7 64 bits prior) Things I have tried: Set the path manually via pythonPath and/or venvPath, in both workspace and user settings: "python.pythonPath": "F:/Web Dev/Python/Django/project_x_v2/backend/venv/Scripts/python.exe", "python.venvPath": "F:/Web Dev/Python/Django/project_x_v2/backend/venv/Scripts/python.exe", It shows me the correct location in the placeholder but I don't have the option to choose it from the dropdown list: Any ideas how I can solve this? Thank you very much. -
Confused with multiple dimension dictionaries
I got this method which returns a multi-dimensional dictionary. def get_apps(): menu_one = { 'name': 'Apps group one', 'menu_one_app_one': { 'name': 'app one!', 'icon': 'fa-rocket', 'url': '/Url' }, 'menu_one_app_two': { 'name': 'app two!', 'icon': 'fa-user', 'url': '/Url2' } }, menu_two = { 'name': 'Apps group two', 'menu_two_app_one': { 'name': 'app three!', 'icon': 'fa-clipboard', 'url': '/Url3' }, 'menu_two_app_two': { 'name': 'app four!', 'icon': 'fa-users', 'url': '/Url4' } } return menu_one, menu_two So in my Django view I'm calling the method get_apps() in order to get the apps with their attributes and show them on different groups like this: def my_django_view(request): apps = get_apps() return render(request, "apps.html", {'apps': apps}) And the idea is to display them by group in my template like this: {% for menu in apps %} <!-- this is ok! --> <div class="breadcrumb"> <h1>{{ menu.name }}</h1> {% for app in menu %} <!-- here is the part where I am wrong --> <a href="{{ app.url }}" data-toggle="tooltip" title="{{ app.name }}"> <i class="fa {{ app.icon }}></i> </a> {% endfor %} </div> {% endfor %} I know what is wrong thanks to django since it's saying 'str' has no attr 'name', of course, since it is a dictionary. But then, how β¦ -
<a> tag is not clickable and not linked
Okay , I am not sure if that is a problem with my Django project logic or with my html tags , so here it goes I am trying to make a link that lists all the groups created by a specific user the template code <h1> <a href"{% url 'infrastructure:user-orgs-view' slug=request.user.slug%}"> Your Organizations </a> </h1> url.py part path('accounts/<slug>/orgs', views.UserOrgsView, name='user-orgs-view' ) my view def UserOrgsView(request, slug): orgs = Profile.objects.get(slug=slug).organization_set return render(request, 'user_orgs.html', { 'orgs' : orgs}) the only css I am using on this page body { text-align: center; vertical-align: middle; } p *{ vertical-align: middle; } what happens is the tag appears as normal text , not clickable .. not linked .. nothing .. any idea why is that happening ? -
How do I auto increment field that is part of unique_together in Django admin
Basketball Game has 4 Quarters. I would like Django to auto increment Quarter.number for each Game in Admin, so I don't have to always correct them manually. Example models.py class Game(models.Model): name = models.CharField() class Quarter(models.Model): number = models.IntegerField(help_text='quarter number from 1 to 4') game = models.ForeignKey(Game) class Meta: unique_together = ['game', 'number'] So number in Quarter can be 1, 2, 3 or 4 (or more for other sports) and should be set to 1 by default. After saving first quarter for one Game it should suggest number=2 for the next entry of the same Game. The incremented numbers should also get shown correctly in admin.TabularInline if I set Quarter as inline of Game in admin.py (in below code Django would by default show 3 entries for a new Game, but all would have default number=1): class QuarterInline(admin.TabularInline): model = Quarter class Game(admin.ModelAdmin): inlines = [QuarterInline] How can I achieve that number gets incremented by default for each game? -
Is there a way for Django to accept naive datetimes with USE_TZ=True, or to suppress warnings?
Our company has been a long-time user of Django -- for more than 10 years. We are currently running Django 1.11.26. We've dealt with a lot of datetime-related issues over the years, but our current issue is proving challenging. Our goal is to do the following: use Django's timezone support (setting USE_TZ=True) with UTC as default time zone for a couple of denormalized fields (daily rollups of energy data) store naive datetimes As is documented in many Stack Overflow questions, Django will issue a warning with datetime field values set to a naive datetime: RuntimeWarning: DateTimeField received a naive datetime...while time zone support is active. We think our use case for storing naive datetime is a reasonable one. While for almost all our datetime fields it make sense to use UTC, for certain kinds of daily rollups we want to store a naive/agnostic datetime indicating the start datetime of the day in the local time zone (multiple time zones for different objects). By using a naive datetime, we are able to use datetime-related filters. Therefore if we are summarizing certain kinds of energy rollups for a given datetime, we can find the rollup for the same local datetime for buildings β¦