Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In DJANGO, Is there a way to transfer the existing users in django.contrib.auth to SAML or OpenID?
I have used django-oidc-provider, but all it does is create a new user. For a large pre-existing user datatbase, it is inconvenient to create new accounts for all users. I want to do this because I cannot integrate AWS services into my django website without an industry standard for federated authentication. -
Using Swup with Django
My Issue: I am trying to use Swup Library with Django's templating engine and everything worked well; except for the fetching of new content. The animations worked perfectly; I could see my contents getting faded out. The addresses in which the get requests are fetching worked perfectly as well; I could see the HTTP response code of 200 being returned in my console. However, the main content, after being faded out, were not being replaced. An example of Django Renderings: Base URL: http://127.0.0.1:8000 <!-- What is written in my code --> <a href="{% url 'home_view' %}" > <!-- What Django renders in the browser --> <a href="/" > in my urls.py: urlpatterns = [ path('', views.homeView, name='home_view'), ] A worthy note: Using dev tools, when hovering over the href rendered, it shows http://127.0.0.1:8000/ Another strange thing I encountered when trying to debug was that my html element has the following attributes added to it but it stay there even after the animation ends. <html lang="en" class="swup-enabled is-changing is-leaving is-animating to-homepage"> Swup config or any additional relevant code used: let options = { LINK_SELECTOR: 'a', debugMode: true, }; const swup = new Swup(options); The Scripts loaded perfectly; I was able to … -
Adding Additional Data to a Serialize Response in Django
I've created a working post response of data from the model using ModelSerialzer, which I call from a post method in a view class. I would like to add additional data to the response. This is the pertinent code from my CBV: resource_data = Resources.objects.all() serializer = ResourceSerializer(resource_data, many=True) #serializer.data["service"] = "All Services" return Response(serializer.data) The commented out line was my attempt to add data base on a similar post here. I get a 500 response in my API call. What is the correct way to do it? The response data is JSON if that's necessary to mention. -
integrating ebay authentication in django application
I am building a django application in which user will be able to sign up or sign in only via their EBay account, no email/username or password required. I couldn't find any authentication library for EBay though there are many for google, facebook, twitter etc. So I got the EBay part working. EBay basically returns (on consent of user) Email and a IEFS token which is unique to that user and wont change. I want to use those two fields only to create a authenticate user across whole application. I don't want username, emails, firstname, lastname or password that ships with django User model. The documentation is quite big and I am confused where to start, any proper suggestion will be big help. Thank you. -
Django POST request not posting anything to database
I cloned Django free source code on GitHub and making modifications to it. The aim of my application is that I wrote an ML algorithm that predicts if one is to have diabetes or not. Here is my issue, the person made use of a single function that calls multiples pages through the help of Django loader. Now hitting on the submit button I want that function to run a submit based on the current page I am on. The function is shown below @login_required(login_url="/login/") def pages(request): context = {} # All resource paths end in .html. # Pick out the html file name from the url. And load that template. try: load_template = request.path.split('/')[-1] print(load_template) context['segment'] = load_template if request.method == "POST": print("YES") print(request.POST) person = Person(request.POST) print(person) person.name = request.POST.get("name") person.email = request.POST.get("mail") print(person.email) person.dob = request.POST.get("dob") person.gender = request.POST.get("gender") person.pregnancy = request.POST.get("Pregnancies") person.glucose = request.POST.get("Glucose") person.blood_pressure = request.POST.get("BloodPressure") person.skin_thickness = request.POST.get("SkinThickness") person.insulin = request.POST.get("Insulin") person.bmi = request.POST.get("BMI") person.pedigree = request.POST.get("DiabetesPedigreeFunction") person.age = request.POST.get("Age") print(person.save()) ml_pickled_model = "django-datta-able-master/ml/dataset/ml model.pkl" person_data = np.array( [ [ person.pregnancy , person.glucose , person.blood_pressure, person.skin_thickness , person.insulin , person.bmi, person.pedigree , person.age ] ] ).reshape(1,8) test_model = joblib.load(open(ml_pickled_model, 'rb')) prediction = test_model.predict(person_data) print(prediction) … -
I tried to delete admin user and then I can't login to the cyberpanel
I tried to remove the default admin user on cyberpanel as follows: Create a new user with the highest authority admin Login cyberpnael with new user and go to user section to delete admin user. I got an error message, I don't remember what it is. I cannot delete it. Then I click on edit and try to change Owner to new user. And as a result I get the error message: 500 Server Error. I went into SSH and edited /usr/local/CyberCP/CyberCP/settings.py to turn on debug. I received the following error message: Environment: Request Method: GET Request URL: https://myip:port/ Django Version: 3.1.3 Python Version: 3.6.8 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'baseTemplate', 'loginSystem', 'packages', 'websiteFunctions', 'tuning', 'serverStatus', 'dns', 'ftp', 'userManagment', 'databases', 'mailServer', 'serverLogs', 'firewall', 'backup', 'managePHP', 'manageSSL', 'api', 'filemanager', 'manageServices', 'configservercsf', 'pluginHolder', 'emailPremium', 'emailMarketing', 'cloudAPI', 'highAvailability', 's3Backups', 'dockerManager', 'containerization', 'CLManager', 'IncBackups', 'WebTerminal'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'CyberCP.secMiddleware.secMiddleware'] Traceback (most recent call last): File "/usr/local/CyberCP/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/CyberCP/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/CyberCP/lib/python3.6/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/CyberCP/loginSystem/views.py", line 150, in loadLoginPage currentACL = ACLManager.loadedACL(userID) … -
I need to translate, or change "Please fill out this field" error message in UserCreationForm on Django
I have been trying and investigating a lot how to change just the error message, or just translate it to Spanish, but I do not manage to find quite the solution. I have tried using locale.Middleware on settings and adding the gettext to my Django project in order to translate it, no luck, here are the settings I am using: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] gettext = lambda x: x LANGUAGE_CODE = 'es' LANGUAGES = ( ('es', gettext('Spanish')), ) TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True After having those settings, and installing the gettext accordingly on my locale folder, no luck in translating the error messages. I have also tried on the forms.py changing the error_messages, but no luck, here is the code for the forms.py file (I have added 'required' everywhere just to see if the message slightly changes, no luck either, also I used 'required' and 'blank' neither worked): class CreateUserForm(UserCreationForm): first_name = forms.CharField(error_messages = {'required':"Ingrese su primer nombre"}, max_length=30,widget=forms.TextInput(attrs={'placeholder': 'Ingrese su nombre', 'class': "form-control"})) last_name = forms.CharField(error_messages = {'required':"Ingrese su segundo nombre"},max_length=30,widget=forms.TextInput(attrs={'placeholder': 'Ingrese su apellido', 'class': "form-control"})) password1 = forms.CharField( label="Password", error_messages = {'required':"Ingrese la … -
Django Get All Cookies With Name That Includes A Substring
I am making this simple random post system, and a problem I've been having is to recommend posts a user has not seen before. To differentiate a use who has seen a post and who has not seen a post, I store a cookie (for anonymous viewers) like so: def render_to_response(self, context, **response_kwargs): # Logic response.set_cookie(f'viewed{post_id}', 'true', max_age=60*60*24*10) # 30 Days Till Expiry This stores a cookie like if I have a post with id=12, it will be stored as: viewed12, true To get the value I do: request.COOKIES.get(f'viewed{post_id}') I want to know retrieve all cookies that begin with the string viewed and then I want to get everything after that (so I just want to get the id of the post from the cookie). This is my code: import random def random_post(request): objects_to_exclude = [1, 2, 8] # Using the cookies with substring "viewed" I want to insert into this list posts = Post.objects.all().exclude(pk__in=objects_to_exclude) post = random.choice(posts) return render(request, 'blog/post_detail.html', {'object': post, 'post': post, 'id': post.id, 'pk': post.id, 'random': 'True'}) Basically I want to find all the cookies with substring viewed, get the number after it, and then insert it into the list called objects_to_exclude. Edit: (I don't need … -
Rendering data to the templates Django
I'm trying to display the data from table using dynamic url. However, when I try to do so, it just rendered out the attribute of the table instead. But when I use the same syntax to print on the shell, it works here is my view def service_fait(request, my_id): if request.user.is_authenticated: elements = JobServices.objects.filter(id=my_id) for element in elements: print(element.service_name) print(element.hour) print(element.user) print(element.description) return render(request, 'services_faits.html', {'elements': elements}) else: return redirect('login') Here is the dynamic url: path('servicefait/<str:my_id>', views.service_fait, name='servicefait') And the template is: {% for tache in taches %}<a href="{% url 'servicefait' tache.id %}" class="btn btn-primary">Postuler</a>{% endfor %} Here is the output of the web page: element.service_name element.hour element.amount element.description And the shell is working properly as it shows the content of the above attribute And finally, here is the model: class JobServices(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) service_name = models.CharField(max_length=100, default="nom du service") hour = models.IntegerField(default="Heures") amount = models.FloatField(default="Cout") service_date = models.DateTimeField(auto_now_add=True, null=True) description = models.CharField(max_length=2000, null=True, default="annonce") image_url = models.CharField(max_length=2000, null=True, blank=True) image = models.ImageField(null=True, blank=True) -
Optional Subfactory
I would like to create a subfactory that only creates instances if the user requests it at call time. Given these models: class Group(models.Model): name = models.CharField() class Member(models.Model): name = models.CharField() group = models.ForeigKey(Group, blank=True, null=True) And this factory: class MemberFactory(factory.django.DjangoModelFactory): class Meta: model = Member name = factory.Sequence("Member {}".format) group = factory.Subfactory(GroupFactory) I would like the option of only creating a group if explicitly requested, but without losing all other features. In other words these should all work: MemberFactory() # Expect group=None MemberFactory(group=True) # Expect group=GroupFactory() MemberFactory(group__name="ABC") MemberFactory(group=Group.objects.get(...)) -
Issue with accents in Django
i've got the following code: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title>Página de prueba</title> </head> <body> <h1>Esto es una página de prueba</h1><br> Página de prueba para Python </body> </html> But, when i try to search it in any browser, this happens: Error What can I do? Thanks. -
How to query on values of foreign key in django
I have 4 models/tables. I am using Django's default SQLite database. Institutional User class InstituitionalUser(models.Model): fullName = models.CharField(max_length=50) postcode = models.CharField(max_length=50) email = models.CharField(max_length=50) password = models.CharField(max_length=50) Professional User class ProfessionalUser(models.Model): firstName = models.CharField(max_length=50) lastName = models.CharField(max_length=50) password = models.CharField(max_length=50) email = models.CharField(max_length=50) phone = models.IntegerField() Institute Open Positions class InstituteOpenPositions(models.Model): institueId = models.ForeignKey(InstituitionalUser, on_delete=models.CASCADE, related_name='institue') title = models.CharField(max_length=50) status = models.CharField(max_length=10) Work applications class ProfessionalWorkApplications(models.Model): workapplicant = models.ForeignKey(ProfessionalUser, on_delete=models.CASCADE, related_name='profworkapplicant') appliedJobs = models.ForeignKey(InstituteOpenPositions, on_delete=models.CASCADE, related_name='profappliedJobs') createdOn = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=10) Steps Institutional User can create a Job which is stored in Institute Open Positions table with Institute as a foreign key. Professional Users can see that job and Apply for that position. If they apply the action is getting stored in the Work applications table. In the Work applications table, I am storing reference of a ProfessionalUser who has applied for a position and the open position as appliedJobs. Now my question I want to write a query to get all the applications received for a given institute. In other words, I have Work applications table, I have mapped InstituteOpenPosition object and InstituteOpenPositions table has the Institue as a foreign key. I can say that I want to … -
Django - DeleteView with pk. No Posty matches the given query
Heeey I have a problem with get_success_url. Namely I would delete a comment from post and then should go back to the page with the post. On this moment have i "No Posty matches the given query." I dont have idea how i can resolve this. I know how to reverse on page with no pk ;( Models class Posty(models.Model): title = models.CharField(max_length=250, blank=False, null=False, unique=True) sub_title = models.SlugField(max_length=250, blank=False, null=False, unique=True) content = models.TextField(max_length=250, blank=False, null=False) image = models.ImageField(default="avatar.png",upload_to="images", validators=[FileExtensionValidator(['png','jpg','jpeg'])]) author = models.ForeignKey(Profil, on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True) published = models.DateTimeField(auto_now_add=True) T_or_F = models.BooleanField(default=False) class Meta: verbose_name_plural = 'Posty' def __str__(self): return str(self.title) def save(self, *args, **kwargs): if not self.sub_title: self.sub_title = slugify(self.title) super(Posty,self).save(*args, **kwargs) def get_absolute_url(self): return reverse('home:detail_post', kwargs={"id":self.id}) Views class delete_post_comment(DeleteView): model = CommentModelForm() template_name = 'delete_comment_from_post.html' def get_object(self): id_ = self.kwargs.get("id") return get_object_or_404(Posty,id=id_) def get_success_url(self): return reverse('home:detail_post') Urls urlpatterns = [ path('', home, name='home'), path('forum/', create_post_and_comment, name='forum'), path('delete_post/<int:pk>/', delete_post_view.as_view(model=Posty), name='delete_post'), path('update_post/<int:pk>/', update_post_view.as_view(model=Posty), name='update_post'), path('delete_post_comment/<int:pk>/', delete_post_comment.as_view(model=CommentPost), name='delete_post_comment'), path('update_post_comment/<int:pk>/', update_post_comment.as_view(model=CommentPost), name='update_post_comment'), path('detail_post/<int:pk>/', contact, name='detail_post'), path('testuje/<int:pk>/', contact, name='test') Forms class CommentModelForm(forms.ModelForm): content1 = forms.CharField(widget=forms.Textarea(attrs={})) class Meta: model = CommentPost fields = ('content1',) -
NGINX-WSS connection failing but WS connection works
I am having trouble implementing wss connections in my app over port 443. When connecting to my app over port 80 I able to connect to the socket(ws connection). my app works fine with HTTPS requests(can log in and request data) but cannot handle wss properly. The console logs failed to connect, with no server error codes. nginx file server 80: server { listen 80; server_name test.com; root html\test.com; index index.html index.htm; location /api/ { proxy_pass http://xxx.xxx.xxx.xx:xxxx; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location /widget/{ proxy_pass http://xxx.xxx.xxx.xx:xxxx/widget/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } The above code works fine nginx file server 443: server { listen 443 ssl; server_name test.com; root html\test.com; index index.html index.htm; ssl_certificate C:/Certbot/live/test.com/fullchain.pem; ssl_certificate_key C:/Certbot/live/test.com/privkey.pem; location /api/ { proxy_pass http://xxx.xxx.xxx.xx:xxxx; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location /widget/{ proxy_pass http://xxx.xxx.xxx.xx:xxxx/widget/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } I am able to make https requests but I … -
How can I create group with the same name as the role name in DRF generics APIView
I'm trying to create a new group each time a user create a role, the problem I keep having errors in my code logic, and I don't really know what to do to make it work, here is what I came with so far : from rest_framework import generics from django.contrib.auth.models import Group class CreateRoleView(generics.ListCreateAPIView): queryset = Roles.objects.all() serializer_class = CreateRolesSerializers permission_classes = (IsAuthenticated,) def post(self, request, *args, **kwargs): role_name=self.kwargs['role_name'] created = Group.objects.create(name=role_name) return self.create(request, created, *args, **kwargs) and here is a screen of my problem : enter image description here -
Django Rest Framework save multiple serializers in a celery task
Am using Django rest framework, Celery, and RabbitMQ for my aplication. I have a task that does some data processing and saves the results as objects in my Django application. The task has two different results that need to be saved, so two model serializers are needed. The problem is that when the task is performed only one of the models is being saved. I tried the method while it was not a celery task and it worked perfectly, and i don't know what changes when it is run as a task that it won't work any more. this is the code runned in the task: def createMBGSimulations(petition_id): ... Data process ... prices = s_Q.tolist() lists_ci = cis.tolist() serializer = serializers.PriceSerializer(data={}) serializer_ci = serializers.ConfidenceIntervalSerializer(data={}) if serializer.is_valid(): petition = models.Petition.objects.get(pk=petition_id) serializer.save(prices=prices, petition=petition) if serializer_ci.is_valid(): serializer_ci.save(ci=lists_ci, petition=petition) petition.clean() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django REST Framework: handle exception for custom permission class
I built a custom permission class in Django that verifies the remote IP address of the request. If the request IP is one that's allowed, the has_permission class returns True, otherwise it returns False and the view responds with status code 403.. class isVerifiedServer(permissions.BasePermission): def has_permission(self, request, view): ip_addr = request.META['REMOTE_ADDR'] return ip_addr == some_verified_ip But I want the view to return 404 when this test fails, which is what the server responds with by default when a request is sent to a non-existent URL endpoint. I want to do this to make sure no one can figure out what a valid endpoint is. DRF documentation says the following about changing the exception response of a custom permission class: Custom permissions will raise a PermissionDenied exception if the test fails. To change the error message associated with the exception, implement a message attribute directly on your custom permission. Otherwise the default_detail attribute from PermissionDenied will be used. Similarly, to change the code identifier associated with the exception, implement a code attribute directly on your custom permission - otherwise the default_code attribute from PermissionDenied will be used. I've tried setting many attributes to achieve this, but the response is still always … -
Cannot get autocompletion on Django Model Manager in PyCharm
I'm trying to use autocompletion to get methods like filter, count, create, etc. in PyCharm, but I can't seem to grab them from the objects attribute. It seems like this specific attribute is not working - since PyCharm provides autocompletion for the class itself, for example, just not objects. I've tried refreshing the virtual environment as well, but it seems like it might just not be a supported features. It doesn't autocomplete in either Pycharm 2020.3 or Pycharm 2021.2., or in abstract or concrete classes. -
DRF serialize foreign key return object, not ID
I have a OneToMany relation. One Construction and many Cameras. I want to return all Building object fields in CameraSerializer Problem When I perform POST request (create new Camera object) { "name": "CameraName", "url": "CameraUrl", "building": 2 } I have an error { "building": { "nonFieldErrors": [ "Invalid data. Expected a dictionary, but got int." ] } } Reason of error -- Django expects FULL Construction object, but I want to set only ID How can I fix the error? models.py class Construction(models.Model): """ Объект строительства""" developer = models.ForeignKey( Developer, related_name="constructions", on_delete=models.CASCADE ) name = models.CharField(max_length=100) plan_image = models.ImageField(upload_to=name_image, blank=True, null=True) ... def __str__(self): return self.name class Camera(models.Model): building = models.ForeignKey( Construction, related_name="cameras", on_delete=models.CASCADE ) name = models.CharField(max_length=100) url = models.CharField(max_length=100) ... def __str__(self): return self.name serializers.py class ConstructionSerializer(serializers.ModelSerializer): coordinates = MyPointField() deadline = serializers.DateTimeField(format=TIME_FORMAT) cameras_number = serializers.SerializerMethodField() developer_name = serializers.SerializerMethodField() events = serializers.SerializerMethodField() class Meta: model = Construction fields = ( 'id', 'developer', 'developer_name', 'name', 'plan_image', 'address', 'coordinates', 'deadline', 'workers_number', 'machines_number', 'cameras_number', 'events' ) read_only_fields = ('workers_number', 'machines_number', 'cameras_number', 'events') def create(self, validated_data): instance = super().create(validated_data=validated_data) return instance class CameraSerializer(serializers.ModelSerializer): frames = FrameSerializer(many=True, read_only=True) building = ConstructionSerializer() class Meta: model = Camera fields = ( 'id', 'building', 'name', 'url', … -
Error: Deploying Django app into Heroku push rejected
Hello Can anyone help me with this error. I am trying to run git push heroku :main but this is continuously failing. I am trying to deploy heroku django app. Enumerating objects: 536, done. Counting objects: 100% (536/536), done. Delta compression using up to 2 threads Compressing objects: 100% (472/472), done. Writing objects: 100% (536/536), 102.08 KiB | 967.00 KiB/s, done. Total 536 (delta 291), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-18 stack remote: -----> Using buildpack: heroku/python remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: ! Python has released a security update! Please consider upgrading to python-3.8.11 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.8.10 remote: -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting appdirs==1.4.4 remote: Downloading appdirs-1.4.4-py2.py3-none-any.whl (9.6 kB) remote: ERROR: Could not find a version that satisfies the requirement apturl==0.5.2 (from -r /tmp/build_a3e7552b/requirements.txt (line 2)) (from versions: none) remote: ERROR: No matching distribution found for apturl==0.5.2 (from -r /tmp/build_a3e7552b/requirements.txt (line 2)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push … -
Pulling profile data from Google OAuth2 for custom Django User Model
I am currently attempting to program a web app using the Django and React Framework, and want to add a feature in which users can sign up with their Google Accounts. Once a certain user is signed in with their Google Account, I would like to extend the profile using a Django User (or AbstractBaseUser) Model with more fields such as some pictures or favorite colors. However, I am lost on how and where to implement this in my code. Any help would be greatly appreciated! -
Django manage.py - differentiate runserver and/or actual server running from other command contexts?
Suppose I have some code in one of the urls.py that really shouldn't be run during a lot of the Django management/maintenance commands. Is there a way to know what context the code is being loaded for, other than checking sys.argv directly and explicitly? ... def setup_at_startup(): """code here would definitely fail on python manage.py makemigrations/migrate but let's it's discovery code to figure out some services """ #pseudo-code if django.command in ("makemigrations", "migrate", "<others>"): return do-code-that-blows-up #gets run at import urls.py time. setup_at_startup() ... What's a good portable way to test for this, including Django being accessed via gunicorn or the like? -
How do I run Django test using a CustomUser(AbstractUser) class instead of default AbstractUser for correct ForeignKey assignment during test?
I have a CustomUser model in 'accounts' app that overrides Django's default auth.User: class CustomUser(AbstractUser): age = PositiveIntegerField(null=True, blank=True) user_type = CharField(max_length=8, null=False, choices=[('customer', 'Customer'), ('owner', 'Owner')]) And another app 'ecommerce' with a model Product (abbreviated for brevity) with a ForeignKey to the CustomUser field above: class Product(Model): name = CharField(max_length=255, null=False, blank=False) [...] seller = ForeignKey(CustomUser, on_delete=CASCADE, related_name='products') When I create the new Product, I'm using form_valid() function on the model to set the user based on the request that Django uses via CreateView. This works when I'm working in a browser, however does not when I am trying to validate my ProductCreateView through a test a script: views.py class ProductCreateView(CreateView): model = Product [...] def form_valid(self, form): form.instance.seller = self.request.user return super().form_valid(form) test.py def test_product_create_view(self): response = self.client.post( reverse('ecommerce_post_product'), { 'name': 'newProduct', 'price': 2.99, 'category': 'newCategory', 'quantity': 100, 'shipping': 'standard', }) # error happens here self.assertEqual(response.status_code, 302) # test does not reach this line When I run my tests, this test always throws an error stating, ValueError: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7fbce54f0040>>": "Product.seller" must be a "CustomUser" instance." I have tried passing in the self.user that I defined in the 'setUp()' function of the TestCase with … -
Django fetch FK data
Hello I am trying to replicate this raw sql query with Django ORM. SELECT G.ID, G.DEFAULT_VAL, G.tag_flg,M.TRANSLATION_ID, M.language_id FROM translation.GLOSSARY G LEFT JOIN translation.GLOSSARY_TRANS_MAP M ON M.GLOSSARY_ID = G.ID and M.LANGUAGE_ID = {language_id} LEFT JOIN translation.GLOSSARY_TRANSLATION T ON T.ID = M.TRANSLATION_ID The models that I have are these: class ReportLanguage(models.Model): iso_cd = models.CharField(max_length=50) display_nm = models.CharField(max_length=50) class Meta: managed = False db_table = 'report_language' class Glossary(models.Model): placeholder = models.CharField(max_length=50) default_val = models.CharField(max_length=150) tag_flg = models.BooleanField() class Meta: managed = False db_table = 'glossary' class GlossaryTransMap(models.Model): glossary = models.ForeignKey('Glossary', models.DO_NOTHING) translation = models.ForeignKey('GlossaryTranslation', models.DO_NOTHING) language = models.ForeignKey('ReportLanguage', models.DO_NOTHING) class Meta: managed = False db_table = 'glossary_trans_map' class GlossaryTranslation(models.Model): translated_val = models.CharField(max_length=1000) crt_dts = models.DateTimeField() crt_user = models.CharField(max_length=255) upd_dts = models.DateTimeField() upd_user = models.CharField(max_length=255) glossary = models.ForeignKey('Glossary', models.DO_NOTHING) translation = models.ForeignKey('GlossaryTranslation', models.DO_NOTHING) class Meta: managed = False db_table = 'glossary_translation' I was able to get similar response as i get from the query with this orm all_glossaries = GlossaryTransMap.objects.select_related('translation', 'glossary', 'language').values( 'glossary__id', 'translation', 'language', default_val=F('glossary__default_val'), tag_flg=F('glossary__tag_flg')).filter(language__id=lang_id) Also the serializer that i created looks like this: class AllGlossariesData(serializers.ModelSerializer): id = serializers.SerializerMethodField() default_val = serializers.SerializerMethodField() tag_flg = serializers.SerializerMethodField() translation_id = serializers.SerializerMethodField() language_id = serializers.SerializerMethodField() class Meta: model = GlossaryTransMap fields = ['id', 'default_val', 'tag_flg','translation_id', … -
How to add watermark to video while saving using django
I'm new in django. How to add watermark to video file while saving using django?