Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use update in django admin with custom function
this is my first question in Stack Overflow. I am trying to make an admin action to update the price of an asset. It firsts set the last_update_date to today/now and I want to set the last_price to the current market price. The last part is not working as it is not updating. Admin.py @admin.action(description='Update asset price') def update_price(modeladmin, request, queryset): queryset.update(last_update_date = timezone.now()) for q in queryset: q.last_price = get_close_price(q.ticker) #does not change anything class AssetAdmin(admin.ModelAdmin): actions = [update_price] admin.site.register(Asset, AssetAdmin) Models.py class Asset(models.Model): ticker = models.CharField( verbose_name="Ticker", max_length=5, unique=True, ) last_price = models.DecimalField( verbose_name="Last Price", max_digits=8, decimal_places=2, validators=[MinValueValidator(0)] ) last_update_date = models.DateTimeField( verbose_name="Last update date" ) class Meta: ordering = ['ticker'] def __str__(self) -> str: return self.ticker Custom function (from Alpha Advantage API) def get_close_price(SYMBOL): params["symbol"] = SYMBOL close_price = get(URL, params).json() close_price = close_price["Global Quote"]["05. price"] return close_price #returns an int -
DJANGO - The HTTP GET Request return nothing
I was running a python script that returned URLs of google search about a topic and it worked so I tried to embed this script in Django to display these URLs on a webpage but it doesn't work anymore and does not display any error Where did I go wrong? urls.py in AppWEB from django.urls import path from . import views urlpatterns = [ path('', views.scrap, name='scrap') ] view.py in AppWeb def fetch( query): params = { 'q': query, 'sxsrf': 'ALiCzsbh0YEbk_cEHlMBgzgq_tPEfVLYiQ:1660146922900', 'ei': '6tTzYrPNNsWM9u8PyLOOuAc', 'ved': '0ahUKEwiz6vSc0bz5AhVFhv0HHciZA3cQ4dUDCA0', 'tbs': 'qdr:d', 'gs_lcp': 'Cgdnd3Mtd2l6EAMyBAgjECcyCAguEIAEENQCMgUILhCABDIFCAAQgAQyBQgAEIAEMgUIABCABDIFCC4QgAQyCAguEIAEENQCMgsILhCABBDHARCvATIFCAAQgAQ6BAgAEEM6DgguEIAEEMcBENEDENQCOgsILhCABBDHARDRAzoFCAAQkQI6BwgjEOoCECc6BwguENQCEEM6BAguEENKBAhBGABKBAhGGABQAFjWFmCDGWgCcAF4AoABkweIAfQekgELMi00LjIuMC4xLjKYAQCgAQGwAQrAAQE' } headers = { 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'accept-language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7', 'cache-control': 'no-cache', 'cookie': 'OTZ=6594569_52_56_174240_52_315300; SID=Mwgr1yh_8pdqxcCW4bAmUDoP5GOeVkusbuzcWHdOYXlNadWmdbOUtPITFz1UUQ3OM8vseA.; __Secure-1PSID=Mwgr1yh_8pdqxcCW4bAmUDoP5GOeVkusbuzcWHdOYXlNadWmRmqrl9iD_9UOIZNkvbqX-Q.; __Secure-3PSID=Mwgr1yh_8pdqxcCW4bAmUDoP5GOeVkusbuzcWHdOYXlNadWm-ywqR6vV-7MXRA_OAoLNSQ.; HSID=APDjrCSjYxzBvkMxC; SSID=AsSz-gQXwFFeJqQzw; APISID=5Qwkn_cNhMDuRqpZ/AYczojbKYldQo2t5b; SAPISID=wxHQFonmSjj6gGfI/A6yfUPmtjo4OFWvWX; __Secure-1PAPISID=wxHQFonmSjj6gGfI/A6yfUPmtjo4OFWvWX; __Secure-3PAPISID=wxHQFonmSjj6gGfI/A6yfUPmtjo4OFWvWX; OGPC=19022622-1:; SEARCH_SAMESITE=CgQIjpYB; AEC=AakniGMUfMDPvK8aZ7e5s1miz5lAntjOEygTd68cx9N_z5Fn3uDUsuzpZvs; 1P_JAR=2022-08-12-11; NID=511=tk_V5K8omiV0ceKov6QEdmx7ZHv09DNibXnysZs-9qSzgrEd0Q2PhMZVvo4OLQNzxU7NEruKDmY-DIAvlXwIooK6EPJ2dFHgSc_gb3ukJxpdYSyf6cUl30ZMJb_p-9whuvDcv-EUGed7mD7e1Vn4BzICgaDnrL1gw3PGPA78T188TXjPfPQg-DULaqdIOiwxgEsFD2zz5SbHuW0G9bm5dOq2n22Hw4d2lVGSA6w9nBzpLaeMHQUObSp_Aua2CKm1WqKdwH4Isjd84aNc1cMdEGYeqcIScj32M0xBvThOCynpQutIyszjHl0NaN9js0m06wrM51XHJ-EXidLPoVCqRE88txdEmKDJ8qcSREpYbuddzCMBKIg7u1NEpAm81nih; SIDCC=AEf-XMRyfzEKl27JhtXmvgFbTAk1-0YKLGcy9fOOR6lPAULVKhiY3ZfPQVTib3S3S1BmrDf1O0U; __Secure-1PSIDCC=AEf-XMTBmMvKCbMLFwPKBRDd3u1rlbKfgVxzVV1SQZFKucrNE9q-FEczUfVA1miYsfyX_0ypDJk; __Secure-3PSIDCC=AEf-XMSO1Xh3vQg15LldTb_mzifg8hacgWmM70oDPo8lo-jutQ7Ho9dEoeegIgEW6Yr2iaAsGuoz; DV=o66_OU3929pTIBy4P1MyROsAdBYeKRhfk61DJytXfAAAAAAifm2YC1-efQAAAHh0x-PxVD2eJgAAAGy871Dv-DMjFQAAAA', 'referer': 'https://www.google.com/', 'upgrade-insecure-requests': '1', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.134 Safari/537.36 OPR/89.0.4447.83' } base_url = 'https://www.google.com/search' params['q'] = query # Make HTTP GET request return requests.get(base_url, params=params, headers=headers) def scrap(request): response = fetch('Parti Authenticité et Modernité(pam)') context = { 'url': response.url, 'code': response.status_code, } return render(request, 'index1.html',context) index1.html <p>Google search URL is : {{context.url}}</p> <p> status of code is : {{context.code}}</p> I got as a result -
Can't add a new Django model instance through admin "Can't resolve Keyword"
When I go to my admin panel and try to add a new instance of my Clip model I get the error message Cannot resolve keyword 'title' into field. Choices are: clip, description, endChapter, id, name, order, saga, saga_id, startChapter, even though the only fields the Clip model has at the moment are description, arc, chapter, viewers, characters, author, order, videoURL, verboseDescription. I've have no migrations to make so really unsure what's gone wrong. -
Docker: pg_config executable not found in docker?
i am trying to use docker in my django project, i am new to using docker and i do not really know where the error is coming from. I have read so many stackoverflow questions related to this issue but all the solution are not working for me. Maybe there is a new way to fix the bug. Please what the really the issue and how can i fix it? This is how my Dockerfile looks: FROM python:3.8.13-slim-buster WORKDIR /app COPY ./my_app ./ RUN pip install --upgrade pip --no-cache-dir RUN pip install psycopg2 --no-cache-dir RUN apk del build-deps --no-cache-dir RUN pip install -r /app/requirements.txt --no-cache-dir RUN \ apk add --no-cache postgresql-libs && \ apk add --no-cache --virtual .build-deps gcc musl-dev postgresql-dev && \ python3 -m pip install -r requirements.txt --no-cache-dir && \ apk --purge del .build-deps CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] # CMD ["gunicorn", "main_app.wsgi:application", "--bind"] This is the full trace_back PS C:\Users\Destiny\Desktop\StridEarn-master> docker build -t myimage . Sending build context to Docker daemon 12.13 MB Step 1/9 : FROM python:3.8.13-slim-buster ---> 289f4e681a96 Step 2/9 : WORKDIR /app ---> Using cache ---> 06ecbb3b2e23 Step 3/9 : COPY ./my_app ./ ---> Using cache ---> f00b6ccdae31 Step 4/9 : RUN pip install … -
JOIN multiple SELECT statements results and group by seperate SELECT Statement
I am trying to get specific stock provided per supplier between a date range and ordered in descending order: something like this NAME LOCATION TYPE STOCK PROVIDED Tesco Towcester Supermarket 200g Waitrose Towcester Supermarket g SOFEA Milton Keynes Charity g Tesco Daventry Supermarket g I can currently receive the total weight during the collection period like this: # Collections in date range - returns string list of collection ids in date range cursor.execute('SELECT id FROM app1_collection WHERE created_at BETWEEN %s AND %s AND larder_id = %s', [start_datetime, end_datetime, larder_id]) collection_ids = re.findall(r'\d+', str(cursor.fetchall())) collection_ids_string = "'"+"','".join(collection_ids)+"'" print(collection_ids_string) # Total weight of products in date range from collection ids cursor.execute("SELECT SUM(weight) FROM app1_product WHERE collection_id IN ("+collection_ids_string+")") total_weight_in = cursor.fetchone()[0] print(total_weight_in) My Products table looks like: id name weight collection_id ...etc 1 twix 46.0 12 2 mars 540.0 11 3 coca-cola 330.0 11 etc... My Collection table looks like: id created_at larder_id supplier_id volunteer_id 1 2022-08-18 17:31:18.274780 1 3 1 2 2022-08-18 17:31:44.209567 1 3 1 etc... My Supplier table looks like: id name addressFirstLine postCode Type date created_at 1 Tesco Towcester NN12 7BA Supermarket 2022-08-18 17:29:14.477425 2022-08-18 17:29:14.477450 2 Waitrose Towcester NN12 8AB Supermarket 2022-08-18 17:29:30.119565 2022-08-18 17:29:30.119592 etc... My … -
Django "if request.method == 'POST':" is return False
I'm making django app and I have an issue I've never had problem with before. As always in form view, I'm checking if request.method == 'POST' but somehow it returns False, (I can see "request method is not correct" in console) my code looks like that: def recipe_create_view(request): context = {} form = RecipeForm(request.POST or None) IngredientFormset = formset_factory(IngredientForm) formset = IngredientFormset(request.POST or None) context['form'] = form context['formset'] = formset if request.method == 'POST': if form.is_valid(): if formset.is_valid(): form.save() print("made a recipe") for form in formset: child = form.save(commit=False) child.recipe = parent child.save() print("made an Ingredient") else: print("formset is not valid") else: print("form is not valid") else: print("request method is not correct") return render(request, 'recipes/create_recipe.html', context) create_recipe.html file: <form method="POST"> {% csrf_token %} <label>recipe</label> <p>{{form}}</p> <label>ingredients</label> {% for form in formset %} <ul> <label>name</label> <li>{{ form.name }}</li> <label>quantity</label> <li>{{ form.quantity }}</li> </ul> {% endfor %} <div> <input type="submit" value="submit" class="button-33" role="button"> </div> </form> where is the problem >? -
count: int = len(data_from_postgres) TypeError: object of type 'NoneType' has no len()
count: int = len(data_from_postgres) TypeError: object of type 'NoneType' has no len() There is such an error data_from_postgres = query_postgres(state_file=state_file, query=query) count: int = len(data_from_postgres) index: int = 0 actions: list = [] while count != 0: -
UnboundLocalError: local variable 'formset' referenced before assignment in DJANGO
Hey so I have this list of campaigns that have a button to start and stop the process. ''' from django.shortcuts import render from .models import Campaign from .forms import CampaignForm, CampaignStatusFormSet def home_view(request): queryset = Campaign.objects.all() if request.method == 'POST': form_type = request.POST.get('id') if form_type == 'campaign_status': formset = CampaignStatusFormSet( request.POST, request.FILES, queryset=queryset, ) for form in formset.forms: if form.is_valid(): form.save() else: formset = CampaignStatusFormSet(queryset=queryset) campaigns_and_forms = list(zip(queryset, formset)) context = { 'formset': formset, 'campaigns_and_forms': campaigns_and_forms, } return render(request, 'campaigns_in_progress.html', context) ''' But when I run it and click on the button to change play/pause it shows this error. UnboundLocalError: local variable 'formset' referenced before assignment Can anyone help me refactor this code so that it doesn't show this error? -
Sending a server event to redirect a specific pair of users to a particular domain/url
If I want to redirect specific users to different endpoints, how would I implement this logic. Specifically, I would take two user_id's and redirect those specific users to a particular end point. I am using Django for my backend, I also use Django Channels to send some data from my client to my server and I have a React.js frontend I am currently POST ing usernames to a particular API endpoint to create a TwiML object that instructs Twilio to create a conference call. In this view I also get the user_id's associated with each username My assumption is to: Implement some sort of server sent event. Since I have a Django backend, I would use a library like Django Channels to leverage websockets to send some event to my client. Assuming this is the case, what exactly would my websocket be sending to my client? My first thought is to: send the user_id's back to my client through a websocket. Store the user_ids in state, then check what user id's are in state and redirect the users in state to different end points. For some reason I don't think this makes sense (I don't quite know why, but it … -
Django DRF get_queryset, how to join two models?
I have two models, I have to make an endpoint where the results of two tables should appear in the json, which have a fongeringkey that joins them. My code is the following: models.py class Property(models.Model): address = models.CharField(max_length=120) city = models.CharField(max_length=32) price = models.BigIntegerField() description = models.TextField(blank=True, null=True) year = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'property' class StatusHistory(models.Model): property = models.ForeignKey(Property, on_delete=models.CASCADE) status = models.ForeignKey(Status, on_delete=models.CASCADE) update_date = models.DateTimeField() class Meta: managed = False db_table = 'status_history' views.py class StandardResultsSetPagination(PageNumberPagination): page_size = 10 page_size_query_param = "page_size" max_page_size = 1000 class PropertyListView(viewsets.ModelViewSet): http_method_names = ['get', 'head'] serializer_class = PropertyListSerializer queryset = Property.objects.all() pagination_class = StandardResultsSetPagination def get_serializer_class(self): if self.action == 'list': return PropertyListSerializer return PropertyListSerializer def get_queryset(self): queryset = Property.objects.all() if self.request.GET.get('year'): queryset = queryset.filter(year=self.request.GET.get('year')) if self.request.GET.get('city'): queryset = queryset.filter(city=self.request.GET.get('city')) if self.request.GET.get('status'): #what would I do here? pass else: queryset = queryset.order_by('-year') return queryset def list(self, request): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) serializers.py class PropertyListSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Property fields = ('id', 'address', 'city', 'price', 'description', 'year') class StatusHistoryListSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = StatusHistory fields = ('property', … -
Django forms send by default the value of request.user
My intention is that when I enter the Django Admin form to register a new value in a table, in one of the fields (my_field) the username of my user appears, that is, the current user. I tried to set the value inside the __init__ of my form: class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): my_field = request.user The problem is that I can't access request from this point I also tried from get_form(): class MyModelAdmin(ModelAdmin): def get_form(...): form = MyForm form.my_field = request.user return_field But the field is not updated. -
Using a subquery to get a COUNT from a different table in Django
I have these models: class IceCream(models.Model): name = models.CharField(max_length=255) class Topping(models.Model): name = models.CharField(max_length=255) ice_cream = models.ForeignKey(IceCream, on_delete=models.CASCADE, related_name="toppings") is_active = models.BooleanField(db_index=True) I would like to run the following query to get a list of all ice creams, together with a count of the total number of available toppings, which in SQL would look like this: SELECT ice_cream.*, (SELECT COUNT(id) FROM topping WHERE topping.ice_cream = ice_cream.id AND topping.is_active = True) AS total_toppings FROM ice_cream This is a simplified version and there are more parameters in there, but if I can make this work, then things should work out. Can I do this in Django using Subquery expressions? I have not managed to make it work. Or are raw queries my only way out here because of the COUNT that I want to include in the subquery? -
'bytes' object has no attribute 'items' while using list
Getting error in: items = [item for item in body.items()] I just want to add multiple orderitems. I don't know this loop will work after this error. But atleast you will understand my requirement I am giving following data: [ { "service_id": 1, "quantity": 2, "price": 20 }, { "service_id": 2, "quantity": 3, "price": 20 }, { "service_id": 3, "quantity": 4, "price": 20 } ] @api_view(['GET', 'POST']) @csrf_exempt # class CreteOrderView(View): def create_order(request, *args, **kwargs): if request.method == 'POST': now = datetime.date.today() order = Order.objects.create(date=now) order.save() orderid = order.id order_id = orderid data = json.loads(request.body) price = request.session.get('price') quantity = request.session.get('quantity') print('quantity ' + str(quantity)) service_id = request.session.get('service_id') body = request.body items = [item for item in body.items()] for item in items: orderitemcreate= OrderItem.objects.create(order_id_id=order_id, service_id_id=service_id, quantity=quantity, price=price) orderitemcreate.save() return Response({"Order_id":str(order.id), "Order_date":str(order.date), "OrderItems_id" :str(orderitemcreate.id), "service_id" :str(orderitemcreate.service_id), "quantity" :str(orderitemcreate.quantity), "price":str(orderitemcreate.price)}) else: order_qs = models.Order.objects.all().values_list() OrderItem_qs = models.OrderItem.objects.all().values_list() return Response({"Order":str(order_qs),"OrderItem":str(OrderItem_qs)}) -
is it possible to have google-auth within django template?
I have a django app that uses Google's allauth for signing up and logging in, but it first takes me to a google url and to sign in, i.e., my header and other parts of my site are not visible. Once I log in through my google account I'm redirected, so the logic works fine. I'm just wondering if it's possible to have that process be done on my site. -
Why is my DRF view accepting post requests without a csrf token in the headers?
I've just started using Django Rest Framework, and I'm slightly confused about the usage of CSRF tokens in requests. For example, using a standard Django view with the below request would require a CSRF token: fetch("http://127.0.0.1:8000/api/add_item/", { method: "POST", headers: { "Content-Type": "application/json" // "X-CSRFToken": Cookies.get("csrftoken") }, body: JSON.stringify({ content: value }) }) But doesn't seem to with the below DRF implementation: @api_view(['POST']) def add_item(request): serializer = ToDoSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) Is there a reason for this? -
Choice field model django
I have created a model called ingrident where I have store all the ingrident name now I want to pass all these items into choice of a field in another model. How can I do this I don't want to use foreign key because I want to Crete the choice field in inline formset so that the user can Crete recipe by selecting multiple ingrident and giving each ingrident with quantity -
Django Forms allow user to input a list of tuples of unknown length
The app I'm creating requires instances of lessons to be created. For each lesson, any number of instructors can be assigned each with a specific user-inputted role. For example: Lesson 1 has the following instructors role: head, name: Bob role: example, name: Adam role: assistant, name: Joy Because the roles are unknown and the amount of instructors are unknown, the form must be able to accept a list of 'tuples'. Each tuple would then need a textfield and a select field (selecting form a list of instructors). The data would then be saved in this model: class MapInstructorTeach(models.Model): teach = models.ForeignKey(Teach, on_delete=models.CASCADE) instructor = models.ForeignKey(Instructor, on_delete=models.CASCADE) role = models.CharField(max_length=32) The Teach model is just a model specifying the name of the lesson. The instructor model is a list of instructors. How would I go about creating the forms.py class and the html for something like this? I don't even know where to begin. Attempts jQuery infinite input form I've tried using the above method to generate the fields in the front end but couldn't figure out a way to link the input fields to the backend. -
object has no attribute 'set_password'
I am getting an error message of 'UserProfileInfo' object has no attribute 'set_password' I cant seem to find what I missing I did a few projects alike this one but never encountered such error Is there something I missing. I have been trying to fix this for the past hour but still no luck I would appreciate it if you help me out from django.contrib.auth import authenticate, login, logout from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from .forms import UserForm , LoginForm # Create your views here. def home(request): if not request.user.is_authenticated: message = "You are not logged in" return render(request,'home.html',{"MESSAGE":message}) else: message = "You are logged in" return render(request,'home.html',{"MESSAGE":message}) def Register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() registered = True else: print(user_form.errors) else: user_form = UserForm() return render(request,'signup.html', {'user_form': user_form,'registered':registered}) def user_login(request): if request.method == 'POST': login_info = LoginForm(request.POST) if login_info.is_valid(): user = authenticate(username = login_info.cleaned_data["username"], password=login_info.cleaned_data["password"]) if user: login(request,user) return HttpResponseRedirect(reverse('Home')) else: return HttpResponse("Wrong") else: login_info = LoginForm() return render(request,"login.html",{'logininfo':login_info}) My form from cProfile import label from re import L from django import forms from django.contrib.auth.models import User from .models import … -
Django - multiple forms on one view - passing uncreated object to second form
I wonder if it is possible to make two django model based forms on one view which one requires object which is gonna be created by second (Foreign Key). I will show an example to make it more understandable I got these models: class Recipe(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Ingredient(models.Model): name = models.CharField(max_length=200) quantity = models.CharField(max_length=200) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) def __str__(self): return self.name as you can see, Indgredient model takes Recipe as an parameter. I'd like to make a form, which allow user to make new Recipe and Ingredient (or ingredients) which recipe field will be filled by a recipe creating in the same view I was trying to make it this way from .models import Ingredient, Recipe from django.forms import ModelForm class IngredientForm(ModelForm): class Meta: model = Ingredient fields = ['name', 'quantity'] class RecipeForm(ModelForm): class Meta: model = Recipe fields = ['name'] def recipeAndIngredientsCreationView(request): form1 = RecipeForm() form2 = IngredientForm() if request.method == "POST": data1 = { 'csrfmiddlewaretoken': request.POST['csrfmiddlewaretoken'], 'name': request.POST['name'], } form1 = RecipeForm(data1) if form1.is_valid(): form1.save() print("recipe created") data2 = { 'csrfmiddlewaretoken': request.POST['csrfmiddlewaretoken'], 'name': request.POST['name'], 'quantity' : request.POST['quantity'], 'recipe_id': Recipe.objects.get(name=request.POST['name']).id, } form1 = IngredientForm(data2) if form2.is_valid(): form2.save() return redirect('home') context = {'form1':form1, … -
How to use JSON in Django functions
i'm doing a django project for adding and updating things with a mysql database, but i was told that it's not safe to add and update thing directly without JSON, is this possible? how can i do that? here's my create function: form = RoomForm() if request.method == 'POST': form = RoomForm(request.POST) if form.is_valid(): form.save() return redirect('home') context = {'form': form} return render(request, 'tasks/room_form.html', context)``` -
Django custom model save() method, how do you pass a form non-persistent form value?
In Django 4 custom model save() method, how do you pass a form non-persistent form value? For example: The model form below has the non-persistent field called client_secret. class ClientModelForm(forms.ModelForm): client_secret = forms.CharField(initial=generate_urlsafe_uuid) This field will never be saved, it is auto-generated and will be required to make a hash for a persisted field in my model save() method. class Client(models.Model): client_hash = models.BinaryField(editable=False, blank=True, null=True) def save(self, *args, **kwargs): """ Save override to hash the client secret on creation. """ if self._state.adding: "GET THE CLIENT SECRET FROM THE FORM" client_hash = make_hash_key(client_secret) self.client_hash = client_hash How do I get the client secret value from the form above code example? Is this the most appropriate approach? -
My presave slugify function seems to have stopped working in localhost, but not on deployed version? Has this happened to anyone else?
I have been working on a dog adoption website which I have been builing on my local host in python using the Django framework. I have a python page which uses the pre-save function to create a unique slug for the dog whenever one is created. I have now deployed my website and this works absolutely fine. However, as of today this seems to have stopped working on my local host. I cannot find any reason why and it uses the same code as the deployed version of the system. Has anyone ever experience this before and if so does anyone have a solution as I would like to keep working and maintaining on my localhost. class Dogs(models.Model): dog_id = models.AutoField(primary_key=True) dog_name = models.CharField(max_length=100) dog_slug = models.SlugField(unique=True, null=True, blank=True) breed = models.ForeignKey(Dog_breed, on_delete=models.CASCADE) dogs_image = models.ImageField(upload_to='media/') description = models.TextField(default="Description information to be added soon") dog_illness_disability = models.BooleanField(null=True, blank=True) can_live_with_cats = models.BooleanField(null=True, blank=True) can_live_with_dogs = models.BooleanField(null=True, blank=True) can_be_with_children = models.BooleanField(null=True, blank=True) hours_excercise_required = models.IntegerField(default=0) dog_sociability = models.IntegerField(default=0) can_be_left_alone = models.IntegerField(default=0) weight_kg = models.FloatField(default=0) size_range = models.IntegerField(default=0) affection_level = models.IntegerField(default=0) training_level = models.IntegerField(default=0) energy_level = models.IntegerField(default=0) age = models.IntegerField(default=0) age_range = models.IntegerField(default=0) male_female = models.BooleanField(null=True, blank=True) neutered = models.BooleanField(null=True, blank=True) slugify.py: def … -
pip install mysql-connector-python-8.0.30 installed completely - no errors. What are confer for settings .py [DATABASES ]
Environment = macOS Monterey V12.5 M1Max with Visual Studio Code + Python 3.10.6 + Django 4.1 + PIP3. Have successfully installed mysql-connector-python-8.0.30. Current dbsqlite3 has populated tables. When I run python manage.py migrate from dbsqlite3 to MySQL Community 8.0.30 the error messages include "Did you install mysqlclient." Oracle documentation indicates the mysql-connector-python should be used and is all that is needed. Current DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'DatabaseName', (These are the same settings in MySQL Workbench and mySQL that is running in shared mode) 'HOST': '127.0.0.1:3306', 'USER': 'root', 'PASSWORD': 'DDDDDD', Question: Are there separate configuration settings [options] to remove mysqlclient and replace it with mysql-connector-python-8.0.30? -
Can't fetch from backend - React [closed]
I have the information in the backend (Django) but I can't seem to get it with the methods that I found on google. When I implement the code for all products it works. But when I specify the id it doesn't return anything. I also get a warning in console of: "React Hook useEffect has a missing dependency: 'match.params.id'" Here is the code: function ProductScreen({ match }) { const [product, setProduct] = useState([]) useEffect(() =>{ async function fetchProduct() { const { data } = await axios.get(`/api/products/${match.params.id}`) setProduct(data) } fetchProduct() },[]) Thank you in advance! -
Duplicate tables created in django migrations when using SQL Server schemas
I want to place all Django specific tables and my custom Auth models into the default dbo schema, and have all my different app specific tables in a schema named after the app. Something to note is that all of my app tables will foreign key back to my auth model (I have _created_by and _last_updated_by fields on a base model that all apps inherit from). Basically I want the DB structure to be something like this: DBO - my_custom_auth_table - django_migrations - django_session - django_content_type - etc... APP1 -table1 -table2 APP2 -table1 -table2 In order to achieve this, I tried creating a Login/User pair on the DB server for each app and implemented a DB router. my allow_migrate method: def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == db: return True else: return False my database settings (I will use my doglicense app as an example): default_db_settings = { 'ENGINE': 'mssql', 'NAME': '***', 'USER': 'some_user', 'PASSWORD':'***', 'HOST':'***', 'PORT':'1433', 'OPTIONS':{'driver':'ODBC Driver 18 for SQL Server', 'extra_params': 'trustServerCertificate=yes'}, } doglicense = { 'ENGINE': 'mssql', 'NAME': '***', 'USER': 'DogLicense', 'PASSWORD':'***', 'HOST':'***', 'PORT':'1433', 'OPTIONS':{'driver':'ODBC Driver 18 for SQL Server', 'extra_params': 'trustServerCertificate=yes'}, } I have successfully migrated the custom auth app and all of …