Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django permissions not being added to groups
I have created a project with x apps. My aim is to create groups with permissions attached to them that populate auth tables - 'auth_groups' 'auth_permissions' and 'auth_group_permissions' on initial migration & migrate Installed apps is up to date, tried with app name,i.e "morgue' and "morgue.apps.MorgueConfig" - used terminal to check apps in apps class. database: tried in both mysql and sqlite3 Problem: I am just trying to attach the default django perms to groups. Problem is some of the groups & permissions combo works whilst others will not add permissions to group. I have 10 groups 6 will do as required four will not. ~ see my code below for how i have attempted todo this. my code: from django.contrib.auth.management import create_permissions from django.contrib.auth.models import Group, Permission from django.db import migrations class Populator(object): def populate_groups(apps, schema_editor): # Create user groups user_roles = [ "Admin only", "Morgue only", ] for name in user_roles: Group.objects.create(name=name) for app_config in apps.get_app_configs(): app_config.models_module = True create_permissions(app_config, verbosity=0) app_config.models_module = None all_perms = Permission.objects.all() - does return all permissions # morgue - 'i substituted for permission.content_type.app_label, does exist in database' morgue_perms = [i for i in all_perms if i.content_type.app_label == "morgue"] # group is created … -
Upload Image in Django with Ajax
This question is asked many times. And after long time trying I gave up. I try to upload an image to the server with an Ajax function. The Ajax function does submit quite a lot of data (I deleted the unnecessary part). The console.log gives me an empty array. What is wrong with my function? Here is the HTML: <form method="POST" id="form-create" enctype="multipart/form-data"> {% csrf_token %} <input type="file" id="myImg" name="myImg"> </form> This is the script $(document).on('submit', '#form-create', function (e) { e.preventDefault() var formData = new FormData(); formData.append('myIMG', $('#myIMG')[0]); console.log(formData) $.ajax({ type: 'POST', cache: false, url: "{% url 'creator:build' %}", data: { img:formData, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), }, success: function (data){ if (data.msg === "Success") { $('h4').html('It worked!'); } if (data.msg === 'Fail') { $('h6').html('Sorry! There was a problem...'); } }, }); }); -
React Django Stripe Button
I have a react frontend and a Django/DRF backend. I am trying to create a button on the frontend that allows users to purchase a product via stripe. The below react code works fine for purchasing item. However, it does not register the purchase under specific user, meaning that you can purchase an item, but it is not linked to any user because it does not have the token (identifying the user who is making the purchase). return ( <section> <div className='product'> <img src='https://i.imgur.com/EHyR2nP.png' alt='The cover of Stubborn Attachments' /> <div className='description'> <h3>Stubborn Attachments</h3> <h5>$20.00</h5> </div> </div> <form action={`${API_URL}/api/stripe/create-checkout-session`} method='POST' > <button className='button' type='submit'> Checkout </button> </form> </section> ); }; Here is what I tried: const Playsub = () => { const purchase_item = () => async dispatch => { if (localStorage.getItem('access')) { const config = { headers: { 'Content-Type': 'application/json', 'Authorization': `JWT ${localStorage.getItem('access')}`, 'Accept': 'application/json' } }; const body = JSON.stringify({ token: localStorage.getItem('access') }); const res = await axios.post(`${API_URL}/api/stripe/create-checkout-session`, body, config) .then((res) => { console.log(res.data) }) .catch(err => { console.log(err.response.data) }); }}}; return ( <section> <form> <button onClick={purchase_item} className='button' type='submit'> Checkout </button> </form> </section> ); }; export default Playsub; The above code when clicking on the button created gives … -
How to send a message by time in a datatimefield in DJANGO?
Hello everyone I am making a REST application based on Django Rest. I have a mailing model and fields with the start date and the end date of the mailing. I would like the newsletter to be sent by the value in the creation date field and completed in the end date field. I am a beginner, and I have no ideas about implementing such an idea. Could it be Celery? class MailingList(models.Model): start_dt = models.DateTimeField() text = models.TextField(max_length=500) operator_code = models.ForeignKey( OperatorCode, related_name='+', on_delete=models.CASCADE, ) tag = models.ForeignKey( Tag, related_name='+', on_delete=models.CASCADE, ) end_dt = models.DateTimeField() -
Adding custom table for model in django admin panel
I want to add custom table to my model. I explored this question and found out that I should change change_list_results.html like this: {% load render_table from django_tables2 %} {% render_table table %} But I got bare table without sidebhars and so on. What did I do wrong? -
With Django Websockets, how can I subscribe the current user to a new group from views.py
In Django, I have models.py with Collection and Members as a relationship to them: # models.py class Collection(models.Model): name = models.CharField(max_length=100, null=False, blank=False) class Member(models.Model): account = models.ForeignKey(User, related_name="account_set", on_delete=models.CASCADE) collection = models.ForeignKey(Collection, related_name='members', on_delete=models.CASCADE) And I have a websocket for notifying members whenever we have changes in a collection that the user is member of. For that, I have MainConsumer, shown below. # consumers.py class MainConsumer(WebsocketConsumer): def connect(self): user_id = self.scope['user_id'] collection_ids = Member.objects.filter(account_id=user_id).values_list("collection_id", flat=True) for collection_id in collection_ids: async_to_sync(self.channel_layer.group_add)(f'collection_ws_{collection_id}' , self.channel_name) self.accept() Works like a charm. I can comunicate perfectly. Question is the following: If I create a new collection, I need somehow to tell my MainConsumer that the requested user should now receive notifications from this new collection as well. # views.py class CollectionCreate(generics.CreateAPIView): permission_classes = [IsAuthenticated, ] def create(self, request, *args, **kwargs): collection = Collection.objects.create(name=request.data['name']) # Create a member as admin member = Member.objects.create( collection=collection, account=request.user, ) ** -- Here I want to 'subscribe' the current user to this new collection as well, but I cant figure out how... -- ** return JsonResponse({"payload": CollectionSerializer(collection, many=False).data }, status=200) Worth mentioning that I could "reload" my websocket in the frontend and it works, but it seems a bit … -
Connect react static files within django app dynamically to AWS S3 bucket
I have been running a django app for a long time and now I need to integrate a React app within this project. I set it up successfully, but I am struggling with correctly connecting the static files. The main problem is that when building the react project it creates a path to the CSS and the JS file which is absolute (<link href="/static/css/main.849502n.css" rel="stylesheet">). What I tried to change this path is to simply add the homepage option in the package.json file "homepage": "../../../myproject/static/reactapp". Then I copied the static files from the react app to my django-static folder by adding to the build command: react-scripts build && cp -R build/static/ ../../myapp/static/reactapp This works locally, since in development I am using the static files stored in my app. But in production I am saving my static assets in an AWS bucket. The configuration for my production looks like this: STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_DIRS = [os.path.join(BASE_DIR, "myapp/static"), os.path.join(BASE_DIR, "frontend/reactapp/build/static")] STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" COLLECTFAST_STRATEGY = "collectfast.strategies.boto3.Boto3Strategy" AWS_STATIC_LOCATION = "static" For development: STATIC_URL = "/static/" STATICFILES_DIRS = [os.path.join(BASE_DIR, "myapp/static"), os.path.join(BASE_DIR, "frontend/reactapp/build/static")] STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ) My project structure: - djangoapp - frontend - reactapp - djangoapp - static … -
Django multiple params link
I have this urls.py path('calendar/<dt:date>/', views.CertainDay.as_view(), name="classrooms"), path('calendar/<dt:date>/<int:classroom>/', views.ScheduleList.as_view(), name="schedule"), first path with one args works good with reverse func in some file how i can do this -> from .../calendar/2020-01-01 to .../calendar/2020-01-01/100 in template without using context and 2 args like url " " date arg2 something like <a href = "{% url 'schedule' *** %}> tries reverse full path with two args -
using automated testing to send text and image(outside) from exel list to whatsapp file but not sending this every contact list
Loop works when import image is not scripted pre = os.path.dirname(os.path.realpath(__file__)) f_name = 'wpcontacts.xlsx' path = os.path.join(pre, f_name) f_name = pandas.read_excel(path) count = 0 image_url = input("url here") driver = webdriver.Chrome(executable_path='D:/Old Data/Integration Files/new/chromedriver') driver.get('https://web.whatsapp.com') sleep(25) for column in f_name['Contact'].tolist(): try: driver.get('https://web.whatsapp.com/send?phone=' + str(f_name['Contact'][count]) + '&text=' + str( f_name['Messages'][0])) sent = False sleep(7) # It tries 3 times to send a message in case if there any error occurred click_btn = driver.find_element(By.XPATH, '/html/body/div[1]/div/div/div[4]/div/footer/div[1]/div/span[2]/div/div[2]/div[2]/button/span') file_path = 'amazzon.jpg' driver.find_element(By.XPATH, '//*[@id="main"]/footer/div[1]/div/span[2]/div/div[1]/div[2]/div/div/span').click() sendky = driver.find_element(By.XPATH, '//*[@id="main"]/footer/div[1]/div/span[2]/div/div[1]/div[2]/div/span/div/div/ul/li[1]/button/span') input_box = driver.find_element(By.TAG_NAME, 'input') input_box.send_keys(image_url) sleep(3) except Exception: print("Sorry message could not sent to " + str(f_name['Contact'][count])) else: sleep(3) driver.find_element(By.XPATH, '//*[@id="app"]/div/div/div[2]/div[2]/span/div/span/div/div/div[2]/div/div[2]/div[2]/div/div').click() sleep(2) print('Message sent to: ' + str(f_name['Contact'][count])) count = count + 1 output is Message sent to: 919891350373 Process finished with exit code 0 how convert this code into loop so that i can send text to every no. mentioned in exel file thanks -
django session midleware is working locally, but it doesn't on production
I'm working on a project that i don't want anyone to access my media through a direct link ex : https://www.xxx.sa/media/reports_images/report_bfc4242c.png i used session middleware and it works perfect but when it comes to the production, it doesn't here's my code class GatedContent(MiddlewareMixin): def process_request(self, request): path = request.path user = request.user disallow_user = False for gated in settings.GATED_CONTENT: if path.startswith(gated) or path.endswith(gated): report_uuid = path.split("/")[-1].split('.')[0] if gated == REPORT_IMAGE_PATH: report_image = get_object_or_404(ReportImage, uuid=report_uuid) elif gated == COMMENT_IMAGE_PATH: report_image = get_object_or_404(ReportComment, uuid=report_uuid) if user.is_staff: disallow_user = False elif report_image.report.triage: if report_image.report.triage.user == user: disallow_user = False else: disallow_user = True else: disallow_user = True break # Validate the user is an authenticated/valid user if disallow_user: raise Http404 so, what's wrong here -
Get foreign key related JSON objects in Django template
So I currently have an API response that encodes a many-to-one relationship both ways, where the one object (called Sagas) has a set of the many objects (called Arcs) relating to it: //1 Saga contains many arcs in this way: //GET Saga [ { "id": 1, "arc_set": [ 1, 2, 3, 4, 5, 6 ], "name": "East Blue", "description": "The East Blue Saga is the introductory saga of the series...", "startChapter": 1, "endChapter": 100 }, ] //GET Arc [ { "id": 2, "name": "Orange Town", "description": "Luffy and his first crew member Zoro arrive at Orange Town where....", "startChapter": 8, "endChapter": 21, "saga": 1 }, ] basically I want to be able to go through the arc_set in my django template and grab the related arcs with the matching ids. It seems simple I'm just not too familiar with the django template syntax needed Currently all I've been working on is code to loop through the arc_set array and get the id values but I can't even get that to work, never mind getting the related Arc object: {% for saga in sagas|dictsort:'id' %} {% for arc_key, arc_id in saga.arc_set.items|dictsort:'id' %} but I've been unable to iterate through the arc_set … -
Creating Class Based ListView with form that submits
I am creating a Class Based ListView that contains a Form. I was able to add the form to my template but I am not able to submit the form. The submission should redirect to the original page. Here's the code: urls.py urlpatterns = [ path('<str:uuid_group>/manage/groupmembers', ManageGroupMembersListView.as_view(), name="manage_groupmembers"), ] forms.py class ManageGroupMemberForm(forms.ModelForm): class Meta: model = AadGroupmember fields = ['id_aaduser','id_aadpermissions'] views.py class ManageGroupMembersListView(ListView): model = PermissionAAD template_name = 'permissions/group_members.html' paginate_by = 10 def get_context_data(self, *args, **kwargs): context = super(ManageGroupMembersListView, self).get_context_data(*args, **kwargs) context['uuid_group'] = self.kwargs['uuid_group'] context ['object_list'] = self.model.objects.filter(Q(uuid__icontains=context['uuid_group'])) context['form'] = ManageGroupMemberForm() return context group_members.html <form method="post" action="{%url 'manage_groupmembers' uuid_group%}"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> <table class="table"> <thead> <tr> <th scope="col">Users</th> <th scope="col">First Name</th> <th scope="col">test</th> </tr> </thead> <tbody> <tr> {% for user in object_list %} <td>{{ user.username}}</td> <td>{{ user.shortdesc}}</td> <td>{{ user.groupname}}</td> </tr> {% endfor %} </tbody> </table> -
Is it worth having social signup on my website?
I am creating a website and I've already implemented the "Sign up with Google" button and i've already added the normal user creation form. i'm considering adding the "Sign up with Facebook" button but I'm not sure if it's worth it. I couldn't find any reliable statistics online about social signup market share and I was wondering if anyone else knew. I am open to other ways of signing up as well. -
Django doesn't see model after migration
Just started to make a project, wrote code in models and decided to make migrations, after which I saw an error Operations to perform: Apply all migrations: socialaccount Running migrations: Applying socialaccount.0001_initial...Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "users_advuser" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/src/auto_store/manage.py", line 22, in <module> main() File "/usr/src/auto_store/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 290, in handle post_migrate_state = executor.migrate( File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 131, in migrate state = self._migrate_all_forwards( File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 163, in _migrate_all_forwards state = self.apply_migration( File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 251, in apply_migration migration_recorded = True File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 157, in __exit__ self.execute(sql) File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 192, in execute cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 103, in execute return super().execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers( File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers return executor(sql, params, … -
launch Django project from any folder
In my project I use config file which is one level higher than manage.py. I use ConfigParser to read it, but for Django to run correctly I need to be in the directory where manage.py is Here is the part where the magic should happen import os import configparser # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) config = configparser.ConfigParser() config.read('../config.ini', encoding='utf-8') and if i am in the right directory, everything launches correctly (.venv) kisha@LAPTOP-LLMM16ID:~/vmlist/vmlist_frontend/it$ ll total 388 drwxr-xr-x 13 kisha kisha 4096 Aug 5 16:05 ./ drwxr-xr-x 7 kisha kisha 4096 Aug 8 10:43 ../ drwxr-xr-x 6 kisha kisha 4096 Aug 5 16:05 accounts/ drwxr-xr-x 4 kisha kisha 4096 Aug 8 10:43 api/ drwxr-xr-x 7 kisha kisha 4096 Aug 5 16:05 cluster/ drwxr-xr-x 5 kisha kisha 4096 Aug 5 16:05 description/ drwxr-xr-x 6 kisha kisha 4096 Aug 8 10:43 direction/ drwxr-xr-x 5 kisha kisha 4096 Aug 5 16:05 errors/ drwxr-xr-x 5 kisha kisha 4096 Aug 5 16:05 graphs/ drwxr-xr-x 6 kisha kisha 4096 Aug 5 16:05 it/ -rw-r--r-- 1 kisha kisha 622 Jun 29 15:07 manage.py drwxr-xr-x 2 kisha kisha 4096 Aug 2 11:47 migrations/ -rw-r--r-- 1 kisha kisha 17976 Aug 8 10:36 request.log … -
sqLite3.ProgrammingError when trying to run python manage.py dumpdata
I am trying to run python manage.py dumpdata > data.json and it's giving me this error. CommandError: Unable to serialize database: 'charmap' codec can't encode characters in position 1-8: character maps to Exception ignored in: <generator object cursor_iter at 0x0000029AAC7E9E00> Traceback (most recent call last): File "C:\Users\jsalv\Desktop\ItPartsECommerce\myenv\lib\site-packages\django\db\models\sql\compiler.py", line 1876, in cursor_iter cursor.close() sqlite3.ProgrammingError: Cannot operate on a closed database. The code that is throwing the error is the following: def cursor_iter(cursor, sentinel, col_count, itersize): """ Yield blocks of rows from a cursor and ensure the cursor is closed when done. """ try: for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): yield rows if col_count is None else [r[:col_count] for r in rows] finally: cursor.close() The error comes out but the file gets generated, when it does it's never full, the last lines do not close out and because of that I cannot migrate my database to PostgreSQL, I tried saving this file with UTF-8 decode but it didn't work. Can anyone tell me if I'm doing something wrong? -
Using prefetch_related to reduce expensive query
How can i make the querying here on the database level. in my code for assigning the emails to the list i am using python code instead i want to make use of ORM querying i.e on the database level how can my query look like here. models.py class UserModel(models.Model): email = models.EmailField(unique=True, blank=True, null=True) class Mymodel(models.Model): name = models.CharField(max_length=300) assignees = models.ManyToManyField( User, related_name='tasks', blank=True, ) send_email = models.BooleanField(default=False) views.py def my_view(self): due_date = datetime.date.today() records = Mymodel.objects.filter(due_date=due_date) for rec in records: if rec.send_email: responsible_emails = [] for person in rec.assignees.all(): responsible_emails.append(person.email) -
Django detect model changes at runtime
I'm trying to generate migration files dynamically to detect changes in the model, but the issue is, makemigration command only create the migration file once and after that it says no changes detected.I tried, removing the app dynamically, and then adding it back, but that didn't work either. I have shared my code with you, any help would be appreciated, thanks. from collections import OrderedDict from django.apps import apps from django.core.management import call_command import os import shutil def add_dynamic_app(app_name, db_name='default', backwards=False): if app_name not in settings.INSTALLED_APPS: app_path = os.path.join(settings.BASE_DIR, app_name) os.mkdir(app_path) with open(os.path.join(app_path, "__init__.py"), "w") as f: f.write("") with open(os.path.join(app_path, "apps.py"), "w") as f: f.write( f""" from django.apps import AppConfig class {app_name.title()}Config(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = '{app_name}' """ ) with open(os.path.join(app_path, "models.py"), "w") as f: f.write( f""" from django.db import models class DynamicModel(models.Model): class Meta: app_label = '{app_name}' db_table = 'dynamictable' phone = models.CharField(max_length=13) name = models.CharField(max_length=50) """ ) ## Dynamic App Loading new_app_name = app_name settings.INSTALLED_APPS += (new_app_name, ) apps.app_configs = OrderedDict() apps.apps_ready = apps.models_ready = apps.loading = apps.ready = False apps.clear_cache() apps.populate(settings.INSTALLED_APPS) ## Dynamic Migration and SQL Creattion migration_name_1 = "dynamic_migration" args = ["sqlmigrate", app_name, f"0001_{migration_name_1}"] if db_name: args.extend(['--database', db_name]) if backwards: args.extend(['--backwards']) call_command("makemigrations", "--name", migration_name_1, app_name, … -
I am having issue with getting the source of streaming video with django
I had issue the video tag on chrome because I want to be able to skip to particular time on the video, google chrome does not allow that to happen because it requires a specific kind of response after doing some research I came to this post on stackoverflow after adding the code, I set the endpoint on the source tag of the video like this <source src="{% url 'namespace:stream_video' obj.video.path %}" type="video/mp4" /> even did it like this <source src="{% url 'namespace:stream_video' path=obj.video.path %}" type="video/mp4" /> But I am getting NoReversMatch 'stream_video' with arguments '('/home/UserName/Work/projectName/media/uploads/2022/8/3/b3f10ea2-b323-4398-a86c-c5fb5936cfd723.mp4',)' not found. 1 pattern(s) tried: ['video\\-stream/(?P<path>[^/]+)\\Z'] The path path("stream/<str:path>", views.stream_video, name="stream_video") And this is my view it's literally a copy of the view from the post: def stream_video(request, path): range_header = request.META.get('HTTP_RANGE', '').strip() range_match = range_re.match(range_header) size = os.path.getsize(path) content_type, encoding = mimetypes.guess_type(path) content_type = content_type or 'application/octet-stream' if range_match: first_byte, last_byte = range_match.groups() first_byte = int(first_byte) if first_byte else 0 last_byte = int(last_byte) if last_byte else size - 1 if last_byte >= size: last_byte = size - 1 length = last_byte - first_byte + 1 resp = StreamingHttpResponse(RangeFileWrapper(open(path, 'rb'), offset=first_byte, length=length), status=206, content_type=content_type) resp['Content-Length'] = str(length) resp['Content-Range'] = 'bytes %s-%s/%s' % (first_byte, last_byte, … -
How to set CustomUser’s field value inside APIView?
I have a custom user model with a tokens Integerfield and an APIView that sends a request to OpenAI’s GPT-3 API. I want to implement a feature where user has a token limit. When user has less than 0 tokens left as their user field, the GPT3 APIView will respond with a 400BADREQUEST. The GPT-3 API returns how many tokens an user has used in a single request, so I wanted to “SET” this user’s tokens field inside the APIView like the following: request.user.tokens = request.user.tokens - used_tokens # This line does not work It doesn’t give any error, but the user’s tokens field is never updated. Anyone has idea how to accomplish this? users/models.py class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = None first_name = models.CharField(max_length=100, default="unknown") last_name = models.CharField(max_length=100, default="unknown") profile_pic = models.CharField(max_length=200, default="unknown") premium = models.BooleanField(default=False) tokens = models.IntegerField(default=200) appname/views.py class GPT3(ApiPremiumMixin, APIView): def post(self, request, format=None): try: response = requests.post( url="https://api.openai.com/v1/completions", headers={ "Authorization": "Bearer " + os.getenv("GPT3_API_KEY"), "Content-Type": "application/json; charset=utf-8", }, data=json.dumps(request.data), ) used_tokens = response.json()["usage"]["total_tokens"] print(request.user.tokens) request.user.tokens = request.user.tokens - used_tokens # This line does not work print(request.user.tokens) return JsonResponse( response.content.decode("utf8"), status=status.HTTP_200_OK, safe=False ) except requests.exceptions.RequestException: Response("Request Failed", status=status.HTTP_400_BAD_REQUEST) -
Django inlines without Foreign Key
I have models: class MyModel(models.Model): name = models.CharField() group = models.ForeignKey(Group) class Group(models.Model): name = models.CharField() class City(models.Model): name = models.CharField() group = models.ForeignKey(Group) I want to get inlines (City) in the admin of MyModel for a group that includes cities: class CityInline(admin.TabularInline): model = City @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): list_display = ('pk', 'name',) inlines = [CityInline, ] How can I do this? -
django.db.utils.IntegrityError: null value in column "auto_id" of relation "university_university" violates not-null constraint
Iam getting a integrity error, i have tried adding null=True to auto id field then its working but auto_id field must not be blank=True or null=True.These models are given by my superiors i am finding this hard to understand This is the core app models.py import uuid from django.db import models from django.db.models import Max from django.utils import timezone from decimal import Decimal from django.utils.translation import gettext_lazy as _ from django.core.validators import MinValueValidator from core.utils import DictField from django.contrib.auth import get_user_model from django.contrib.humanize.templatetags.humanize import naturaltime def basedata(self, request): # Check is create if self._state.adding: self.auto_id = (self.__class__.objects.aggregate(max_auto_id=Max('auto_id')).get('max_auto_id') or 0) + 1 if request.user.is_authenticated: self.creator = request.user # If updating if request.user.is_authenticated: self.updater = request.user self.date_updated = timezone.now() class BaseModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) auto_id = models.PositiveIntegerField(db_index=True, unique=True) creator = models.ForeignKey(get_user_model(), blank=True, related_name="creator_%(class)s_objects", limit_choices_to={'is_active': True}, on_delete=models.CASCADE) updater = models.ForeignKey(get_user_model(), blank=True, related_name="updater_%(class)s_objects", limit_choices_to={'is_active': True}, on_delete=models.CASCADE) date_added = models.DateTimeField(db_index=True, auto_now_add=True) date_updated = models.DateTimeField(auto_now_add=True) is_deleted = models.BooleanField(default=False) class Meta: abstract = True def delete(self): self.is_deleted = True self.save() def delete_with_user(self, user): self.is_deleted = True user = self.user user.username = user.username + '_deleted_' + str(self.id) user.save() self.save() @property def date_added_natural(self): return naturaltime(self.date_added) class Mode(models.Model): readonly = models.BooleanField(default=False) maintenance = models.BooleanField(default=False) down = models.BooleanField(default=False) class … -
Can somebody tell me about this slash in path?
Can somebody tell me the difference between two paths? This is my urls.py in django urlpatterns = [ path('update/<int:id>/', views.update), ] urlpatterns = [ path('update/<int:id>', views.update), ] <form action="/app/update/{id}/" method="POST"> Why I should add slash(/) in the end of path? If I add / in path in urlpatterns, when I submit , it works well. If I don't, it occurs an error. -
Django + JS-Framework vs Django + native Javascript
I'm currently developing a website with a friend (Django + Django Templates with Bootstrap). It started as a learning project so we altered a lot during the development process. The project has around 30K to 40K lines of code and we tried a rather component based approach by including often used code fragments from external files with the django template language. By now, even if it started out as a learning project, we want to take it online when it's finished so it's supposed to handle mid to high web traffic in production. The question we're asking ourselves now is if it's worth migrating to a JS-Framework like Svelte or React since we'd like the website to be as fast as possible and we'd like to migrate it into a SPA. Would there be a benefit in using a framework like Svelte for realizing such goals or would this approach also be a suitable option for us? -
Multiple proxy_pass destination for multiple domain name
What I want to do is like this, Change the destination of proxy depending on domain name. However it shows the error a duplicate default server for 0.0.0.0:8090 in /etc/nginx/sites-enabled/default:7 server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; index index.html index.htm index.nginx-debian.html; server_name exmaple.com; location / { proxy_pass http://127.0.0.1:8021/; include /var/www/html/exmaple/current/uwsgi_params; } } server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; index index.html index.htm index.nginx-debian.html; server_name exmaple2.com; location / { proxy_pass http://127.0.0.1:8022/; include /var/www/html/exmaple2/current/uwsgi_params; } } I should not duplicate the server delective. However how can I use multiple proxy_pass.