Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make header urls independent?
I have urls.py urlpatterns = [ path('video/<int:video_n>', views.video_detail, name='video_detail'), ] It's ok for my url mysite.com/video/12345 I have nav bar in header video_detail.html <header> <ul> <li> <a href="mylink1">link 1</a> </li> </ul> </header> I want only links from header navbar (link 1) redirects to mysite.com/mylink1 But django engine redirects me to mysite.com/video/mylink1 How to avoid wrong redirect or make nav url independent? -
Which is the best relational dbms to use with django in web development
I am working on a web development project in django that will highly involve users doing alot of posting and searching. I am not sure which dbms to use. From your experience which is the best dbms to use. -
time out error H12 while uploading images in django-heroku
While uploading the image on Heroku I get time out error. my questions is how to increases speed of uploading ? or its really depend on internet speed. when i tried to upload image greater than 2 mb or sometimes 1.5 mb it get time out error 2020-05-29T06:00:09.372570+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=POST path="/home_page/new_post/" host=www.collegestudentworld.com request_id=201efff4-7d5e-4d6d-869e-60e1e36f317d fwd="157.33.235.68" dyno=web.1 connect=0ms service=30317ms status=503 bytes=0 protocol=http is i have to compress image before uploading? or something else please help ? i use amazon s3 for storage -
403 error when uploading javascript blob to django form
I'm generating an audio blob using javascript with the following code: function sendData(blob) { let fd = new FormData; fd.append('fname', 'test.wav'); fd.append("recording", blob); let token = '{{csrf_token}}'; $.ajax({ url: 'landing/submit/', type: 'POST', headers: { 'X-CSRFToken': token }, data: fd, cache: false, processData: false, // essential contentType: false, // essential, application/pdf doesn't work. enctype: 'multipart/form-data', }); } I am trying to send this to a django form, but i'm getting a 403 error. Here is the view it's being sent to: views.py def post_new(request): if request.method == 'POST': form = PostAudio(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('landing-home') else: form = PostAudio() return render(request, 'landing/submit.html', {'form': form}) What am I missing? Most other folks posting online say this has to do with not using CSRF tokens, but I included them in my headers. -
I made a form using html. Now I want to save that form in database and in admin panel using Django framework.What should I do?
The following code is done for form using only html. I want to extract data from user and save it in database. <form method='post' action='register'> <input type=text name="name"> <input type=text name="number"> <input type=text name="address"> <input type=submit name="value"> </form> -
How to Upload an Image to Django
I have spent over three days on this. It appears that something saved to the db, but when I try to access it in the template, I can only get the object of the db. I can not access it. I believe it was not saved successfully because I don't see a media folder where it would be saved. This is what I have so far. #settings.py STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #forms.py from .models import Pic from django import forms class ImageForm(forms.ModelForm): class Meta: model= Pic fields= ["picture"] #models.py class Pic(models.Model): picture = models.ImageField(upload_to = 'media/', default = 'media/None/no-img.jpg', null=True, blank= True) def upload(request): form = ImageForm context = {} userBio = Bio.objects.get(userData = User.objects.get(id = request.session['client']['id'])) if request.method == 'POST': # .is_valid checks the models parameters via forms method form = ImageForm(request.FILES) if form.is_valid(): form.save() print("succesful uploaded image") return redirect("/dashboard") else: print("Not a valid input from form....") messages.error(request,"Not a valid input") return redirect("/dashboard") #dashboard.html <form rule="form" class="border border--secondary" method="POST" action="/manageFile" enctype="multipart/form-data"> {% csrf_token%} <input type="file" name = "update"> <input type = "submit"> </form> {% if pictures %} {% for pic in pictures%} <img src="{{pic}}" … -
How to send data to a Django form using javascript
I have javascript data input & sending form like this: function sendData(input) { let fd = new FormData; fd.append("audioRecording", input); fetch("landing/submit/", {method:"POST", body:fd}) .then(response => response.ok) .then(res => console.log(res)) .catch(err => console.error(err)); } I am trying to send this to a django form at that url, but I get the following error: Forbidden (CSRF token missing or incorrect.): /landing/landing/submit/ How do I fix this? -
Django - models | HTML Render Issue
In the html file I am trying to render the Remove button. If I just printout out the {{combo}} it renders out. But if I try to query it based on the cart model it doesn't render the button. I also tried querying it like this {% if combo in cart.combo_item.combo.all %} but it didn't work. update-cart.html <form method="POST" action="{% url 'carts:combo_add_to_cart' %}" class="form"> {% csrf_token %} <input type="hidden" name="combo_id" value="{{ combo.id }}"> <button type="submit" class="btn btn-success">Add to Cart</button> {% if combo in cart.combo_item.all %} <button type="submit" class="btn btn-success">Remove?</button> {% endif %} </form> {{combo}} cart.models class ComboCartItem(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) combo = models.ForeignKey(Combo, blank=True, null=True, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) def __str__(self): return f"{self.quantity} of {self.combo.combo}" class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) combo_item = models.ManyToManyField(ComboCartItem, blank=True, null=True) addon_item = models.ManyToManyField(AddonCartItem, blank=True, null=True) ordered = models.BooleanField(default=False) cart_total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) objects = CartManager() def __str__(self): return str(self.id) combo.models class Combo(models.Model): title = models.CharField(max_length=120) combo_regular_price = models.DecimalField(decimal_places=2, max_digits=10, default=0.00) combo_sale_price = models.DecimalField(decimal_places=2, max_digits=10, default=0.00) timestamp = models.DateTimeField(auto_now_add=True) slug = models.SlugField(blank=True, null=True) active = models.BooleanField(default=True) objects = ComboManager() def __str__(self): return self.title views.py class ComboList(ListView): template_name = 'products/list.html' def get_context_data(self, *args, **kwargs): context = super(ComboList, … -
Conditionally do not allow a form submission
I have a template rendering 2 formsets. The user should only complete one of the 2 formsets. If the user completes both or neither of the formsets, I do not want the user to be able to submit the template form so the formsets do not clear out. Is this best handled at the template level? How should I configure my code to conditionally prevent form submission? book_add.html (template) <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div> {{ form }} </div> <div> {{ books_file.management_form }} {% for books_file_form in books_file %} <div> {{ books_file_form }} </div> {% endfor %} </div> <div> {{ books.management_form }} {% for books_form in books %} <div> {{ books_form }} </div> {% endfor %} </div> <button type="submit">Submit Books</button> </form> -
Unclear why Django url is giving 404 error
Help me. I cannot figure out why I keep getting this error when I go to http://127.0.0.1:8000/landing/submit Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/landing/submit urls.py urlpatterns = [ path('', views.home, name='landing-home'), path('landing/submit/', views.post_new, name='post_new') ] views.py def post_new(request): form = PostAudio() return render(request, 'landing/submit.html', {'form': form}) submit.html {% extends "landing/base.html" %} {% block content %} <h2>New post</h2> <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock content %} forms.py class PostAudio(forms.ModelForm): class Meta: model = audio fields = ('recording',) -
Mimicking post request on django
I have a html page that sends a POST request to another site, and it works well. <form method = "POST"> ------form datas------ </form> Now I'm trying to simulate the same POST request with only django views, utilizing request module. I've checked the POST request header I send and duplicated it into my view function, And following is how I've coded. def POST_send(request): headers = {} headers["HOST"] = "my_server_domain" headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" headers["Accept-Encoding"] = "gzip, deflate" headers["Cache-Control"] = "max-age=0" headers["Connection"] = "keep-alive" headers["Content-Type"] = "multipart/form-data; boundary=----WebKitFormBoundarypoNblPUprPs3iWxh" headers["ORIGIN"] = "http://example.com" headers["referer"] = "http://example.com/sender_view/" form_data = {} ------form dats------ response = requests.post(target_url, data=form_data, headers=headers) content = response.content I expected this to be effective just as the original form's POST request, but I only get 404 not found error code. Am I doing it wrong? -
How to combine the username in the Django db and score variable in the JavaScript?
Here I am developing the quiz using Django and JavaScript my entire logic is under the JavaScript so I need to connect the username and score to store the data into the Django Database. I have a score variable in the JavaScript . I have a username in the Django Database How to connect these two into one view and send into the Django Database. /*ajax call*/ var questions = []; $.ajax({ url: 'http://127.0.0.1:8000/api2/?format=json', type:'GET', async:true, dataType: "json", success: function(data) { questions = data ; loadQuestion(); } }); //Displaying questions var currentQuestion = 0; var score = 0; var totQuestions = 8; var AnswerOption = null; function loadQuestion() { resetColor(); enableAll(); //questionIndex = 0 var questionEl = document.getElementById("question"); var opt1 = document.getElementById("opt1"); var opt2 = document.getElementById("opt2"); var opt3 = document.getElementById("opt3"); var opt4 = document.getElementById("opt4"); questionEl.innerHTML = (currentQuestion + 1) + '. ' + questions[currentQuestion].question; opt1.innerHTML = questions[currentQuestion].option1; opt2.innerHTML = questions[currentQuestion].option2; opt3.innerHTML = questions[currentQuestion].option3; opt4.innerHTML = questions[currentQuestion].option4; if(1 == parseInt(questions[currentQuestion].answer)) AnswerOption = opt1; if(2 == parseInt(questions[currentQuestion].answer)) AnswerOption = opt2; if(3 == parseInt(questions[currentQuestion].answer)) AnswerOption = opt3; if(4 == parseInt(questions[currentQuestion].answer)) AnswerOption = opt4; } //Loading next question function loadNextQuestion() { resetColor(); enableAll(); var selectedOption = document.querySelector('input[type=radio]:checked'); if (!selectedOption) { alert('Please select your answer!'); … -
AWS Beanstalk with Django: eb create complains about unknown config setting 'StaticFile'
I'm trying to deploy a django app with Elasticbeanstalk, following this setup https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html and this https://www.1strategy.com/blog/2017/05/23/tutorial-django-elastic-beanstalk/ At the first attempt, in the .ebextension/django.config, I have option_settings: "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: "my_django_path_name.settings" PYTHONPATH: "$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: "my_django_path_name/wsgi.py" StaticFiles: "/static/=www/static/" when calling eb create, it complains about ERROR: ServiceError - Configuration validation exception: Invalid option specification (Namespace: 'aws:elasticbeanstalk:container:python', OptionName: 'StaticFiles'): Unknown configuration setting. So I took out the StaticFiles part, and eventually it becomes option_settings: "aws:elasticbeanstalk:container:python": WSGIPath: "my_django_path_name/wsgi.py" and it STILL complains about the unknown OptionName: StaticFiles Then I used the example in https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-container.html#python-namespaces with minor tweaking option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: production.settings aws:elasticbeanstalk:container:python: WSGIPath: ebdjango.wsgi:application NumProcesses: 3 NumThreads: 20 yet it STILL complains about the same thing. I don't know where the StaticFiles option name is being read. It doesn't exist in the .config file. Is it cached somewhere or something? -
django.db.utils.IntegrityError: NOT NULL constraint failed: new__score_comment.post_id
I was working on a comment section for post and was getting a django.db.utils.IntegrityError: NOT NULL constraint failed: new__score_comment.post_id so I added null=True, blank=True to the post and user in the models.py class comment and proceeded with the comments addition section but now when I am trying to link users and posts to the comment I am getting the same error Here is the Models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) # reply = models.ForeignKey('Comment', null=True, related_name="replies") content = models.TextField(max_length=160) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return '{}-{}'.format(self.post.title, str(self.user.username)) Here is the views.py: class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter(post=post).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') comment = Comment.objects.create( post=post, user=request.user, content=content) comment.save() return HttpResponseRedirect("post_detail.html") else: comment_form = CommentForm() context["total_likes"] = total_likes context["liked"] = liked context["comments"] = comments context["comment_form"] = comment_form return context class PostCommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = ['content', ] success_url = reverse_lazy('score:post-detail') def post(self, request, *args, **kwargs): form = CommentForm(request.POST) if form.is_valid(): post = form.save() post.save() print(args, kwargs, … -
Django - IntegrityError at / FOREIGN KEY constraint failed
I am new to Django. Getting the below error when i try to submit and save multiple forms. Though i dont have foreign key relationships in my models. Error message- IntegrityError at / FOREIGN KEY constraint failed Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 3.0.6 Exception Type: IntegrityError Exception Value: FOREIGN KEY constraint failed Exception Location: C:\Users\mrudu\PycharmProjects\WEBPROJECT\venv\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 396 The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception: C:\Users\mrudu\PycharmProjects\WEBPROJECT\venv\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) ▼ Local vars Variable Value exc IntegrityError('FOREIGN KEY constraint failed') get_response > request Models.py- from django.db import models from django import forms from multiselectfield import MultiSelectField class PatientBasicInfo(models.Model): first_name = models.CharField(max_length=200) # help_text='Enter your Firstname') last_name = models.CharField(max_length=200) # help_text='Enter your Lastname') email = models.EmailField(max_length=100) GENDER_CHOICES = (('M', 'Male'), ('F', 'Female'),) gender = models.CharField(max_length=6, choices=GENDER_CHOICES, default=False) age = models.PositiveIntegerField(default=False, null=True, blank=False) #date_of_birth = models.DateField('DOB', null=True, blank=False) height = models.FloatField(null=True) weight = models.FloatField(null=True) bmi = models.FloatField(null=True) ETHNICITY_CHOICES = ( ('indian', 'INDIAN'), ('asian', 'ASIAN'), ('american', 'AMERICAN'), ('latin', 'LATIN'), ('european', 'EUROPEAN'), ('australian', 'AUSTRALIAN'), ('others', 'OTHERS'), ) ethnicity = models.CharField(max_length=15, choices=ETHNICITY_CHOICES, default=False, blank=False) def __str__(self): return self.first_name def save(self, *args, **kwargs): self.bmi = round((self.weight / self.height**2), 2) super(PatientBasicInfo, self).save(*args, **kwargs) class … -
Wagtail Error Creating Custom User Unknown field(s) (is_active) specified for User
I was creating a custom user for my application but I got the following error when i make migrations (in a new db) from wagtail.admin import urls as wagtailadmin_urls File "/opt/miniconda3/envs/nefoenv/lib/python3.7/site-packages/wagtail/admin/urls/__init__.py", line 13, in <module> from wagtail.admin.urls import password_reset as wagtailadmin_password_reset_urls File "/opt/miniconda3/envs/nefoenv/lib/python3.7/site-packages/wagtail/admin/urls/password_reset.py", line 3, in <module> from wagtail.admin.views import account File "/opt/miniconda3/envs/nefoenv/lib/python3.7/site-packages/wagtail/admin/views/account.py", line 16, in <module> from wagtail.users.forms import ( File "/opt/miniconda3/envs/nefoenv/lib/python3.7/site-packages/wagtail/users/forms.py", line 188, in <module> class UserEditForm(UserForm): File "/opt/miniconda3/envs/nefoenv/lib/python3.7/site-packages/django/forms/models.py", line 267, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (is_active) specified for User My idea is to create a personalized user with email and unique username, and take care, all these required fields and that like the wagtail admin also in django update and creation forms are updated models.py from django.db import models from django_countries.fields import CountryField from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class UserManager(BaseUserManager): def create_user( self, email, username, country, password=None ): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') if not country: raise ValueError('Users must have country') user = self.model( email=self.normalize_email(email), username=username, country=country ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, country, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, … -
multi tenant django Headache
Headache with tenant... I made a multi-tenant app in django using postgres db and react in frontend, everything flows well until I came across this issue.... tenant 1 =company1.mydomain.com,tenant2= tenant2.mydomain.com.. the problem is when the user enters mydomain.com and enters their credentials. What should I do to find the tenant that belongs to? each tenant has its own user tables and their own roles... I need that when the user enters the login gets the tenant to which it belongs, what idea they can give me, thank you anticipated... -
What models and fields do I need to handle subscriptions such as Apple's Autorenewable Subscriptions?
I want to build an autorenewable subscription service, with an introductory trial period. There doesn't seem to be much written documentation on what models and fields I need to best model (and futureproof) my subscriptions. I'm starting with Apple's App store right now, but I do have a web interface and want to go to the Play Store at some point. From this video: https://developer.apple.com/videos/play/wwdc2018/705/ it seems like the minimum I need is something like a Subscription model with fields userId, productId, originalTransactionId, latestExpiresDate, consumedProductId, latestReceiptData. Is there anything else I need? Will I be able to retrieve other subscription information in the future (i.e. the billingRetry information as suggested in the video for grace periods; my understanding is by sending the saved receipt data I can get the JSON blob again and retrieve additional fields if I need to)? How will I extend this to co-exist with web and Play Store subscriptions? -
When is it required to use `schema_editor.connection.alias` in a django `migrations.RunPython` method?
When is it required to use schema_editor.connection.alias in a migrations.RunPython method and why? When using RunPython in a data migration, django advises that you should use schema_editor.connection.alias: from django.db import migrations def forwards_func(apps, schema_editor): # We get the model from the versioned app registry; # if we directly import it, it'll be the wrong version Country = apps.get_model("myapp", "Country") db_alias = schema_editor.connection.alias Country.objects.using(db_alias).bulk_create([ Country(name="USA", code="us"), Country(name="France", code="fr"), ]) class Migration(migrations.Migration): dependencies = [] operations = [ migrations.RunPython(forwards_func, reverse_func), ] Warning RunPython does not magically alter the connection of the models for you; any model methods you call will go to the default database unless you give them the current database alias (available from schema_editor.connection.alias, where schema_editor is the second argument to your function).* But the docs section that describes data migrations, it doesn't mention the alias at all: from django.db import migrations def combine_names(apps, schema_editor): # We can't import the Person model directly as it may be a newer # version than this migration expects. We use the historical version. Person = apps.get_model('yourappname', 'Person') for person in Person.objects.all(): person.name = '%s %s' % (person.first_name, person.last_name) person.save() class Migration(migrations.Migration): dependencies = [ ('yourappname', '0001_initial'), ] operations = [ migrations.RunPython(combine_names), ] -
Django how to optimize handling of large data?
I am working on a website where I want to populate product data from an external API. This api has hundreds of products data, and each product has dozens of variants. Each product and data have their images which I'm using Django's ImageField from models to store locally in Postgresql. Now the problem is that there are well over 15000 images, and it is taking forever to do populate the images data. Here is the structure of API: { ... Single Product Image: ... { Product Variant1: ..., [images] } { Product Variant2: ..., [images] } { Product Variant3: ..., [images] } } Each product has somewhere from 10-50 variations. Here is what I have done. For variation images, I'm using a many-to-one relationship table to store all the images of each variant: models.py: class ProductsVariation(models.Model): .... class VariationImages(models.Model): prd_id = models.ForeignKey(ProductsVariation, on_delete=models.CASCADE) img = models.ImageField( upload_to=settings.MEDIA_ROOT + 'product_variation') get_products.py: from msilib.schema import File from tempfile import NamedTemporaryFile from pip._vendor import requests for product in api_data: #Loop over main product ... main_product_request = requests.get(product['IMAGE_NAME']) main_img_temp = NamedTemporaryFile(delete=True) main_img_temp.write(main_product_request.content) main_img_temp.flush() main_product.prd_img.save(product['GENERIC_NAME'] + ".jpg", File(main_img_temp), save=True) main_product.save() # Populate this product's variants for variants in product['Product']: # Loop through each variant of … -
Custom Permissions in Django Rest Framework
I have this get View that I want to check IsOwner Permission. Permission Class class IsOwnerVendor(permissions.BasePermission): def has_object_permission(self, request, view, obj): print(f"Vendor Email:{obj.vendor_id.email}") print(f"Loggon user:{obj.vendor_id.email}" ) return obj.vendor_id.email == request.user this is my object Model class Menu(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=500) price = models.FloatField() quantity = models.IntegerField(default=1) menu_cat = models.CharField(choices=MENU_CAT, max_length=5) date_created = models.DateTimeField(auto_now_add=True) last_edited = models.DateTimeField(auto_now=True) vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE) is_recurring = models.BooleanField(default=False) recurring_freq = models.IntegerField(default=1) and this is my view class MenuDetailView(generics.GenericAPIView): permission_classes = [IsOwnerVendor | IsOwnerVendor] def get_serializer_class(self): if self.request.method == 'PUT': return MenuUpdateSerializer elif self.request.method == 'GET': return MenuListSerializer else: return MenuListSerializer def get_object(self, pk): try: obj = Menu.objects.get(pk=pk, ) self.check_object_permissions(self.request, obj) return obj except Menu.DoesNotExist: raise Http404 @method_permission_classes((IsOwnerVendor,)) def get(self, request, pk, format=None): my_menu = self.get_object(pk=pk) menu_serializer = MenuListSerializer(my_menu) return Response(menu_serializer.data, status=status.HTTP_200_OK) When I try to access the view, I always get the error below { "detail": "You do not have permission to perform this action." } I have read the DRF doc and I still cannot pinpoint where my issue lies. I also printed the Permission checkers on the console and saw that it was supposed to return true. -
Can I filter options automatically on the Django Admin "add" page?
Consider a Word-A-Day Django webapp that presents the user with a vocabulary word each day, with the difficulty of the word increasing from "common" on Monday to "obscure" on Friday. The models in models.py look like this: class WordADay(models.Model): """A vocabulary word and its assigned day""" date = models.DateField( help_text="The date to post the selected word" ) word = models.ForeignKey( Words, help_text="The selected vocabulary word" ) class Word(models.Model): """Vocabulary words""" OBSCURITY_CHOICES = [(1,'Monday'), (2,'Tuesday'), (3,'Wednesday'), (4,'Thursday'), (5,'Friday')] word = models.CharField( max_length=32, help_text="A vocabulary word" ) difficulty = models.PositiveSmallIntegerField( choices=OBSCURITY_CHOICES, help_text="How obscure the word is" ) On the Admin "add" page for the WordADay model, I want to be able to first select a day from the standard calendar selector for the 'date' field. Once selected, I'd like the options in the drop-down selector for the 'word' field to be automatically filtered to only those instances of the Word model that have the correct difficulty, with "1" corresponding to a Monday date and "5" corresponding to a Friday date. That is, I'd like to filter Foreign Key options according to the value selected for a different field. For the sake of discussion, I can provide a skeleton admin.py from django.contrib import … -
Advice on User License Data Model and Integrating Django Permissions
I'm looking for some advice/feedback on a conceptual data model used in a Django web application that requires all users who signup have an available license for their email domain as I don't have much experience with data modeling. I'm also seeking advice on implementing and integrating some sort of permissions system where users who register under a certain license have limited access to certain features in the application. For a bit more context I'll provide a signup scenario. On my end, I've created an Organization (Example Org) along side a License (Example Org License) as well as two Domain Licenses (one with the domain example.org and another with sub.example.org) each with 1 allocated and available licenses. If Alice from Example Org registers with her company email alice@example.org and we have allocated a license for that domain, then Alice will have successfully signed up and the number of available licenses for that domain license will be 0. If Bob (also from Example Org) has an email bob@sub.example.org, and we have allocated enough licenses for Example Org for that domain, then Bob also successfully signs up and the available licenses for that domain license becomes 0. I've attached an image of … -
Trying to test re_path regular expressions in django
I am trying to write a test for a re_path url and I cannot figure it out. Below is my code so far. Please forgive the Puserid and Pcomment_comment_of_the_day. I did not know how escape the less than symbol. urls.py file: from django.urls import path, re_path from . import views urlpatterns = [ re_path(r'trophy/(?Puserid>\w+)/(?Pcomment_of_the_day>\w+)/$', views.commentoftheday, name='commentoftheday'), ] tests.py file: from django.test import TestCase, Client from django.urls import reverse class helpme(TestCase): def test1(self): response = self.client.get(reverse("commentoftheday"), kwargs={'userid':'bleh'}) response.status_code -
My upload function works locally but not on my server django
I have an upload function that runs good locally but it does not function when it is deployed. Any advice? class UploadModel(models.Model): owner = models.ForeignKey(User, related_name="upload_models", on_delete=models.CASCADE) cord_y = models.IntegerField() cord_x = models.IntegerField() model = models.FileField(upload_to='standard//', validators=[validate_file_extension]) title = models.CharField(max_length=30) def __str__(self): return self.title def upload(request): if request.method == "POST": form = UploadModelForm(request.POST, request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.owner = request.user obj.save() os.rename(BASE_DIR+'//media//'+str(obj.model),\ os.path.join(BASE_DIR, 'media\\standard\\SaveFile'+str(obj.id)+'.z2s')) else: form =UploadModelForm() return render(request, "upload/upload.html", {"form": form})