Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django button not submit when i have onclick
I have a button and i want to when this button is clicked this submit my form and they open a popup with onclick but when i have the onclick the form is doesn't submitted. I have tried to delete onclick and the form perfectly work but when i readd is same ): <div class="container-login-form-btn"> <input onclick="openPopup(event)" class="login-form-btn" type="submit" value="Submit"/> </div> <div class="popup" id="popup"> <h1 type="submit">OTP Verification</h1> <p>Code has been send</p> <div class="otp-card-inputs"> {{ otp }} </div> <p>Didn't get the otp <a href="#">Resend</a> </p> <input class= "verify-otp-btn" type="submit" value="Submit"/> </div> function openPopup(event){ popup.classList.add("open-popup"); event.preventDefault(); } .popup { width: 900px; background: #ffffff; border-radius: 20px; position: absolute; top: 0; left: 50%; transform: translate(-50%, -50%) scale(0.1); text-align: center; padding: 0 30px 30px; color: #333; visibility: hidden; transition: transform 0.4s, top 0.4s; z-index: 2; font-family: 'Poppins', sans-serif; box-shadow: 0 10px 40px -20px black; } .open-popup { visibility: visible; top: 50%; transform: translate(-50%, -50%) scale(1); } Thanks you in advance I'm trying to show the popup and to submit the form. -
How to ensure that a custom field may be used when creating an instance but is not included when updating?
I have a serializer for a User model with custom fields password_1 and password_2 configured with write_only = True so they are not displayed with GET but required with POST when creating a new model, which is perfectly fine. My problem is the PUT method, because when I want to update a model the fields are still required. How can I configure the serializer or the view to make these two fields optional with PUT ? I test my code with the browsable API and the PATCH method, although supported, isn't proposed when updating a model. This is what I've tried: first I updated the put method of the view by adding partial_update, but I couldn't get the expected result, probably because they are custom fields. views.py @permission_classes([IsAuthenticated]) class ManagerDetailsView(RetrieveUpdateAPIView): serializer_class = ManagerSerializer lookup_url_kwarg = "pk" def get_object(self): pk = self.kwargs.get(self.lookup_url_kwarg) obj = get_manager(pk) return obj def get_permissions(self): if self.request.method == 'PUT': self.permission_classes = [HasChangeManagerObjectPermission | HasTeamLeadPermission] return super(self.__class__, self).get_permissions() def put(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) Then I undo the previous try and modified the validate method of the serializer by setting kwargs["partial"] to True but it has no effect. serializers.py class ManagerSerializer(serializers.ModelSerializer): password1 = serializers.CharField(write_only=True) password2 … -
Can't get NGINX to read socket created by GUNICORN via SUPERVISORD (permission error)
I'm trying to run Django on AWS/Ubuntu using NGINX/Gunicorn (via supervisord) My Nginx logs keeps throwing a permission error when trying to access app.sock. "app.sock" is created by gunicorn, and gunicorn is run by supervisord, and supervisord is a nightmare. ps aux | grep nginx root 63435 0.0 0.1 55200 1692 ? Ss 10:56 0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on; www-data 63436 0.0 0.5 55848 5424 ? S 10:56 0:00 nginx: worker process As we can see www-data is the user associated with nginx. ls -lh ~/www/app.sock srwxrwxrwx 1 root root 0 Dec 27 11:20 /home/ubuntu/www/app.sock And app.sock is owned by "root", hence the permission error I'm getting. And here is my supervisord config file [program:gunicorn] directory=/home/ubuntu/www command=/usr/local/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/www/app.sock matched.wsgi:application user=www-data autostart=true autorestart=true stderr_logfile=/logs/gunicorn.err.log stdout_logfile=/logs/gunicorn.out.log In my config file, I've attempted to tell supervisor to run my gunicorn command AS www-data, but its still creating app.sock as root. It seems like the "user" parameter does not do anything at all. The only solution I see to this ridiculous problem is to run Nginx as root, which I know is a bad idea. I've searched almost every discussion on the web and I cannot … -
Keeping information from model Django
I have a project and when users logged in they have to choose a company and unit after that when user is working how can keep the company_id and unit_id? Because user have to be only adding data that company_id and unit_id I tried keeping ids from url with int:company_id/sint:unit_id but it can't work -
csv file stored in Django members directory loaded as directory instead of csv file
I am working in a Django app in a directory myworld. In this directory, I have a members directory with a templates directory with an html file myfirst.html. In the html file, I have this code: <script src="https://d3js.org/d3.v7.min.js"></script> <script> const loadData = () => { return d3.csv("/members/employees").then((data) => { for (var i = 0; i < data.length; i++) { console.log(data[i].Name); console.log(data[i].Age); } } ) }; loadData(); </script> And the contents of employees.csv is: Name, Age John, 30 Jane, 32 (I'm following an example here). However instead of getting the output that they get on that link, namely: John 30 Jane 32 I only get many lines of Undefined. On the django side, the terminal says: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). December 27, 2022 - 11:14:57 Django version 4.1.2, using settings 'myworld.settings' Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. HTTP GET /members/ 200 [0.16, 127.0.0.1:51510] HTTP GET /static/myfirst.css 200 [0.01, 127.0.0.1:51510] HTTP GET /static/myfirst.jss 200 [0.00, 127.0.0.1:51510] HTTP GET /members/employees 301 [0.00, 127.0.0.1:51510] HTTP GET /members/employees/ 200 [0.00, 127.0.0.1:51510] I tried seeing if the data was even loaded from the file correctly, but something … -
Why my validation is not working in django-rest serializer?
Appointment is being registered although I am providing before time in start time for appointment. models.py class Appointment(models.Model): status = models.CharField( choices=APPOINMENT_STATUSES, max_length=20, default=SCHEDULED, help_text="", ) full_name = models.CharField(max_length=100) gender = models.CharField(choices=GENDER_TYPE, max_length=10, default=MALE) email = models.EmailField() phone_no = models.CharField(max_length=10, validators=[validate_phone_no]) start = models.DateTimeField(max_length=50, help_text="Appointment start Date & Time") end = models.DateTimeField(max_length=50, help_text="Appointment End Date & Time") doctor = models.ForeignKey(Doctor, on_delete=models.PROTECT, blank=True, null=True) message = models.TextField() def __str__(self): return self.full_name serializers.py class AppointmentCreateSerializer(serializers.ModelSerializer): class Meta: model = Appointment fields = '__all__' def create(self, validated_data): return super().create(validated_data) def validate(self, attrs): # check appointment start and end time if attrs["start"] < timezone.now(): raise serializers.ValidationError("Appointment date cannot be in the past") if attrs["start"] >= attrs["end"]: raise serializers.ValidationError( f"Appointment end date/time should be after than start/date time." ) return super().validate(attrs) Description: This is my appointment model and serializer for that. Why my validation is not working. I want, the user wont be able to create appointment if the start date and time is before current date and time. ----------------> But Appointment is getting registered, if User is entering today date but before time . What's Wrong with this? and What can be better solution for this problem? -
i want to change 'add cart' button to 'plus' ,'value', and 'minus' when click on "add cart" in shopping cart
$(".cart").click(function () { var idstr = this.id.toString(); console.log(idstr); if (cart[idstr] != undefined) { console.log("exist"); qty = cart[idstr][0] + 1; console.log(qty); console.log(cart[idstr][0]); } else { qty = 1; price = document.getElementById("price" + idstr).innerHTML; image = document.getElementById("img" + idstr).src; aname = document.getElementById("name" + idstr).innerHTML; console.log("not"); cart[idstr] = [qty, aname, image, price]; } console.log(cart); updateCart(cart); localStorage.setItem("cart", JSON.stringify(cart)); }); function updateCart(cart) { for (var item in cart) { document.getElementById("div" + item).innerHTML = "<button id='minus" + item + "' class='btn btn-primary minus'>-</button> <span id='val" + item + "''>" + cart[item][0] + "</span> <button id='plus" + item + "' class ='btn btn-primary plus'>+</button>"; } } this happened when i try i am expecting this when i clicked on add cart button it didnt change to my expected buttons its means my function updateCart not working -
Django - How to store country name?
I am using a proxy model in django: from django.db import models from datetime import datetime # Create your models here. def get_current_datetime_str(): now = datetime.now() return now.strftime("%Y-%m-%d %H:%M:%S") class customer_location(models.Model): parent_id=models.IntegerField() name=models.CharField(max_length=100) status=models.CharField(max_length=100, default='nil') added_by=models.CharField(max_length=100, default=1) updated_by=models.CharField(max_length=100, default=1) created_on=models.CharField(max_length=100) updated_on=models.CharField(max_length=100) class Meta: db_table="customer_location" def __str__(self): return self.name def save(self, *args, **kwargs): self.created_on = get_current_datetime_str() self.updated_on = get_current_datetime_str() super().save(*args, **kwargs) class Country(customer_location): class Meta: proxy = True def save(self, *args, **kwargs): self.created_on = get_current_datetime_str() self.updated_on = get_current_datetime_str() self.parent_id = 0 if Country.objects.filter(name=self.name).exists(): pass else: super().save(*args, **kwargs) class State(customer_location): country_name = models.CharField(max_length=100) class Meta: proxy = True def save(self, *args, **kwargs): self.created_on = get_current_datetime_str() self.updated_on = get_current_datetime_str() try: country_obj = Country.objects.get(name=self.country_name) #error here self.parent_id = country_obj.id except Country.DoesNotExist: self.parent_id = 777 #FIX THIS PARENT ID super().save(*args, **kwargs) Now as you can see i have declared country_name inside state proxy model so that i can get the id of country stored in the database. Basically i want to set state parent_id = country id and i am not able to do it. I am very close i guess but stuck at last step i guess so? Can someone please help? The error i get is: django.core.management.base.SystemCheckError: ?[31;1mSystemCheckError: System check identified some issues: … -
Ajax Request to ApiView endpoint raises forbidden http error
I have been trying to to an AJAX Request to an ApiView endpoint. $.ajax({ url: '{% url 'edit_custom_user_additional_info' %}', method: "patch", data: $form.serialize(), header: { "X-CSRFToken": "{{ csrf_token }}" }, success: function (data) { alert("Dati aggiuntivi salvati con successo"); }, error: function (data) { console.log("Errore durante il salvataggio dei dati aggiuntivi"); }, }); I have also added the {% csrf_token %} to the form but I still get Forbidden error. I have also tried to add the CSRF Exempt but still the error. How can I fix that? -
Deploying Django app to Elastic Beanstalk Docker platform
Im'm trying to deploy a django app to single docker container platform on EB version Docker running on 64bit Amazon Linux 2/3.5.2. This is what I've done so far: Created Dockerfile and compose, pushed the image to ECR, Created Dockerrun.aws.json and it looks like this: { "AWSEBDockerrunVersion": "1", "Image": { "Name": "URI to the ECR repository", "Update": "true" }, "Ports": [ { "ContainerPort": 8000, "HostPort": 8000 } ] } Created sample app in Elastic Beanstalk. Uploaded the Dockerrun.aws.json file as the source code Now the EB url is taking to a "This site can't be reached" page but in the logs I can't find the specific error instead I see a message stating that deployment has succeeded Also when I run eb locally like this eb local run --port 8080, eb local open, it's working just fine. Let me know if there's anything else I need to share. -
optmizing queries in django
Here I have four models Category, Products, ProductOffer and CategoryOffer. The CategoryOffer is Foreignkey to Category and ProductOffer is Foreignkey to Products. And while a product have an offer and the category having the product also have an offer. I'll compare both offers and shows whichever is higher. So far everything is working but when I looked on to how much queries is getting executed. It's a lot. It's shown below: (0.000) SELECT "accounts_account"."id", "accounts_account"."password", "accounts_account"."first_name", "accounts_account"."last_name", "accounts_account"."email", "accounts_account"."date_joined", "accounts_account"."last_login", "accounts_account"."is_admin", "accounts_account"."is_staff", "accounts_account"."is_active" FROM "accounts_account" WHERE "accounts_account"."id" = 52 LIMIT 21; args=(52,); alias=default (0.016) SELECT "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date", "inventory_category"."id", "inventory_category"."category_name", "inventory_category"."slug", "inventory_category"."title", "inventory_category"."description", "inventory_category"."category_image" FROM "inventory_products" INNER JOIN "inventory_category" ON ("inventory_products"."category_id" = "inventory_category"."id") WHERE "inventory_products"."is_available"; args=(); alias=default (0.000) SELECT "inventory_productoffer"."id", "inventory_productoffer"."product_id", "inventory_productoffer"."valid_from", "inventory_productoffer"."valid_to", "inventory_productoffer"."discount", "inventory_productoffer"."is_active", "inventory_products"."id", "inventory_products"."category_id", "inventory_products"."product_name", "inventory_products"."sub_product_name", "inventory_products"."sku", "inventory_products"."slug", "inventory_products"."base_price", "inventory_products"."product_image", "inventory_products"."stock", "inventory_products"."is_available", "inventory_products"."created_date", "inventory_products"."modified_date" FROM "inventory_productoffer" INNER JOIN "inventory_products" ON ("inventory_productoffer"."product_id" = "inventory_products"."id") WHERE ("inventory_productoffer"."is_active" AND "inventory_productoffer"."product_id" = 5) LIMIT 21; args=(5,); alias=default (0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active" FROM "inventory_categoryoffer" WHERE ("inventory_categoryoffer"."category_id" = 4 AND "inventory_categoryoffer"."is_active") LIMIT 21; args=(4,); alias=default (0.000) SELECT "inventory_categoryoffer"."id", "inventory_categoryoffer"."category_id", "inventory_categoryoffer"."valid_from", "inventory_categoryoffer"."valid_to", "inventory_categoryoffer"."discount", "inventory_categoryoffer"."is_active", "inventory_category"."id", "inventory_category"."category_name", "inventory_category"."slug", "inventory_category"."title", "inventory_category"."description", "inventory_category"."category_image" FROM … -
django: Page not found (404)
project/urls.py from django.contrib import admin from django.urls import path, include from django.http import HttpResponse urlpatterns = [ path("admin/", admin.site.urls), path("", include('todo.urls')), ] setting.py TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(BASE_DIR, "templates")], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] todo/ulrs.py from django.urls import path from . import views urlpatterns = [ path("login", views.home), ] todo/views.py from django.http import HttpResponse from django.shortcuts import render def home(request): return render(request, 'index.html') I don't know why it is not showing my page... I have created django project called taskly. And in that project I have only 1 app called todo. I have referred templates folder as well as you can see above. In that template folder there is only 1 page index.html -
Django 'User' object has no attribute 'profile'
Good day to all of you we are facing a problem when I create a user profile with signals when I enter the register section 'str' object has no attribute 'get' my View: from django.shortcuts import render,redirect from .forms import LoginForm,RegisterForm from django.contrib.auth import authenticate,login,logout from django .contrib.auth.models import User # Create your views here. def Login_view(request): form=LoginForm(request.POST or None) if form.is_valid(): username=form.cleaned_data.get('username') password=form.cleaned_data.get('password') user=authenticate(username=username,password=password) login(request,user) return redirect('index') return render(request,'accounts/login.html',{'form':form}) def Register_view(request): form=RegisterForm(request.POST or None) if form.is_valid(): user=form.save(commit=False) password=form.cleaned_data.get('password1') user.set_password(password) user.save() new_user=authenticate(username=user.username,password=password) login(request,new_user) return redirect('index') return render(request,'accounts/register.html',{'form':form}) def logout_view(request): logout(request) return redirect('index') My Signals from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import UserProfile @receiver(post_save,sender=User) def create_profile(sender,instance,created,**kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save,sender=User) def save_profile(sender,instance,**kwargs): instance.profile.save() My Model: class UserProfile(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) username=models.CharField(verbose_name='Kullanıcı Adı',max_length=40) name=models.CharField(verbose_name='ad',max_length=40) surname=models.CharField(verbose_name='Soyad',max_length=40) bio=models.TextField() avatar=models.ImageField(null=True,blank=True) I used the signals part for the user profile, but I'm making a mistake somewhere, I need to solve it -
having issues with my django project on vscode
i tried running my project and its showing this error message ModuleNotFoundError: No module named 'models' i kept models in my settings.py in my installed apps but still did not work -
cannot import name 'InvalidAlgorithmError' from 'jwt'
I am trying to implement djangorestframework-simplejwt in djanog project. when I try to post username and password show error. include this following line. from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns = [ path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] asgiref==3.5.2 Django==4.0 djangorestframework==3.14.0 djangorestframework-simplejwt==5.2.2 mysqlclient==2.1.1 PyJWT==2.6.0 pytz==2022.6 sqlparse==0.4.3 tzdata==2022.6 -
i use append in for loop of local storage ,i want to display item in a new line every time loop finished
for(item in cart){ let name =cart[item][1]; let qty =cart[item][0]; let image =cart[item][2]; let price=cart[item][3]; mystr=` <td class="product-thumbnail"><a href="shop-details.html"><image src="${image}" alt="product"> </a></td> <td class="product-name">${name}</td> <td class="product-price"><span class="amount">${price}</span></td> <td class="product-quantity"> <button id='plus" + item + "' class ='btn btn-primary plus'>+</button> <span id="quantity" >${qty}</span> <button id='minus" + item +"' class='btn btn-primary minus'>-</button> </td> <td class="product-subtotal"><span class="amount"></span></td> <td class="product-remove"><a href="#"><i class="fa fa-times"></i></a></td> ` console.log(mystr); $('#items').append(mystr) } i want to display every item in new line not all items in same line i expect this -
Django Soak Testing Bulk Request at once
I want to test whether Django can handle heavy load requests at once continuously. How to conduct this scenario? using tests?. Eg: 300 Read requests 300 Write requests within 1 sec. You can take any basic ORM query like User.objects.get(id=`some id) for 1 request and take this as 300 different read requests. Same for write requests as well but change any field of your choice. Later check if that works for at-least 10 sec. You can think of this scenario as multiple concurrent users using the Django app. -
Annotate value to a many to many field in django
I have a model: class A(models.Model): ... users = models.ManyToManyField(User) ... I want to annotate some data to users of an instance of model A. I was doing something like this: a=A.objects.filter(id=2).first() a.users.all().annotate(games_played='some condition here') but this statement is returning a queryset of User model. Is it possible to annotate data to a many to many field of an instance and still have an object of model A so that I can do this; a.users.all()[0].games_played -
server Python Django
How to accept data from the client using a Post request (Login, password, email) with subsequent entry into the database for use when logging in I used it, but I don't fully understand it correctly or not, most likely not because nothing is written to the database Views.py class Reqs: def __init__(self, user, password, email): self.user = user self.password = password self.email = email class ReqsEncoder(DjangoJSONEncoder): def default(self, obj): if isinstance(obj, Reqs): return { "user": obj.user, "password": obj.password, "email": obj.email, } return super().default(obj) def api_response(request): user = request.POST.get("user") password = request.POST.get("password") email_ = request.POST.get("email") data = Data(user, password, email_) data.save() try: return HttpResponse(data, safe=False, encoder=ReqsEncoder) except: return HttpResponse("G") -
getting error while save image to db using s3 bucket
RuntimeError: Input Screenshot from 2022-12-23 18-34-04.png of type: <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> is not supported. getting this error while use s3 bucket in django InMemoryUploadedFile error -
how to create dependent dropdown list in CRUD Django
I am beginner and trying to create CRUD Django Application where I want to keep below fields. Company Name DOB Date and time State (should be dependency between State and City) City (should be dependency between State and City) Please help me for complete code For example i give input as company name : ABC DOB Date and time : 2022-01-01 08:12:00 State : Karnataka(if I select State "Karnataka" then related city of Karnataka has to be showed in dropdown) City : Bangalore, Mysore ''''''''''''''''' if I click on edit button entire field's value has to be show form design has to horizonal for Example company name DOB , Date and time State , City Not like this company name DOB Date and time State City -
Three-level inline formsets in the frontend
I'm trying to accomplish a three-level stacked inline form in Django. Suppose these models: class Anuncio(models.Model): title = models.CharField(max_length=200) delivery = models.CharField(max_length=100) class Product(models.Model): anuncio = models.ForeignKey(Anuncio, on_delete=models.CASCADE) name = models.CharField(max_length=200) quantity = models.PositiveIntegerField(default=1) price = models.PositiveIntegerField() class Image(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField() There is a relation Anuncio-Product and another relation Product-Image. With this Django package, I accomplished exactly what I want in the Django admin: when creating an Anuncio object, I can add as many Products as I want, and those products can have as many Images as I want. I'm trying to accomplish this in the front end. I think the way to go is with Django formsets, but I'm facing some problems. All the resources I've been able to find online are only 'two-level' formsets or in 'three-level' cases all the foreign keys point to the same parent model. With this forms.py file: class ProductForm(ModelForm): class Meta: model = Product fields = ['name', 'quantity', 'price'] class ImageForm(ModelForm): class Meta: model = Imagen fields = ['image'] class AnuncioForm(ModelForm): class Meta: model = Anuncio fields = ['title', 'delivery'] And this views.py function: def anunciocreateview(request): form = AnuncioForm(request.POST or None) ProductFormSet = inlineformset_factory(Anuncio, Product, form=ProductForm) ImageFormSet = … -
Django - How to remove data redundancy from the state model
My following code is storing multiple data: models.py from django.db import models from datetime import datetime # Create your models here. def get_current_datetime_str(): now = datetime.now() return now.strftime("%Y-%m-%d %H:%M:%S") class customer_location(models.Model): parent_id=models.IntegerField(max_length=100) name=models.CharField(max_length=100) status=models.CharField(max_length=100, default='nil') added_by=models.CharField(max_length=100, default=1) updated_by=models.CharField(max_length=100, default=1) created_on=models.CharField(max_length=100) updated_on=models.CharField(max_length=100) class Meta: db_table="customer_location" def __str__(self): return self.name def save(self, *args, **kwargs): self.created_on = get_current_datetime_str() self.updated_on = get_current_datetime_str() super().save(*args, **kwargs) class Country(customer_location): class Meta: proxy = True def save(self, *args, **kwargs): self.created_on = get_current_datetime_str() self.updated_on = get_current_datetime_str() self.parent_id = 0 if Country.objects.filter(name=self.name).exists(): pass else: super().save(*args, **kwargs) class State(customer_location): class Meta: proxy = True def save(self, *args, **kwargs): self.created_on = get_current_datetime_str() self.updated_on = get_current_datetime_str() try: country_obj = Country.objects.get(name=self.name) self.parent_id = country_obj.id except Country.DoesNotExist: pass super().save(*args, **kwargs) My country model is working fine it does not have any issue related to data redundancy/repetition and is storing the data as it is intended. But my state model, either gets parent_id as null or stores the country name again in the database. I have no clue where i am going wrong. Will attach forms.py and views.py for your perusal: forms.py: class CustomerLocationForm(forms.Form): country = forms.ChoiceField(choices=COUNTRY_CHOICES) state = forms.CharField(max_length=100) status = forms.ChoiceField(choices=STATUS_CHOICES) class CustomerCountryForm(forms.Form): country = forms.CharField(max_length=100) status = forms.ChoiceField(choices=STATUS_CHOICES) class Meta: model=customer_location exclude = … -
Django - MySQL intergration Mac M1 Max
I'm relatively new to Django and working on a project. I was about to makemigrations and got the following trace: demoproject lamidotijjo$ python3 manage.py makemigrations Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so, 0x0002): Library not loaded: /opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib Referenced from: <D6AC4B91-4AA0-31A5-AA10-DE3277524713> /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so Reason: tried: '/opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib' (no such file), '/opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib' (no such file), '/usr/lib/libmysqlclient.21.dylib' (no such file, not in dyld cache) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/lamidotijjo/Python/Django/demoproject/manage.py", line 22, in <module> main() File "/Users/lamidotijjo/Python/Django/demoproject/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, … -
Tried building a query that would give you the page views per url for a given date range and needs to apply filters
I got the output for the page views per url for a given date range but as it fetches every url i need to apply filters into it for the dimension ga:landingPagePath The output for the query when executed is:- http://code.google.com/apis/analytics/docs/gdata/gdataExplorer.html And i only need the pageviews for the landing page starting with /job-details/ I tried giving the filters like:- filters=ga:landingPagePath%3D%3D/job-details/ but i was getting an error like:- Error message: Invalid value 'filters=ga:landingPagePath%3D%3D/job-details/'. Values must match the following regular expression: 'ga:.+'