Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is there way to make page open for logged in user only
I'm trying to make this page for logged in user only and when i write @login_required it don't do anything and page open for all user how to fix this views.py @login_required(login_url='accounts/login/') @register.inclusion_tag('survey/survey_details.html', takes_context=True) def survey_details(context, survey_id): survey = Survey.objects.get(id=survey_id) return {'survey': survey} -
Error running WSGI application ModuleNotFoundError: No module named 'f_worldSHop' File "/var/www/fworld_pythonanywhere_com_wsgi.py"
**I have facing issues when i deploy a django project on pythonanywhere error below** Error running WSGI application ModuleNotFoundError: No module named No module named 'f_worldSHop' File "/var/www/fworld_pythonanywhere_com_wsgi.py" wsgi.py """ path = '/home/Fworld/f-worldshop/f_worldSHop' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'f_worldSHop.settings' ## then: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() """ Inner project Path """ README.txt f-worldshop (myenv) 21:33 ~ $ cd f-worldshop/ (myenv) 21:33 ~/f-worldshop (master)$ ls db.sqlite3 f_Usershop f_shop f_worldSHop manage.py media requirements.txt (myenv) 21:33 ~/f-worldshop (master)$ pwd /home/Fworld/f-worldshop (myenv) 21:34 ~/f-worldshop (master)$ cd f_worldSHop/ (myenv) 21:34 ~/f-worldshop/f_worldSHop (master)$ pwd /home/Fworld/f-worldshop/f_worldSHop """ Kindly help me Thanks Regards: Umer Malik Error running WSGI application ModuleNotFoundError: No module named No module named 'f_worldSHop' File "/var/www/fworld_pythonanywhere_com_wsgi.py" Error running WSGI application ModuleNotFoundError: No module named No module named 'f_worldSHop' File "/var/www/fworld_pythonanywhere_com_wsgi.py" -
Collect payments and pay out
I'm developing an iOS application (with a Django backend) with an internal currency system. Users will be able to purchase coins and redeem them for real money. I will not use the in-app purchase but a custom payment system (I'm allowed to do this and the question is not about Apple's guidelines). I'm searching for an API that allows me to collect payment and pay out users as fast as possible globally and without daily/weekly/monthly limitations. My problem is that I don't want to accumulate the earnings on a bank account/credit card since they have limitations in the number of transactions, so performing mass pay outs is not possible. Is there a way to receive payments with Stripe/PayPal/Braintree without transferring funds to a bank account and then pay users quickly with previously accumulated money? If it is possible would you direct me to related resources/documentation? -
Referenced Url works with static number but not with variable
So i'm trying to get product_id to work and every time it comes up with this error:NoReverseMatch at /playground/hello/ Reverse for 'information' with arguments '('',)' not found. 1 pattern(s) tried: ['playground/hello/(?P<product_id>[0-9]+)\Z'] It works perfectly fine if i pass a constant like the number 1 or 2(can go infinitely long based on how many objects are stored in the admin panel) instead of product_id inside the index.html file but the issue with that is that if i click on any link on the first page it redirects to the same thing no matter what i click. index.html {% extends 'base.html' %} {% block content %} <table class="table table-bordered table-hover"> <thead> <tr> <th>Work</th> <th>Type of Work</th> <th>Hours needed</th> </tr> </thead> <tbody> {% for context2 in context%} <tr> <td> <a href={% url 'product:information' product_id %}>{{context2.work}}</a> </td> <td>{{context2.genre}}</td> <td>{{context2.hoursWorked}}</td> </tr> {% endfor %} </tbody> </table> {% endblock %} Urls.py from django.urls import path from . import views app_name = 'product' urlpatterns = [ path('hello/', views.hello, name='hello'), path('hello/<int:product_id>', views.detail, name='information') ] Views.py from django.shortcuts import render, get_object_or_404 from django.http import Http404, HttpResponse from .models import products, typeWork def hello(request): context = typeWork.objects.all() context2 = {'context':context} return render(request, 'products/index.html', context2) def detail(request, product_id): context = get_object_or_404(typeWork, … -
django allauth redirect to another page after email verification
I have this issue: I need to redirect to another page when email verification is confirmed and login for the first time after the email verification. I tried to configure this in setting.py, but didn't work. My settings.py: ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = os.getenv('schools/form-school') the url in urls.py is: path('form-school', views.school_list_view, name = 'schools' ), if you have any clue on how to resolve this please comment your ideas, thanks so much!! -
Djangochannelsrestframework hot to send image file?
How can I send image file by websocket using djangochannelsrestframework? Thanks! -
Django getting session 500 error on specific line
I'm trying to run the code here: https://github.com/TwilioDevEd/automated-survey-django. The problem I'm stuck on is in the below function, the first time a text is send, there is no session and request.session.get('answering_question_id') is false/null. The second text sent from the same number (where I can see there is a new row in the django_session table), returns a 500 error on this line request.session.get('answering_question_id'). I see a 500 error is a server error, but I'm stuck on what that could mean for this. I thought the result should just be false/null if 'answering_question_id' isn't available. Any thoughts? @require_http_methods(["GET", "POST"]) def redirects_twilio_request_to_proper_endpoint(request): print("HELLOOOO!") answering_question = request.session.get('answering_question_id') print("YEPPERS") if not answering_question: print('1') first_survey = Survey.objects.first() redirect_url = reverse('survey', kwargs={'survey_id': first_survey.id}) else: print('2') question = Question.objects.get(id=answering_question) redirect_url = reverse('save_response', kwargs={'survey_id': question.survey.id, 'question_id': question.id}) return HttpResponseRedirect(redirect_url) -
Django MultiTenant saas registeration
I have been coding my project using a single DB and tenant_ids for each entry I wanted to switch to django-tenant and have schema based app. My question is about the initial registration. Registration should be a shared app but do i need to create a tenant for "public" regardless so that everyone becomes that tenant when they are registering? And do you add this public tenant with a script onetime when you set up the project so that you have a "public" tenant. Creating a tenant for public feels a bit odd. Or what would be the registration sequence be like( Ideally registration should create the tenants) Ideally my flow should be : you register a tenant with an email so that when tenant registers it sends an email and when you activate that mail you create your first user (admin user) for that tenant. -
Unique PermissionError: [WinError 5] Access is denied IIS Issue
I am currently setting up a django site to run on IIS, however I am running into an issue with the USZipCodes python module, When it goes to call the USZipCodes module if gets an access denied error. I have confirmed all folders regarding this EXCEPT the systemprofile folder has proper permissions for the IIS_IUSRS profile. I would do the systemprofile as well but it just give me more errors and I would prefer not to This module works fine when not IIS, through CMD it works fine, it is only when using IIS to run the app does this occur. I suspect I may just have the cut the module out but I would prefer not too Error Log: Traceback (most recent call last): File "C:\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\inetpub\wwwroot\Apps\scituateApp\.\tickets\views.py", line 286, in push json_client['street_name'], zco(json_client['zip']), json_client['state'], json_client['zip'], File "C:\inetpub\wwwroot\Apps\scituateApp\.\tickets\views.py", line 15, in zco search = SearchEngine() File "C:\Python310\lib\site-packages\uszipcode\search.py", line 153, in __init__ self._download_db_file_if_not_exists() File "C:\Python310\lib\site-packages\uszipcode\search.py", line 173, in _download_db_file_if_not_exists download_db_file( File "C:\Python310\lib\site-packages\uszipcode\db.py", line 33, in download_db_file Path(db_file_path).parent.mkdir(parents=True, exist_ok=True) File "C:\Python310\lib\site-packages\pathlib_mate\pathlib2.py", line 1614, in mkdir _try_except_filenotfounderror(_try_func, _exc_func) File "C:\Python310\lib\site-packages\pathlib_mate\pathlib2.py", line 117, in _try_except_filenotfounderror … -
How can I fix AWS Security Key Error Django Project?
I have Greatkart but I can't build this project enter image description here -
Django Signals for User Profile (Customer and Employee)
So I am trying to create a signal to create a profile for a newly created user. However, I need to have two different types of profiles: A customer profile and an employee profile. The type of profile which will be created is decided inside my User model via the "user_type" field: user/models.py: class User(AbstractBaseUser): USER_TYPES = ( ('Employee', 'employee'), ('Customer', 'customer'), ('Vendor', 'vendor') ) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) phone_number = models.CharField(max_length=20) user_type = models.CharField(max_length=8, choices=USER_TYPES) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' def __str__(self): return f'{self.first_name} {self.last_name} : {self.email}' def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin # if user.is_employee == True class EmployeeProfile(models.Model): EMPLOYEE_ROLES = ( ('Driver', 'driver'), ('Production', 'production'), ('Manager', 'manger') ) user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.CharField(max_length=12, choices=EMPLOYEE_ROLES) def __str__(self): return str(self.user) # if user.is_customer == True class … -
How to transfer django model field data to another field
I have a Django app in which I have videos. The description field for a video is set to CharField but I would like to change it to TextField. I don’t want to lose the data from my CharField but instead transfer it over to my TextField. How would I go about doing so? -
Css background url doesn't change django
I'm beginer and have realy dumb problem. In my Django project, i'm trying to make background picture for html page. CSS styels work right but pcture doesn't work. Here is css code in vscode: background: #9a8e77 url("image/intro-bg.jpg") center no-repeat; But in browser background have another url: browser If i change it to background: #9a8e77 url("image/intro-bg.jpg") center no-repeat; by my hands in browser it works. This problem only with background, another pictures have the right url "image/". Powersheel teling me this - ""GET /static/img/intro-bg.jpg HTTP/1.1" 404 1807" I check it 100 times, but don't get what's wrong. -
How do I assign permissions in for the user in Docker?
I am trying to run my DjangoRestFramework project in Docker. This is my deployment script and I am trying to check on my local machine before deploying to the Remote machine. I am able to successfully build the container using docker-compose -f docker-compose-deploy.yml build But when I try to run docker-compose -f docker-compose-deploy.yml up I get a PermissionError: [Errno 13] Permission denied. These are the details Operating System : Windows 10 Dockerfile FROM python:3.9.13-alpine3.16 LABEL maintainer="sohail.developes@gmail.com" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt COPY ./app /app COPY ./scripts /scripts WORKDIR /app EXPOSE 8000 RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ apk add --update --no-cache postgresql-client && \ apk add --update --no-cache --virtual .tmp-deps \ build-base postgresql-dev musl-dev linux-headers && \ /py/bin/pip install -r /requirements.txt && \ apk del .tmp-deps && \ adduser --disabled-password --no-create-home app && \ mkdir -p /vol/web/static && \ mkdir -p /vol/web/media && \ chown -R app:app /vol && \ chmod -R 755 /vol && \ chmod -R +x /scripts ENV PATH="/scripts:/py/bin:$PATH" USER app CMD ["run.sh"] This is my docker-compose.yml file version: "3.9" services: app: build: context: . restart: always volumes: - static-data:/vol/web environment: - DB_HOST=db - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASS=${DB_PASS} … -
Django technology implementation of line breaks by number of posts
My problem I am making a shopping mall using Django, Bootstrap I want to implement technology line break when the post becomes 4 I thought if I used col-3 and {$ for %} {% endfor %} it would be divided into four and line breaks. but not working How can i fix it? MY models from django.db import models class Cloth(models.Model): title = models.CharField(max_length=30) explain = models.CharField(max_length=30) price = models.IntegerField(blank=True) def __str__(self): return self.title My views from django.shortcuts import render from .models import Cloth def index(request): post = Cloth.objects.all() return render(request, 'Blog/index.html', {'post':post}) My urls from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] My index.html <div class="container py-3"> <h2 align="center"> Top </h2> </div> <div class="container py-2 px-1"> <div class="row"> {% for p in post %} <div class="card col-3" style="width: 16rem;"> <img src="http://placeimg.com/600/600/any" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title"> {{ p.title }}</h5> <p class="card-text"> {{ p.explain }}</p> <p> {{ p.price }}</p> </div> </div> {% endfor %} </div> -
How to discover the reason for a N+1 query in DRF serializer
I have a Django REST Framework -based project where one of the endpoints is super slow. Turns out it's a N+1 queries problem, where each of the returned row, of hundreds of rows, causes an additional query. The endpoint is not supposed to do any joins or additional queries, just return the contents of a single table, filtered a bit. The model for that table contains a few foreign keys, but none of the referents are supposed to be accessed, only the ID's are supposed to be rendered as JSON and sent to the client. A bit of trial and error reveals that it's DRF's Serializer that causes the additional queries: class FooSerializer(serializers.ModelSerializer): class Meta: model = Foo fields = ["data_field_a", "data_field_b", "bar_id", "qux_id"] When I comment bar_id out in the serializer, the query becomes as fast as expected. What's surprising is thatqux_id, even though the field is basically identical to bar_id, doesn't cause such a slowdown. I read https://www.django-rest-framework.org/api-guide/relations/ and among other stuff, tried setting depth = 0 in the Meta class. Also, I understand that using select_related or prefetch_related whould essentially serve as a quick fix for the problem, but strictly saying, those shouldn't be needed for this … -
dj-stripe (django) - How to distinguish between free trial vs. paying user?
How do you distinguish between a user who is on free trial vs. someone who is actually paying? Say it's a 30 day trial.. but someone decides to upgrade on day 10... so you can't go by date. -
Django choice field is not returning data through API endpoints
I have a custom User model and Profile model. In the Profile model I have 4 attributes: owner - OnetoOne relation with CustomUser gender - IntegerField with choices tuple. ie: (1, 'Male'), default=1 city - CharField country - CharField The serializer is defined with '__all__' fields. But the API endpoint is returning: { "id": 5, "city": null, "country": null } What I'm expecting from the API to return is all the fields defined in Profile Model. like this: { "id": 5, //Here I'm expecting the owners(CustomUser) Fields under user key "gender": 1, "city": null, "country": null } for better understanding please take a look at the code. My Custom User model: class CustomUser(AbstractBaseUser, PermissionsMixin): avatar = models.ImageField(upload_to="avatars/", null=True, blank=True) email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = CustomBaseUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def get_full_name(self): return self.name def __str__(self): return self.email Profile Model: GENDERS = ( (1, 'Male'), (2, 'Female'), (3, 'Other'), ) class Profile(models.Model): """Model for users profile""" owner = models.OneToOneField( CustomUser, on_delete=models.CASCADE, related_name='profile' ) gender = models.IntegerField(_('Gender'), default=1, choices=GENDERS) city = models.CharField(_('City'), max_length=255, null=True, blank=True) country = models.CharField(_('Country'), max_length=255, null=True, blank=True) def __str__(self): return f'profile-{self.id}-{self.owner.get_full_name()}' Profile Serializer: class ProfileSerializer(serializers.ModelSerializer): """Serializer … -
Permission denied from pre-commit, unable to access local python build
I am trying to commit some recent work and have been unable to get my precommit to work. I have changed permissions for this file, restarted the terminal, etc. Essentially the precommit script refuses to run. Any insight into this? Here is the error message I have been getting. $ git commit -m "test commit" .git/hooks/pre-commit: line 14: C:\Users\Josiah\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe: Permission denied .git/hooks/pre-commit: line 14: C:\Users\Josiah\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe: Permission denied also here is my current pre-commit file #!/usr/bin/env bash # File generated by pre-commit: https://pre-commit.com # start templated INSTALL_PYTHON='C:\Users\Josiah\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe' ARGS=(hook-impl --config=.pre-commit-config.yaml --hook-type=pre-commit) # end templated HERE="$(cd "$(dirname "$0")" && pwd)" ARGS+=(--hook-dir "$HERE" -- "$@") if [ -x "$INSTALL_PYTHON" ]; then exec "$INSTALL_PYTHON" -mpre_commit "${ARGS[@]}" elif command -v pre-commit > /dev/null; then exec pre-commit "${ARGS[@]}" else echo '`pre-commit` not found. Did you forget to activate your virtualenv?' 1>&2 exit 1 fi -
Django Filter name is not defined
I'm trying to filter my Todos by the test_id pulled from the URL. It pulls the id from the URL but it cant seem to filter with todo__test. I have also tried "test", "Todo.test.test_id", "Todo.test". I guess I'm confused about what variable I need to filter and the Django restframework documentation doesn't explicitly show what variable to use. Their example uses "purchaser__username" which I don't understand where it comes from. https://www.django-rest-framework.org/api-guide/filtering/ class TodoList(generics.ListAPIView): queryset = Todo.objects.all() serializer_class = TodoSerializer def get_queryset(self): test_id = self.kwargs['test_id'] return Todo.objects.filter(todo__test == test_id) class Todo(models.Model): test = models.ForeignKey(Test, on_delete=models.CASCADE) content = models.TextField(blank=True) order = models.IntegerField() def __str__(self): return self.content + ' - ' + self.test.test_name class Meta: ordering = ['test_id'] -
Cant upload multilple images using django admin
I have two models: one is the post model that can have multiple linked images. The image model has a foreign key to the post. That is, the images have a foreign key for a single post. When adding a new post I want to upload multiple images at the same time. Here is the code: model.py class Post(models.Model): title = models.CharField(max_length=255) thumbnail = models.ImageField(upload_to='thumbnails') summary = RichTextField() body = RichTextUploadingField() created_at = models.DateField(auto_now_add=True) class Meta: ordering = ['-created_at',] def __str__(self): return self.title class Imagens(models.Model): img = models.ImageField( upload_to = "media/", ) post = models.ForeignKey( "Post", on_delete=models.CASCADE, default=1) admin.py class ImageAdminForm(forms.ModelForm): class Meta: model = Imagens fields = ['img',] def __init__(self, *args, **kwargs): super(ImageAdminForm, self).__init__(*args, **kwargs) self.fields['img'] = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class ImageInline(admin.TabularInline): model = Imagens extra = 1 form = ImageAdminForm class PostAdmin(admin.ModelAdmin): search_fields = ['title'] inlines = [ImageInline,] def save_model(self, request, obj, form, change): obj.save() files = request.FILES.getlist('img') #he gets nothing print(files) for f in files: x = Imagens.objects.create(post=obj,img=f) x.save() admin.site.register(Post, PostAdmin) The problem is that if I save the post object it saves only one image and if I try to get the list of images it gives an empty list. Sorry I'm new to Django and even … -
Checkbox and function in Django
I welcome everyone who answers and helps if possible and thank you all in advance! There is a Django web application that downloads videos from YouTube using the python library. It will convert the video to audio and make a transcript of the text into a file. The question is that there is a variable in the language function that will change the language of text extraction. You need to change the value that corresponds to the video every time. How to make a language selection in a template that supports google web speech. I can't implement this idea, any help is welcome! Links to files at the bottom https://github.com/Erekeakz/Youtube-to-text.git -
Django; How can I display the questions foreign key for a responses table and then saving the responses using Django forms?
Hey I'm working on a survey app that has 7 questions and accepts a 1-3 integer answer for all of them except the last question which is free response. My models.py looks like this: class Question(models.Model): question = models.CharField(max_length=255) class Response(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="response") response = models.IntegerField(validators=[MinValueValidator(0),MaxValueValidator(3)]) respondantEmail = models.EmailField(unique=True) I was planning on storing the 7 questions in the questions table and then have the survey's response split into 7 rows per user submission. I don't know if there's a better approach to this so feel free to direct me towards another way of storing the responses. This works well in my admin view but I can't get it to display properly in the front-end. What I currently have is: Forms.py class ResponseForm(ModelForm): class Meta: model = Response fields = { "response","respondantEmail"} widgets = {"response": forms.TextInput(attrs={'type':"range", 'min':'1','max': '3'})} index.html <form action="{% url 'AssessmentForm:submit' %}" method="post"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> Now this obviously only displays a single range input field and an email input field but I'd like it to display a range field and an email field for every question there is stored in my Questions table, alongside the question itself. How do … -
How to return variables and store them from ready() method in Django?
I want to initialize a class ONCE when the app starts and store the return variable from the ready() method in apps.py. But I don't see how to return the variables. I searched google and everyone is pointing to apps.py is the preferred location to write these kinds of "Run Only Once" functions. This is my code- class MainPageConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'main_page' def ready(self) -> None: print("Hello ready") load_dotenv(".env") logging.set_verbosity_error() x, y = ModelProcessorCaller()() return x, y How to use this x and y later? What is the better alternative? And also why is the load_dotenv not working in the ready() method even though there is a .env file? The main idea is that I want to run this ModelProcessorCaller only once and store it for future use. -
How can i have same html for multiple categories or pages and then add specific or different data from database to them in django restframework?
In this program i have these two functions in my views.py: def home(request): p=product.objects.all() return render(request,'home.html',{'p':p}) def foods(request): p=product.objects.all() return render(request,'foods.html',{'p':p}) They both have access to the same data from database i mean if i want to post some json with django restframework then foods and home will have the same data because they have the same html: <div class="grid"> {% for i in p%} <div class='card'> <img src="{{i.image}}"></img> <p id="id">{{i.description}}</p> <a href="{{i.buy}}" target='_blank' rel='noopener noreferrer'> <button><span class="price"> ${{i.price}}</span> buy</button> </a> </div> {%endfor%} </div> it is good for me to have just one html for multiple pages and then access to different data from database but if i add some json both of them will contain the same data(for some reason data of foods is empty but it will generate the same number of products based on json like home) I want to know how can you have same html for multiple categories or pages and then add specific or different data from database to them? More details: models.py: from django.db import models # Create your models here. class product(models.Model): image=models.CharField(max_length=500) description=models.CharField(max_length=500) price=models.CharField(max_length=50) buy=models.CharField(max_length=100) serializers.py: from rest_framework import serializers from .models import product class productSerializer(serializers.ModelSerializer): class Meta: model= product fields="__all__" …