Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get max value from a set of rows
This question is in relation to project 2 of the cs50 course which can be found here I have looked at the following documentation: Django queryset API ref Django making queries Plus, I have also taken a look at the aggregate and annotate things. I've created the table in the template file, which is pretty straight forward I think. The missing column is what I'm trying to fill. Image below These are the models that I have created class User(AbstractUser): pass class Category(models.Model): category = models.CharField(max_length=50) def __str__(self): return self.category class Listing(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField() initial_bid = models.IntegerField() category = models.ForeignKey(Category, on_delete=models.CASCADE) date_created = models.DateField(auto_now=True) def __str__(self): return self.title class Bid(models.Model): whoDidBid = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) list_item = models.ForeignKey(Listing, default=0, on_delete=models.CASCADE) bid = models.IntegerField() category = models.ForeignKey(Category, on_delete=models.CASCADE) date = models.DateTimeField(auto_now=True) def __str__(self): return_string = '{0.whoDidBid} {0.list_item} {0.bid}' return return_string.format(self) This is the closest I could come to after a very long time. But the result I get is just the number 2. Ref image below Listing.objects.filter(title='Cabinet').aggregate(Max('bid')) Where 'Cabinet' is a Listing object that I have created. And placed two bids on them. So the question is, how do I get the Maximum bid … -
Unknown issue in Django machine learning app
I loaded a basic machine learning model using joblib in my django app and there is no error but predict method is showing same value even for different user inputs views.py def myapp(request): if(request.method =='POST'): mylis=[] test=joblib.load('/mltestapp/test.sav') mylis.append(request.POST.get('day')) obj= test.predict([mylis]) return render(request,'mltestapp/myapp.html',{'obj':obj[0][2]}) return render(request,'mltestapp/myapp.html') -
ValueError at /accounts/profile/edit/,,,,, Field 'id' expected a number but got 'edit'
models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from phonenumber_field.modelfields import PhoneNumberField class UserprofileCity(models.manager): def get_queryset(self): return super(UserprofileCity,self).get_queryset().filter(city='surat') class UserProfile(models.Model): user= models.OneToOneField(User,on_delete=models.CASCADE) # you an add extra fields as per requirements after city = models.CharField(max_length=100,default='') description = models.CharField(max_length= 500,default='') phone_number = PhoneNumberField(default='+91',max_length=13,help_text='enter mobile number with country code') age = models.IntegerField(default=18) image = models.ImageField(upload_to='profile_image',blank=True) def __str__(self): return self.user.username def create_profile(sender,**kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile,sender=User) views.py: from django.shortcuts import render,redirect from django.urls import reverse from .forms import RegistrationForm,EditProfileForm,ProfileForm from django.contrib.auth.models import User from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth import update_session_auth_hash def register(request): if request.method =='POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect(reverse('accounts:login')) else: form = RegistrationForm() args = {'form':form} return render(request,'accounts/reg_form.html',args) def profile_view(request,pk=None): if pk: user = User.objects.get(pk=pk) else: user = request.user args = {'user':user} return render(request,'accounts/profile.html',args) def profile_edit(request): if request.method =='POST': form = EditProfileForm(request.POST,instance=request.user) profile_form = ProfileForm(request.Post,request.FILES,instance=request.user.userprofile) if form.is_valid() and profile_form.is_valid(): user_form = form.save() custom_form = profile_form.save(False) custom_form.user = user_form custom_form.save() return redirect(reverse('accounts:profile_view')) else: form = EditProfileForm(instance=request.user) profile_form = ProfileForm(instance=request.user.userprofile) args = { 'form':form, 'profile_form':profile_form } return render(request,'accounts/profile_edit.html',args) def password_change(request): if request.method=='POST': form = PasswordChangeForm(data = request.POST,user=request.user) if form.is_valid(): form.save() update_session_auth_hash(request,form.user) return redirect(reverse('accounts:profile_view')) else: return redirect(reverse('accounts:change_password')) else: form = PasswordChangeForm(user = request.user) args … -
How to generate a new record based on the current new one and another one in the model in Django?
I need to create one record when user pass one and there is another one already in the model with same or suitable data. For example: models.py class Generated(models.Model): stage = models.PositiveSmallIntegerField() group = models.PositiveSmallIntegerField() and we already have a record Generated(stage=1, group=1) then we pass another one Generated(stage=1, group=2) and we need to generate one more record like Generated(stage=2, group=1) I just need to know how to get/find records in model when we check current passed record and then create one. -
Access to XMLHttpRequest at 'api url'' from origin 'client url'' has been blocked by CORS policy
i am working on full stack web and mobile projects with Django as backend and react/react-native as frontend. i am trying to post a form, it works great on react but it shows error in my react-native app. how can i post this form successfully? error screenshot below users.js export const CreateMerchantDetails = (formValues) => async (dispatch) => { console.log(formValues); const token = await AsyncStorage.getItem("token"); console.log(token); const config = { headers: { Authorization: "Token ".concat(token), }, }; axios .post(`${ROOT_URL}api/merchant/create`, formValues, { headers: config, }) .then((res) => { dispatch({ type: actionTypes.CREATE_MERCHANT_DETAILS, payload: res.data, }); }) .catch((err) => { console.log(err); const error = { msg: err.response, // status: err.response.status, }; dispatch({ type: actionTypes.CREATE_MERCHANT_DETAILS_ERROR, payload: error.response, }); }); }; screenshots settings.js import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'secret_key_here' DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'corsheaders', 'rest_auth', 'rest_auth.registration', 'rest_framework.authtoken', 'phonenumber_field', 'merchant', 'orders', 'notifications' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'romex.urls' AUTH_USER_MODEL = 'merchant.MerchantDetails' REST_AUTH_REGISTER_SERIALIZERS = { "REGISTER_SERIALIZER": "merchant.api.serializers.CustomRegisterSerializer", } REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 10 } REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'] } TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': … -
Secure file sharing
I'm doing a project on secure file sharing using django framework. Can anyone answer my questions?? where should I upload my file's After uploading a file it must encrypt in aes format. 3)the uploaded files could only be retrieved when 2nd user having the key whic was generated during encryption. Now can anyone answer how to do these tasks using django. -
Django Deployment on CPanel Error "Apache doesn't have read permissions to that file. Please fix the relevant file permissions."
I am trying to deploy a django application on cpanel. I cloned my github repository and all dependencies have been installed and everything is complete but when I try to open the website it gives me this page... What do I need to do in order to fix this? I don't have any knowledge about these file permissions and am just looking to host a small project. -
Django show name of reference not id
this simple database i created then this my code for showing the data in view.py ... def get (request, photo_id) tag = PhotoTag.objects \ .values('tag_id') \ .filter(photo_id = photo_id) \ .all() context = { ... 'my_tag': tag } and this is in my template {% for data in my_tag %} {{ my_tag.tag_id }} {% endfor %} the result is number, what I need is showing the data of another table (tag table) like my_tag => tag_id => name (of another table) when I do another way in view.py like tag = PhotoTag.objects \ .values('tag_id') \ .filter(photo_id = photo_id) \ .all() for data in tag: tag_name = Tag.objects \ .values('name') \ .filter(id=data.get('tag_id')) \ context = { ..., 'my_tag': tag_name, } then in template {% for data in my_tag %} {{ my_tag.name }} {% endfor %} the result is what I need (showing the text name of references table) but it's only 1 data, it's not perfectly loop So Can someone help me solve this problem, or have a magic trick for solve it? -
How to add a foreign key to the username. Django REST framework
During serialization, i noticed that the post_author Foreign Key of the Post model is referencing the id of the creator and thus, i can't display the username of the creator in the REST API, only the post_author id. How can i add the username of the post_creator, so that it is readable to other users, when i fetch the data on the frontend? models.py // CustomUser = the Creator of the post. class CustomUser(AbstractUser): fav_color = models.CharField(blank=True, max_length=120) class Post(models.Model): post_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='posts') post_title = models.CharField(max_length=200) post_body = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def __str__(self): return self.post_title views.py @api_view(['GET']) def post_list(request): posts = Post.objects.all() serializer = PostSerializer(posts, many=True) return Response(serializer.data) serializers.py user model and post model serialization class CustomUserSerializer(serializers.ModelSerializer): """ Currently unused in preference of the below. """ email = serializers.EmailField(required=True) username = serializers.CharField() password = serializers.CharField(min_length=8, write_only=True) class Meta: model = CustomUser fields = ('email', 'username', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password', None) # as long as the fields are the same, we can just use this instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = … -
Presenting ForeignKey Field As Radio Choices
I have the following setup: MODELS.PY class MeatMenu(models.Model): MEAT_CHOICES = ( ('chicken', 'Chicken'), ('beef', 'Beef'), ) meat_type = models.CharField(max_length=20, choices=MEAT_CHOICES) meat_price = models.DecimalField(max_digits=10, decimal_places=2) In the same model file, I use the MeatMenu model as a fk to allow users to buy the meat they want (can calc total cost using price [hence the need for a fk as opposed to direct model choices]) class BuyMeat(models.Model): client = models.ForeignKey(User, on_delete=models.CASCADE) meat_needed = models.ForeignKey(MeatMenu, on_delete=models.SET_NULL, blank=True, null=True) date_created = models.DateTimeField(default=timezone.now) class Meta: ordering = ('-date_created',) def __str__(self): return str(self.meat_needed) FORMS.PY In my form, I'm trying to have a user execute an order for the meat they want as follows: class BuyMeatForm(forms.ModelForm): meat_needed = forms.ModelChoiceField(queryset=None, to_field_name='service_name', widget=forms.RadioSelect, empty_label=None) class Meta: model = BuyMeat fields = '__all__' exclude = ('client', 'date_created') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['service_needed'].queryset = MeatMenu.objects.all() VIEWS.PY def buy_meat(request): if request.method == 'POST': form = BuyMeatForm(request.POST) if form.is_valid(): new_purchase = form.save(commit=False) new_purchase.client = request.user new_purchase.date_created = timezone.now() new_purchase.save() else: form = BuyMeatForm() context = {'buy_form': form} .................... PROBLEM The problem comes in customizing my "meat_needed" field in the form. As you can see in my forms.py file, I would like to customize the foreignkey dropdown-select into radio buttons whereby … -
Django static files not served with Docker
please find below my app architecture. static files are located at /my_project/app/static/ when i 'jump' into my web container docker exec -it my_project sh /usr/src/app/static folder do not contain static files I guess problem is path to serve static files but what is wrong with my configuration? - my_project |_app |_core |_wsqi.py |_settings |_base.py |_dev.py |_prod.py |_urls.py |_requirements |_static |_base.txt |_dev.txt |_prod.txt |_Dockerfile.prod |_entrypoint.prod.sh |_manage.py |_.dockerignore |_nginx |_Dockerfile |_nginx.conf |_.env.prod |_.gitignore |_docker-compose.prod.yml prod.py SITE_ID = 1 STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "static") MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media") docker-compose.prod.yml version: '3.7' services: web: restart: always build: context: ./app dockerfile: Dockerfile.prod restart: always command: gunicorn core.wsgi:application --bind 0.0.0.0:8000 volumes: - ./app:/usr/src/app - static_volume:/usr/src/app/static - media_volume:/usr/src/app/media expose: - 8000 env_file: - ./.env.prod extra_hosts: - "db:192........" nginx: build: ./nginx restart: always volumes: - static_volume:/usr/src/app/static - media_volume:/usr/src/app/media ports: - 1338:80 depends_on: - web volumes: static_volume: media_volume: nginx.conf upstream app { server web:8000; } server { listen 80; server_name localhost; location / { proxy_pass http://app; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /usr/src/app/static/; } location /media/ { alias /usr/src/app/media/; } } -
Rest Framework Ordering Filter for Models Method
I have a model that has method for calculating average rating. How can I add this method to ordering filter fields? I tried to do custom filter with FilterSet but I cannot manage to do that. I received error when I tested my attempts. There are no any example for Order Filtering. I added a filter for average rating with greater than lookup as it is shared below but I couldnt way to add it for order filtering. Model Class: class Establishment(models.Model): owner = models.ForeignKey(User, on_delete=models.PROTECT) name = models.CharField(max_length=255, null= False, blank = False, unique=True) description = models.TextField(max_length=360, blank = True, null=True) address = models.TextField(max_length=360, blank = True, null=True) phone = PhoneNumberField(null=False, blank=False) city = models.CharField(max_length=15, null= False, blank = False) district = models.CharField(max_length=50, null= False, blank = False) latitude = models.DecimalField(max_digits=9, decimal_places=6, null=False, blank=False) longitude = models.DecimalField(max_digits=9, decimal_places=6, null=False, blank=False) cuisine = models.CharField(max_length=255, null= False, blank = False) zipcode = models.IntegerField(null=True, blank=True) average_price = models.IntegerField(blank = True, null=True) profile_photo = models.ImageField(blank=True, null=True, upload_to=upload_path('profile_image')) def no_of_ratings(self): ratings = EstablishmentRating.objects.filter(establishment=self) return len(ratings) def average_rating(self): ratings = EstablishmentRating.objects.filter(establishment=self) return sum(rate.rating for rate in ratings) / (len(ratings) or 1) def __str__(self): return self.name Related ViewSet: class EstablishmentViewSet(viewsets.ModelViewSet): queryset = Establishment.objects.all() serializer_class = EstablishmentSerializer … -
Django Dump Json Data for recommended recipes
Hi everyone I'm looking for help on how to accomplish this. I'm building a Rest API and want to dump an existing db table filled with recipes. this table can be search by users and have recipes selected from the table. Can this be done? is there a command to dump a existing db to json data? I know django will auto create the models, do i then just have to write the serializer and views to search this data and have an authenticated user be able to add a recipe from this to their own list? NOT LOOKING FOR CODE BEYOND SIMPLE COMMANDS. Looking for advice on how to accomplish this? Thanks -
Pop-up message after submiting a form in django
I'm building a website with django, and I have the newsletter functionality. I'm not so good on the frontend but I want to implement a toggle message after the submit button is clicked. I'm not sure how am I suppose to handle this. I've connected the newsletter form with the pop-up message, but the problem is that when the submit is clicked the page is reloaded because of the view function, I tried to not return a redirect but in this case and in the first with the redirect function it doesn't display me the message. the view function def newsletter_subscribe(request): if NewsletterUser.objects.filter(email=request.POST['newsletter_email']).exists(): messages.warning( request, 'This email is already subscribed in our system') else: NewsletterUser.objects.create(email=request.POST['newsletter_email']) messages.success(request, 'Your email was subscribed in our system, you\'ll hear from us as soon as possible !') return redirect('index') newsletter form <section class="bg-gray section-padding"> <div class="container"> <div class="section-intro pb-5 mb-xl-2 text-center"> <h2 class="mb-4">Subscribe To Get Our Newsletter</h2> <p>We post very often on the blog and bring updates on the platform, if you will subscribe you will hear from us everything as soon we made the changes</p> </div> <form class="form-subscribe" action="{% url 'newsletter-subscribe' %}" method="POST"> {% csrf_token %} <div class="input-group align-items-center"> <input type="text" class="form-control" name="newsletter_email" placeholder="Enter … -
How to build a registration and login api using function based views in django rest framework?
I want to create a token authenticated registration and login api using django's built in User model with django rest framework(DRF) using function based views (FBV). Most of the articles which I found in the web are for class based views and there are not much resources available for FBV in the web. From whatever resources including CBV I found in the net, I coded this, # project/settings.py INSTALLED_APPS = [ ... 'rest_framework.authtoken' ] # app/serializers.py from django.contrib.auth.models import User class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password']) return user class LoginSerializer(serializers.ModelSerializer): # TO DO # app/views.py @api_view(['POST'],) def register(request): if request.method == 'POST': register_serializer = RegisterSerializer(data=request.data) if register_serializer.is_valid(): print("Its working") return Response({'Failed':'Failed to create'}) @api_view(['POST'],) def login(request): if request.method == 'POST': login_serializer = # TO DO if login_serializer.is_valid(): print("Its working") return Response({'Failed':'Failed to login'}) # app/urls.py urlpatterns = [ path('register/', views.register, name="register"), path('login/', views.login, name="login"), ] The above register and login are not complete and lacks a proper serilizers object and user creation/validation methods. I still tried to run the above code with this post request {id:,username:"user1", email:"email@email.com",password:"password123"}, id was kept … -
I need help regarding structuring django models and quering them with ease
please I need your help with this: I am building a Django web App that will count the total number of persons entering and exiting a school library in a day, week and year and then save to DB. The Web App uses a camera that is controlled by OpenCv to show live feed on frontend (I have successfully implemented this already). My problem is: How can I design and structure my models to store each data by day, week, month and year? And how can I query them to display them on different Bar Charts using chart.js? Thanks. -
Django duplicate queries
I'm trying to optimize my django app using select and prefetch related but for some reason it doesn't work this is my models : class Question(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(blank=True, default='avatar.png') and this is my serializers : class EagerLoadingMixin: @classmethod def setup_eager_loading(cls, queryset): if hasattr(cls, "_SELECT_RELATED_FIELDS"): queryset = queryset.select_related(*cls._SELECT_RELATED_FIELDS) if hasattr(cls, "_PREFETCH_RELATED_FIELDS"): queryset = queryset.prefetch_related(*cls._PREFETCH_RELATED_FIELDS) return queryset class QuestionSerializer(EagerLoadingMixin, serializers.ModelSerializer): profile = serializers.SerializerMethodField() class Meta: model = Question fields = ( 'id', 'title', 'author', 'profile', 'content', ) _SELECT_RELATED_FIELDS = ['author'] _PREFETCH_RELATED_FIELDS = ['author__profile'] @staticmethod def get_profile(obj): profile = Profile.objects.get(user=obj.author) return ProfileSerializer(profile).data but that's what i get in django debug toolbar SELECT ••• FROM "accounts_profile" WHERE "accounts_profile"."user_id" = 14 LIMIT 21 10 similar queries. -
error while deploy Django app to Namecheap error in passenger_wsgi.py file
App 649063 output: File "/home/techmjiu/techpediaa/passenger_wsgi.py", line 1, in <module> App 649063 output: App 649063 output: from blog_app.wsgi import application App 649063 output: ModuleNotFoundError: No module named 'blog_app.wsgi' passenger_wsgi.py file : from blog_app.wsgi import application when i open website it show ..... We're sorry, but something went wrong. The issue has been logged for investigation. Please try again later. how to fix this -
how can in create a model for each user in Django?
i am trying to create a model for each user. and I want, the user o be able to upload a file to them model. for example the user be able to upload a file to them model fro this template: {% block content %} <form method="post" enctype="multipart/form-data"> <input type="file" id="files" name="files" multiple="multiple" /> <p class="container" style="margin-top: 10px"> <input type="submit" value="upload" class="btn btn-primary" /> </p> </form> {% endblock%} i need a sample code for form.py, model.py, views.py, -
Django + Ajax: Table header repeating after refresh
I am trying to refresh a table after an Ajax call but it isn't functioning as expected. When refreshing the table header (table id="requesttable") repeats like this: Is this due to the Django for loops I have within the template tags or is my javascript the error? I havent been able to figure out what is causing the issue. On the ajax call it is succesful and the item is adding into the table and on a browser refresh the table returns to normal with the correct data. Is it better to build in each additional entry as a row rather than refresh the table? script: $(document).on('submit','#RequestForm',function(e){ e.preventDefault(); $.ajax({ type: 'POST', url: '/request_new/' + track_id + '/', data:{ req_type:$("#req_type").val(), email:$("#email").val(), first_name:$("#first_name").val(), last_name:$("#last_name").val(), licensor:$("#licensor").val(), percentage:$("#percentage").val(), propossed_fee:$("#propossed_fee").val(), agreed_fee:$("#agreed_fee").val(), mfn:$("#mfn").prop('checked'), //template:$("#template"().val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function(){ $('#add_request').modal('hide'); $("#requesttable").load(window.location + " #requesttable"); }, }) }); HTML: <div class="container-fluid"> <div class="row">... </div> <div class="card shadow mb-4"> <div class="card-body"> {% for track in trackdata %} <div class="card"> <div class="card-header">... </div> <div class="tab-content"> <div role="tabpanel" class="tab-pane" id="stats{{track.pk}}">... </div> <div role="tabpanel" class="tab-pane active" id="details{{track.pk}}">... </div> <div role="tabpanel" class="tab-pane" id="request{{track.pk}}"> <br> <div class="container-fluid"> <div class="row"> <div class="table-responsive"> <table class="table table-hover table-borderless table-sm" id="requesttable"> <thead class="thead-dark"> <tr> <th scope="col" >Type</th> <th scope="col" … -
How to pass multiple parameters of unknown length from react to django url
I have to pass multiple parameters to a Django view through Django URL.I am passing the values from React fetch.The list of parameters is variable.For example,it could be 2 sometimes and 3 or 4 sometimes. I have following urls.py file path('getallvalues/<pk>',views.MultipleValueView.as_view()) views.py class MultipleValueView(APIView): def get(self,request,*args,**kwargs): serializer_class=ValueSerializer listoftopics=["test","test2"] return Response({"weights":getMultipleValueJourney(listoftopics)[0],"years":getMultipleValueJourney(listoftopics)[1]}) React code: fetch("http://127.0.0.1:8000/getallvalues/"+valueList) .then(response => response.json()) .then(json => { var {years,weights}=this.state; this.setState({ weights:json.weights, years:json.years, }} How could I structure my urls.py file?I have seen certain answers from stackoverflow but none of them worked in my scenario. -
Django: Track specific user actions
How can I track specific user actions with Django. For example: user logged in user changes password user visited a specific page rest api call within a specific view took 300ms user deleted / updated / created a specific model Is there a nice third party app which can do this for me and display this information in an human readable admin interface or at least in django-admin? If there is no app out there. How would you do this with Django? -
Django recieve ajax post from javascript
I want to recieve ajax from javascript to django views(below) ajax successfully posted And from views, I want to send httprequest but problem is I don't know how exactly convert recieved ajax to base64 string. I'm not used to these kind of data format Please help me audio: base64 string have to be here -
Django/Python generate and unique Gift-card-code from UUID
I'm using Django and into a my model I'm using UUID v4 as primary key. I'm using this UUID to generate a Qrcode used for a sort of giftcard. Now the customer requests to have also a giftcard code using 10 characters to have a possibility to acquire the giftcard using the Qrcode (using the current version based on the UUID) as also the possibility to inter manually the giftcard code (to digit 10 just characters). Now I need to found a way to generate this gift code. Obviously this code most be unique. I found this article where the author suggest to use the auto-generaed id (integer id) into the generate code (for example at the end of a random string). I'm not sure for this because I have only 10 characters: for long id basically I will fire some of available characters just to concatenate this unique section. For example, if my id is 609234 I will have {random-string with length 4} + 609234. And also, I don't like this solution because I think it's not very sure, It's better to have a completely random code. There is a sort regular-format from malicious user point of view. Do … -
Django Concat cannot be used in AddConstraint
I have a constraint like this CheckConstraint( check=Q(full_path__endswith=Concat(Value("/"), F("identifier"), Value("/"))) # | Q(full_path="/"), name="path_endswith_identifier_if_not_root", ), Makemigrations runs fine, but when I try to actually migrate the generated migration, I get IndexError: tuple index out of range ... File "/opt/virtual_env/mch2/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File "/opt/virtual_env/mch2/lib/python3.7/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/opt/virtual_env/mch2/lib/python3.7/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "/opt/virtual_env/mch2/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) IndexError: tuple index out of range When I ran sqlmigrations for the generated migration, I get the following error TypeError: not enough arguments for format string. Here is the full error message: ... File "/opt/virtual_env/mch2/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 345, in add_constraint self.execute(sql) File "/opt/virtual_env/mch2/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 132, in execute self.collected_sql.append((sql % tuple(map(self.quote_value, params))) + ending) TypeError: not enough arguments for format string The string that django tries to format here is: ALTER TABLE "documents_directory" ADD CONSTRAINT "path_endswith_identifier_if_not_root" CHECK (("full_path"::text LIKE '%' || REPLACE(REPLACE(REPLACE((CONCAT('/', CONCAT("documents_directory"."identifier", '/'))), E'\\', E'\\\\'), E'%', E'\\%'), E'_', E'\\_') OR "full_path" = '/')) and the tuple is empty I have tried the following things to rule out plain stupidity: Use Concat(Value("/"), F("identifier"), Value("/")) in an annotation, this works like a charm Replace Value("/") with …