Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ModuleNotFoundError: No module named 'models'
I'm building a web app in Django to purchase movie tickets. All the logic handling the database is in the 'ticket_handler' app. The actual website is in the 'movie_site' app and I'm building a restful api in the 'ticketing_api' app. Whenever I try to import something from one app to another, I get a "ModuleNotFound" error. Here is my directory structure: Movie_Ticketing_Service |- movie_server | |- movie_server | | |- __init__.py | | |- asgi.py | | |- settings.py | | |- urls.py | | |- wsgi.py | |- movie_site | | |- migrations | | |- templates | | |- __init__.py | | |- admin.py | | |- apps.py | | |- forms.py | | |- models.py | | |- tests.py | | |- urls.py | | |- views.py | |- ticket_handler | | |- migrations | | |- __init__.py | | |- admin.py | | |- apps.py | | |- billing_handler.py | | |- mail_handler.py | | |- models.py | | |- tests.py | | |- ticket_handler.py | | |- views.py | |- tecketing_api | | |- migrations | | |- __init__.py | | |- admin.py | | |- apps.py | | |- forms.py | | |- models.py … -
django.contrib.admin.sites.NotRegistered: The model User is not registered
I am trying to register my custom user model to the admin site (I have name my custom user model User), but I am getting this error. as I understood that I should unregister the original User model then register my custom model and this what I have tried to do!! ---------setings.py------- INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', # This is custom user model ] AUTH_USER_MODEL = 'users.User' ---------users/admin.py------- from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User as MyUser # my Custom User Model from django.contrib.auth.models import User admin.site.unregister(User) class MyUserAdmin(UserAdmin): list_display = ('username', 'email') admin.site.register(MyUser,MyUserAdmin) -
How to send image from Expo Image Picker to Django REST using axios
I have spent about a week on this and cannot understand what is going on. I need to upload images from React-Native (EXPO) to Django REST. It seems to be that axios is sending an object instead of an image (I think). React Native EXPO Image Picker/Axios: const pickImage = async () => { // No permissions request is necessary for launching the image library let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.All, allowsEditing: true, aspect: [4, 3], quality: 1, }); if (!result.cancelled) { const formData = new FormData(); formData.append("image", { uri: result.uri, name: "image.jpeg", type: "image/jpeg", }); try { const response = await axiosInstance({ method: "post", url: `/api/businesses/84/upload_image/`, data: formData, headers: { "Content-Type": "multipart/form-data" }, }) console.log(response.data); } catch (error) { console.log(error.response.data); } } }; Django API: class BusinessProfileViewSet(MixedPermissionModelViewSet): """ API endpoint that allows business profiles to be viewed, created, or edited. """ queryset = BusinessProfile.objects.all().order_by('-created_on') serializer_class = BusinessProfileSerializer permission_classes_by_action = { 'list': [IsOwnerOrStaff], 'create': [AllowAny], 'update': [IsOwnerOrStaff], 'retrieve': [IsOwnerOrStaff], 'partial_update': [IsOwnerOrStaff], 'destroy': [IsAdminUser] } paginator = None parser_classes = [MultiPartParser, FormParser] @action(methods=['post'], detail=True, permission_classes=[IsAuthenticated]) def upload_image(self, request, pk=None): try: print(request.data) image = request.data except KeyError: raise KeyError('Request has no image attached') business_profile = BusinessProfile.objects.get(user=request.user) business_profile.image = image business_profile.save() return … -
Django - send_mail -No error while trying to send e-mail, but no e-mail is Sent
Im trying to send an verification email to new registred accounts, but the e-mail is not being sent, the html page that is being loaded when I send the e-mail is being perfectly loaded, and I dont get an error in console aaaaaaaaaaaaaaaaaaaaaa if DEBUG: EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'jamelaumn@gmail.com' EMAIL_HOST_PASSWORD = xxxxx # important else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' def account_register(request): if request.user.is_authenticated: return redirect('account:dashboard') if request.method == 'POST': registerForm = RegistrationForm(request.POST) if registerForm.is_valid(): user = registerForm.save(commit=False) user.email = registerForm.cleaned_data['email'] user.set_password(registerForm.cleaned_data['password']) user.is_active = False email_to = user.email user.save() email_subject = 'Ative sua conta' current_site = get_current_site(request) message = render_to_string('account/registration/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) html_message = "<br> oi </br>" email_body = message send_mail([email_to], subject=email_subject, message=message, from_email=settings.EMAIL_HOST_USER, html_message=html_message) """ email = EmailMessage( email_subject, email_body, settings.EMAIL_HOST_USER, [email_to]) email.send() """ return HttpResponse('registered succesfully and activation sent') else: registerForm = RegistrationForm() return render(request, 'account/registration/register.html', {'form': registerForm}) def account_activate(request, uidb64, token): try: uid = urlsafe_base64_decode(uidb64) user = UserBase.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, user.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return redirect('account:dashboard') else: return render(request, 'account/registration/activation_invalid.html') -
Raw sql query issue in Django
I am trying to to make an SQL query to impliment the answer given here. The user suggested I try doing a raw sql query to solve. I am having issues implimenting what he suggests. For example, this is what I have so far. ingredients = ["eggs", "bacon", "salt"] recipes = Recipe.objects.raw('select whattocook_RecipeIngredients \ from whattocook_Recipe a \ inner join whattocook_RecipeIngredients b \ on a.id = b.recipe_id and b.ingredient in (ingedients) \ group by recipeingredients \ having count(*) >= 2') But this does not work. His answer says to do this recipe_list = Recipe.objects.raw('select a.* from app_Recipe a inner join app_RecipeIngredients b on a.id = b.recipe_id and b.ingredient in ("egg", "bacon", "rice") group by a.* having count(*) >= 2') maybe replace app_ with your project name, replace a.* with list of column names. So I think I am misunderstanding which columns I need to replace, given my code gives me this error. django.db.utils.ProgrammingError: column "ingedients" does not exist LINE 1: ... on a.id = b.recipe_id and b.ingredient in (ingedients... ^ HINT: Perhaps you meant to reference the column "b.ingredient". My app is named whattocook, and the models are as follows class RecipeIngredients(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, null=True) ingredient = models.TextField(null=True, … -
Stuck on Django poll tutorial (trying to connect the polls app to the server.)
i've been trying to connect to polls application but it still only shows the default page in django :( main app: First site url from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include('polls.urls')) ] urls.py in polls app from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', ] -
Passing Extra context to ListViews in Django
Can anyone please tell me how I can pass the "query" on my ListView as a context while at the same time keeping "search_results" as a context_object_name? I just can't get my head around it: class SearchResulView(ListView): model = Product template_name = 'shop/product/search_results.html' context_object_name = 'search_results' def get_queryset(self): query = self.request.GET.get("q") search_results = Product.objects.filter( Q(name__icontains=query) ) return search_results Am trying to render the values passed to "query" on my template but I just can't figure out how... -
can't edit Boolean field on django model when it is link with another field from the same model within this logic scoop?
I am working on django v4.* and I came cross a point where I need to make field publish_date to be auto populated when is_published is ticked import datetime class Article(models.Model): ....... is_published = models.BooleanField(default=False) publish_date = models.DateTimeField(blank=True, null=True) ....... def save(self, *args, **kwargs): if self.is_published: self.publish_date = datetime.datetime.now() super().save(*args, **kwargs) this did the trick but the problem that I can not edit the is_published field anymore, when I tick it (make it true) it stay true even if I try to change it to untick -
How to access object data from 'self' in get_context_data?
I'm creating some charts using ChartJS and Django, so I have the view below: class ChartView(TemplateView): template_name = 'app/chart.html' def get_context_data(self, **kwargs): context = super(ChartView, self).get_context_data(**kwargs) print('\n') print('****************** I NEED TO SEE ALL THE FIELDS AND VALUES THAT ARE BEING PASSED THROUGH SELF ******************') print(self) print('\n') return context I'm informing some values to my charts from context... but I need to do some calculations and I need to see what is exactly comming from "self"... how to access this data? For example, if would be necessary I do something like that: context['obj'] = Obj.objects.get(pk=pk_from_self) -
Can I serve a react app (with react router) from a specific endpoint?
I have a Django app. Most of the endpoints for this app will serve up a template. However, I would like one endpoint, lets say example.com/xyz, to serve a React app. This react app uses routes, so it would manipulate the url path. My question comes in two parts: If it is possible to do this, how can I ensure React router keeps the original /xyz endpoint in the path before adding whatever else to it? How can I configure Django to return the react app for ANY endpoint that begins with /xyz? -
Django: I want to track from which url a request was made?
in the TestQuestionList class, the get function must receive an id to return id, I thought that I could do this with the help of request.get_full_path()example on the bottom class TestQuestionList(APIView): def get(self, request): obj = Test.objects.get(id = request.get_full_path()) romms = TestQuestionBlok.objects.filter(id__in=obj.questions) serializer = TestQuestionSerializers(romms, many=True) return Response(serializer.data) but request.get_full_path() instead of /tests/api/ (where the request was made from) returned /api/question/ why? This is part of the code from where the request was made useEffect(() => { axios({ method: 'GET', url: 'http://127.0.0.1:8000/api/questions/', }).then(response => { setAllQuestions(response.data) }) }, []) Thanks in advance for your replies -
Django modifying login view has no effect
Long story short: No matter what I do with the login view, it won't change the behavior of the login form, I can delete my views altogether (and urls) and it still works, so it must be picking it up from somewhere else. From where and how do I change that? Long version: I was following a tutorial to implement login, logout and registration with django built in features, it is actually working fine but when I was trying to modify the login view I just realized that no matter what I tried to do in the view, it wouldn't change the behaviour (I was trying to redirect to a different page if the user was already logged, for instance). I started playing around to see what I could change and how it would reflect, even adding prints, but nothing happened, until I decided to try replacing all the code inside the login view function with pass, AND IT STILL WORKED! It happens the same with the logout view, but it doesn't with the register view. I don't understand what's going on. I tried to find something online, but I couldn't find anything related to this exact issue. This is … -
Accept URL as parameter in path (special characters)
I have a view and a path where I'd like to accept a str parameter and pass it to my make_request view. The problem I'm having is the strings I'd like to accept are URLs. When I pass a string like 'https://example.com/' I get an error saying Page not found (404) as there are special characters. urls.py from django.urls import path from . import views urlpatterns = [ path('<str:url>', views.make_request, name='make_request'), ] views.py def make_request(url): print(url) -
Django ORM filtering using expression against multiple fields
I am trying to use Django ORM filter to retrieve Announcement records with announcement_dates that are later than the current date - "expire_in_days" field - i.e., retrieve announcements that have not yet expired. Here is the SQL representation of what I am trying to do with ORM: select * from announcement where message_date > current_date - expire_in_days; I should be able to retrieve all records and filter them externally, but I am trying to learn how to do this with Django. Here is my model class Announcement(models.Model): message = models.TextField("announcement message") message_date = models.DateField("Announcement date") expire_in_days = models.PositiveIntegerField("Number of days before announcement expires") def __str__(self) -> str: return '(message: %s, message_date: %s, expire_in_days: %s)' % (self.message, self.message_date, self.expire_in_days) Here is what I tried but it did not work: In [1]: from events.models import Announcement In [2]: from datetime import date, timedelta In [3]: from django.db.models import F In [4]: date.today() Out[4]: datetime.date(2022, 5, 29) In [5]: date.today() - timedelta(days=2) Out[5]: datetime.date(2022, 5, 27) In [6]: Announcement.objects.all() Out[6]: <QuerySet [<Announcement: (message: There is a surprise coming up!, message_date: 2022-05-27, expire_in_days: 1)>]>" In [7]: Announcement.objects.filter(message_date__gt = (date.today() - timedelta(days = F('expire_in_days')))) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [7], in … -
Django: converting csv file to ofx doesn't work when i put the source = request.FILES
I need some help please from 2 days am trying to convert a csv file of an ofx file , i have suceeded to do that but the thing just work when i specify a file and not something general what i mean : this code work perfect : def UploadFile(request): if request.method == 'POST': form = BlogForm(request.POST,request.FILES) if form.is_valid(): form.save() ofx = OFX(mapping) records = read_csv("/home/mariana/django_project/media/test.csv", has_header=True) groups = ofx.gen_groups(records) trxns = ofx.gen_trxns(groups) cleaned_trxns = ofx.clean_trxns(trxns) data = utils.gen_data(cleaned_trxns) content = it.chain([ofx.header(), ofx.gen_body(data), ofx.footer()]) with open ("/home/mariana/django_project/media/testt.ofx", 'w') as f: res = write(f, IterStringIO(content)) print("sucess") else: form = BlogForm() context = { 'form':form, } return render(request, 'pages/Upload.html', context) this is my models.py : class Blog(models.Model): csv_file = models.FileField(null = True, upload_to='files_csv') filename = models.CharField(max_length=20, null = True) urlpatterns = [ ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) def save(self, *args, **kwargs): super(Blog, self).save(*args, **kwargs) the thing doesn't work if i go that in general what i mean is if i modify : records = read_csv("/home/mariana/django_project/media/test.csv", has_header=True) ------> records = read_csv(request.FILES, has_header=True) ---> it doesn't work and give me an error(expected str, bytes or os.PathLike object, not MultiValueDict) , why this !!! why when i put request.FILES doesn't work -
POST request is not working after django website deployment through Microsoft IIS
I have successfully deployed my django web application through Microsoft IIS FastCGI. So look wise my website seems to be fine. But after submitting the form on the website, i's showing nothing. It's like the submit button is not posting the form at all. But the same thing is running fine on the local server (not with the IIS deployed one). In short, after deployment I am assuming that the index.html seems to be working fine but veiws.py or my JavaScript is not. I am not able to find find any solution for this. Any kind of help would be much appreciated. For the reference, the main web.config is below. web.config <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python\python.exe|C:\Python\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <!-- Required settings --> <add key="WSGI_HANDLER" value="my_app.wsgi_app()" /> <add key="PYTHONPATH" value="C:\MyApp" /> <add key="DJANGO_SETTINGS_MODULE" value="my_app.settings" /> <!-- Optional settings --> <add key="WSGI_LOG" value="C:\Logs\my_app.log" /> <add key="WSGI_RESTART_FILE_REGEX" value=".*((\.py)|(\.config))$" /> <add key="APPINSIGHTS_INSTRUMENTATIONKEY" value="__instrumentation_key__" /> <add key="WSGI_PTVSD_SECRET" value="__secret_code__" /> <add key="WSGI_PTVSD_ADDRESS" value="ipaddress:port" /> </appSettings> </configuration> -
How i can to change date of Django project
I implement project using Django and i have a some module calculate with current date and time. I want to test this module with change local time method. I tried to change computer date and time but not change in Django. i want to know how to change current date and time in Django. -
How can I hide current uploaded image location path in django?
I have made a feature in Django where every user can change his platform's logo. The image selected by the user will be saved in static/{user.customer.public_id}/platformLogo/image.jpg. When i save the changes, i can see the uploaded image's path which also contain unique public ID which i don't want user to see for security purpose. Can anyone help me to hide this image path in Django for user? Attaching my code part here below. Here we can see the image path which has unique ID in path, which we need to hide Here is the uploaded image path directory Here is my models.py from sre_constants import CATEGORY from unicodedata import category from attr import fields from django.db import models from datetime import date from django.contrib.auth.models import User import uuid def upload_path(instance, filename): filename = str(date.today()) name = instance.user.customer.public_id.hex return f'{name}/platformLogo/{filename}.jpg' class Customer(models.Model): user = models.OneToOneField(User, null=True, blank =True, on_delete=models.CASCADE) public_id = models.UUIDField(primary_key=True, default = uuid.uuid4, editable=False) date_created = models.DateTimeField(auto_now_add=True, null=True) name = models.CharField(max_length=200, null=True) otp_code = models.CharField(max_length=6, null=True) first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, unique=True) phone = models.CharField(max_length=200, null=True) profile_pic= models.ImageField(upload_to=upload_path, default='logo.png', null=True, blank=False,) def __str__(self): return self.name Here is my views.py @login_required(login_url='login') def accountSetting(request): customer … -
django_filters filter_overrides not applying to CharFields with choices
I have declared a django_filters.FilterSet with a Meta class where I would like to use filter_overrides in order to customise some of the filters. I am using code very similar to the example in the official documentation: class AccommodationFilter(django_filters.FilterSet): class Meta: model = AccommodationOffer fields = ['numberOfPeople', 'petsAllowed', 'typeOfResidence', 'startDateAccommodation' ] filter_overrides = { models.BooleanField: { 'filter_class': django_filters.BooleanFilter, 'extra': lambda f: { 'widget': forms.CheckboxInput(attrs={'class':'form-control', 'value' : 'true'}), }, }, models.CharField: { 'filter_class': django_filters.ChoiceFilter, 'extra': lambda f: { 'widget': forms.Select(attrs={'class':'form-control'}), }, }, } The BooleanFields are showing up as expected, however no matter what I try, the CharFields (which have choices set) do not render with the class="form-control" attribute. -
it doesn't decrease when i delete a row in heroku postgresql,why? (Django)
I have a django application running on heroku. and it is using free postgresql in this application.but even if I delete 30 40 maybe more lines from the admin panel, the number of rows (lines) in the heroku dashboard does not decrease.Even if I delete 20 30 rows (lines) at once, it never decreases, it increases constantly.It never goes below 877. but it keeps increasing when i add something new. -
Django CBV inheritance not working as expected
I use these two classes to get the context data and check permissions respectively: class RestaurantView(View): def get_context_data(self): ctx = {'restaurant': get_object_or_404(Restaurant, slug=self.kwargs['slug'])} return ctx class ManageRestaurantMixin(LoginRequiredMixin, UserPassesTestMixin, RestaurantView): def test_func(self): ctx = super().get_context_data() return ctx['restaurant'].owner == self.request.user Now the first one is working, so when i don't need permission i get the expected behavior, for example with this DetailView: class Info(RestaurantView, DetailView): model = Restaurant context_object_name = 'restaurant' template_name = 'restaurant/info.html' But then if inherit from ManageRestaurantMixin the permissions are checked as expected, but the context object is not working and the template displays an empty form: class EditInfo(ManageRestaurantMixin, UpdateView): model = Restaurant context_object_name = 'restaurant' template_name = 'restaurant/edit_info.html' fields = ['name', 'address', 'logo'] success_url = '/account/myrestaurants' I get that the context gets overwritten, but i don't get how. How can i solve this? Is there a better way to handle this kind of situations? -
ID Card Generation in Django
I am using Django my own Admin panel but I want to create employee card can you help me with view.py and template code? this is My Urls.py path('showcustomer',views.ShowCustomer) this is the view.py def ShowCustomer(request): qrcode_img=qrcode.make('Wellcom') canvas=Image.new("RGB", (290,290),'White') Draw=ImageDraw.Draw(canvas) canvas.paste(qrcode_img) fname=f'qr_code-(self.name)'+'.png' buffer=BytesIO() canvas.save(buffer,'PNG') img=qrcode_img.save(fname, File(buffer), save=False) canvas.close() return render(request, 'ShowCustomer.html',{'img':img}) and this is template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Show Customer page</h1> {{ img }} <img src={{img}} style="width: 20%; height: 20%;"> </body> `enter code here`</html> -
Use two managers in one model
I have a Place model with subclasses Restaurant and Bar. I attached InheritanceManager from django-model-utils to Place to use the select_subclasses() method to get instances of the subclass. from model_utils.managers import InheritanceManager class Place(models.Model): # ... objects = InheritanceManager() class Restaurant(Place): # ... class Bar(Place): # ... Everything worked fine. But now I want to set the order of the model Place with django-ordered-model. This package also uses a manager: ... objects = OrderedModelManager() ... How to combine them? -
Django Framework Rest match calendar users with current user
I am doing an exercise where the goal it's to match my current calendar with other users. To do this, I created a UserProfile App and Schedule App. Each user has a profile that can have multiple intervals. Considering my current calendar: { "count": 1, "next": null, "previous": null, "results": [ { "id": 3, "user": { "id": 3, "username": "john.doe", "first_name": "John", "last_name": "Doe" }, "calendar": [ { "id": 1, "mon": true, "tue": true, "wed": true, "thu": true, "fri": true, "sat": true, "sun": true, "start_date": "09:30", "end_date": "12:20" }, { "id": 2, "mon": true, "tue": true, "wed": true, "thu": true, "fri": true, "sat": true, "sun": true, "start_date": "14:00", "end_date": "23:00" } ] } ]} When I am doing a call to the endpoint /api/search/users it returns all User Profiles with info from each user. example: { "count": 99, "next": "http://localhost:8000/api/search/users?page=2", "previous": null, "results": [ { "id": 1, "user": { "id": 1, "username": "john.bender.99", "first_name": "John", "last_name": "Bender" }, "calendar": [ { "id": 2, "mon": true, "tue": true, "wed": true, "thu": false, "fri": true, "sat": false, "sun": false, "start_date": "09:30", "end_date": "12:20" }, { "id": 55, "mon": false, "tue": true, "wed": true, "thu": false, "fri": true, "sat": false, "sun": false, "start_date": … -
why django can not create a table after deleting the table and the migration files of the app?
I am working with Django v4.* which I connected it to Postgres DB on the localhost, I have created my model (Article) then makemigration then migrate then I have changed the model by adding extra field, as a result it didn't take effect so I have deleted the table and all the migrations files in articles/migrations folder apart of the __init__.py file, then I did makemigrations then migrate it create a new file 0001_initial.py but its not creating a new table into the DB? I am wandering why Django unable to create the table back again?