Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Calling a view function with AJAX not working when current path has sub directory or url parameter (Django)
I am using AJAX to call a view function when my pages load to return a count value (no. of items in basket). This works fine for most of my url paths but when the current path has a sub directory or url parameter value I get a 404 error. Below are a some of my url patterns. The bottom one is the view function I call to return the count value. When I visit the 'orders' path the basket count is returned successfully but for the 'order_history' and 'view_order' paths I get the 404, e.g. 'Not Found: /view_order/basket_count' path("my_orders", views.orders, name="orders"), path("my_orders/history", views.order_history, name="order_history"), path("view_order/<int:id>", views.view_order, name="view_order"), path("basket_count", views.basket_count, name="basket_count"), Very new to Python/Django so I'm sure I'm not grasping something very fundamental here and the url patterns are not resolving correctly. I previously had the basket_count in another file called utils.py and referenced it with utils.basket_count which gives the same outcome. I suppose I could just call the function within each of my views but my intention here was to experiment with AJAX. Is there a simple change to my url patterns that will fix this issue with my current setup or is it simply bad practice? -
In Django, can you create a permission that is not based on a model?
I tried creating a permissions with: Permission.objects.create( codename='my_domains.delete_domain', name='Can Delete domains', ) I get this error: django.db.utils.IntegrityError: NOT NULL constraint failed: auth_permission.content_type_id It looks as though content_type is a required field. I do not a model in my app as the app calls an external service. How can I still add this customer permission, without a linked model? -
Why use flywaydb in django?
I am developing a django project. Recently, the project manager and devops decided to switch from django migrations to flywaydb (https://flywaydb.org/). This is explained by the fact that flyway has migration in one place and versioning. I looked at the flyway, but I did not see any conceptual difference with the django migrations. The same approach, only on pure sql. Plus, we lose the additional features of django migrations (auto-generation of migrations, etc.) Can someone explain what is the advantage of flyway? I did not find any good articles. -
Django: Cannot delete broken PolymorphicModel instance
I have this model setup in a Django project (hosted on Heroku) where I am using django-polymorphic: class Product(PolymorphicModel): ... class Book(Product): ... The problem is, that I have managed to create a corrupted instance of both a Product and a Book. This happened when I had an instance of Product which I wanted to convert to an instance of Book and in a moment of insanity did a stupid thing like this: > p <Product: SomeTitle> > b = Book() > b.__dict__ = p.__dict__ > b.save() Now, I know this was idiotic and it threw all kinds of errors. My problem is, that now I am stuck with an instance p which I cannot delete. When calling p.delete() I get the following error: TypeError Traceback (most recent call last) <ipython-input-3-6a6f0dca8e5f> in <module>() ----> 1 p.delete() ~/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py in delete(self, using, keep_parents) 971 972 collector = Collector(using=using) --> 973 collector.collect([self], keep_parents=keep_parents) 974 return collector.delete() 975 ~/.heroku/python/lib/python3.6/site-packages/django/db/models/deletion.py in collect(self, objs, source, nullable, collect_related, source_attr, reverse_dependency, keep_parents) 220 if self.can_fast_delete(sub_objs, from_field=field): 221 self.fast_deletes.append(sub_objs) --> 222 elif sub_objs: 223 field.remote_field.on_delete(self, field, sub_objs, self.using) 224 for field in model._meta.private_fields: ~/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py in __bool__(self) 252 253 def __bool__(self): --> 254 self._fetch_all() 255 return bool(self._result_cache) 256 ~/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py in … -
Configuring HTTPS proxy in anaconda
Hello guys I have created an app using anaconda and django. How can I run my app on https. Is it possible to create a proxy ? -
How does Django models interact with non-Django files
I am new to Django and am learning by doing. My original web app only used a view.py,base.html and another non-Django python file es.py to connect to a NoSQL database(Elasticsearch) to search over index B. I do most of the front-end in base.html. The app now need to have some dependent drop down based on fields in index A and then enable search over index B filtered by the selected value. So the values need to be somewhat "global". I was trying to create select/drop down but it seems Django does not support them in .html. I searched and found it seems that I have to use models.py. I read some examples and can't find how models.py interact with non-Django python files. Is there an example that illustrates this? What's the easiest way to enable the structure for the project? Thanks. -
my Database is not showing on admin panel
models.py from django.db import models class complain(models.Model): name = models.CharField('Name', max_length=120) Email = models.CharField(max_length=120) message = models.CharField(max_length = 600) def __str__(self): return self.name views.py def contact(request): if request.method == 'GET': form = ComplainForm() else: form = ComplainForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['Email'] message = form.cleaned_data['message'] try: send_mail(name, message, email, ['ankushbanik123@gmail.com']) # change this to your email except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('/success') return render(request, "tem/home.html", {'form': form}) """You need a success view for when the form has been submitted. This will render the thank you message once the user has submitted the form. Then on the urls.py, import successView then add path('success', successView, name='success'),""" def successView(request): return render(request, "tem/success.html") form.py class ComplainForm(forms.ModelForm): class Meta: model = complain fields = ['name', 'Email', 'message',] def clean_email(self): email = self.cleaned_data.get('email') return email admin.py from django.contrib import admin Register your models here. from .models import complain admin.site.register(complain) class complainAdmin(admin.ModelAdmin): list_display = ('name', 'Email', 'message') admin.site.register(complain, complainAdmin) -
AWS returns error when generating prepopulated pdf file
I am prepopulating pdf fields with fields from an online form using fdfgen. Locally it works perfectly. It sends an email with the new pdf generated. When deploying to AWS it throws an error AttributeError: 'str' object has no attribute 'status_code' -
How can i add my django project as chrome extension?
I developed a text editor for Bengali language using django framework. Now i want to add my project in chrome extension. I didn't get any proper guidance how can it will be added in chrome extension. -
Overriding js file for FilteredSelectMultiple widget
I am sorry if this a basic question, but I am new to django and could not find any new info about it. I have implemented FilteredSelectMultiple widget to my user form. Now I would like to make some minor changes to widget itself (make translations, edit tooltips etc.). To do so, I copied and edited original js file. Now I would like to override original file with edited one. For this file I created js directory in static. But then I am trying to add it in my Media class loaded widget remains unchanged. How should I do it correctly? My code in forms.url class DrgSkaiciuokle(forms.Form): bazine_kaina = forms.DecimalField(max_digits=5, decimal_places=2, required=True, label="Bazinė kaina", initial= BazineKaina.objects.get(), def clean_bazine_kaina(self): bazine_kaina = self.cleaned_data['bazine_kaina'] return bazine_kaina drg_pasirinkimas = forms.ModelMultipleChoiceField(queryset=DRGkodas.objects.all(), label="Pasirinkite atvejį sudarančius DRG", widget=FilteredSelectMultiple("DRG kodai", is_stacked=False), required=True) class Media: css = { 'all': ('/static/css/widgets.css',), } js = ( '/static/js/SelectFilter2.js', ) def clean_drg_pasirinkimas(self): drg_pasirinkimas = self.cleaned_data['drg_pasirinkimas'] return drg_pasirinkimas -
django internationalization error with msgmerge
PS C:\Users\Ultrathon\Documents\WorkSpace\Edu_Dr_Dayang\venv_Dayang\3IN> python .\manage.py makemessages --l en processing locale en CommandError: errors happened while running msgmerge msgmerge: unrecognized option --previous' Try(null) --help' for more information. -
Show the result of execution Celery task through api by
I get several website addresses in turn from POST request. I will get the job ID. The task collects the number of any HTML-tags. Next, through api, y ou need to display the result by the task number. How to implement saving results from tasks? I will use this code to count HTML-tags(): @app.task(serializer='json') def demo(request, some_url): if request.method=="POST" page = requests.get(some_url) tree = html.fromstring(page.content) all_elms = tree.cssselect('*') all_tags = [x.tag for x in all_elms] c = Counter(all_tags) """for e in c: #print('{}: {}'.format(e, c[e]))""" return с P.S Code is optional, I have enough links on my topic or ideas! -
Django mail sends sensitive information
Django email sends my settings.py file information to the recipient list. i am tried AdminEmailHandler 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' } 'app': { 'handlers': ['console', 'logfile'], 'level': 'DEBUG', }, -
Exclude models based on a value from another model with no foreign key
I have the following schema class Review(models.Model): comment_id = models.CharField(max_length=32) class Comment(models.Model): comment_id = models.CharField(max_enght=32) uploaded = models.DateTimeField() NOTE 1 there is no Foreign Key beside the fact that Review and Comment models have exactly the same comment_id NOTE 2 there is one-one/unique relation (only one occurrence of the comment_id will exists at each table) I want to make a select query to fetch all the Review models that their relative Comment model IS NOT OLDER than 10 days. -
django-storges support for CloudFront signed URL
I want to use CloudFront's signed URLs rather than plain unsigned URLs. django-storages gives the option of AWS_S3_CUSTOM_DOMAIN but then it generates unsigned URLs from CloudFront's subdomain. By default AWS_QUERYSTRING_AUTH is True and it does generate signed URLs for S3. Any way to generate signed URLs for CloudFront. This is the setting I am looking to turn on, but due to unsigned URLs I disabled it. Settings I am looking to turn on for My distribution -
Getting this name error whilst using django-taggit: name 'Tag' is not defined
For my website, I want users to be able to add tags to their posts. But I get this error: python name 'Tag' is not defined Here is some code Relevant code in models.py from taggit.managers import TaggableManager class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=75) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) image = models.ImageField(upload_to='post_images',blank=True,null=True) published_date = models.DateTimeField(blank=True,null=True,auto_now_add=True) NSFW = models.BooleanField(default=False) spoiler = models.BooleanField(default=False) tags = TaggableManager() def __str__(self): return self.title def save(self, *args, **kwargs): super().save(*args, **kwargs) Here is the relevant code in views.py class TagMixin(object): def get_context_data(self,**kwargs): context = super(TagMixin,self).get_context_data(**kwargs) context['tags'] = Tag.objects.all() return context class PostListView(TagMixin,ListView): template_name = 'mainapp/post_list.html' model = Post context_object_name = 'posts' queryset = Post.objects.all() def get_queryset(self): return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') class TagIndexView(TagMixin,ListView): template_name = 'mainapp/post_list.html' context_object_name = 'posts' model = Post def get_queryset(self): return Posts.objects.filter(tags__slug=self.kwargs.get('slug')) And here is the form. class PostForm(forms.ModelForm): class Meta(): model = Post fields = ['title','text','image','tags','spoiler','NSFW'] widgets = { 'title':forms.TextInput(attrs={'class':'textinputclass'}), 'text':forms.Textarea(attrs={'class':'textareaclass editable'}), } def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['image'].required = False I am getting the error in the Mixin, on this line python context['tags'] = Tag.objects.all() Can anyone tell me why I am getting an error of python name 'Tag' is not defined So far I have changed the … -
Access JavaScript variable from Django template
I have an HTML combobox which needs to be dynamically constructed upon page loading, and I need to do something like this: <select id='sort-combobox'> <option value='1' {% if sesionStorage.getItem('sortFilter') == 1 %} selected {% endif %}>Newest</option> <option value='2' {% if sesionStorage.getItem('sortFilter') == 2 %} selected {% endif %}>>Price ASC</option> <option value='3' {% if sesionStorage.getItem('sortFilter') == 3 %} selected {% endif %}>Price DESC</option> </select> How can I access sessionStorage.getItem('sortFilter') from Django template? -
Django model for seat booking
I am trying to design Django model for booking website. Anyone can book any seats My Logic is simple, if a seat booked already, it can't be booked later, user can unbook. i stuck here: from django.db import models from enum import Enum class Seat(Enum): AA = 1 AB = 2 BA = 3 BB = 4 CA = 5 CB = 6 class Hall(models.Model): """ there 6 seats in a hall """ seat = models.CharField(choices=Seat, max_length=2) class Booking(models.Model): I hope you got my problem. I can handle in frontend like, all the 6 seats will be presented, if user click on a seart, it will be booked and if they clicked on booked seat, it will be unbooked, this is not a big deal to handle. My problem is only backend, i am stuck in writing the models like if a seats booked already, it cant be booked again but it can be unbooked only Can anyone please help me to write this models? -
Sign in required when accessing gcloud API
I am building an app that uses the dialogflow API, and I am having the following issue, the API requires my Gcloud user credentials (login and password) when calling a specific method Which is weird because, I am using the same API to have different kind of data and I don't need to enter my user credentials for other requests. def get_training_phrases(project_id, intent_id): client = dialogflow.IntentsClient() intent = client.get_intent("projects/agent-mikael-gtjdma/agent/intents/{}".format(intent_id), intent_view=dialogflow.enums.IntentView.INTENT_VIEW_FULL) new_intent = json.loads(MessageToJson(intent)) intent_name = new_intent['displayName'] training_phrases = [] for training_phrases_part in new_intent['trainingPhrases']: txt = training_phrases_part['parts'][0]['text'] training_phrases.append(txt) print(training_phrases) return training_phrases, intent_name ```settings.py MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage' PROJECT_DIR = BASE_DIR.replace(str(Path('server/django/Assistant_configuration')), '') os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = PROJECT_DIR + str(Path('/agent-mikael-gtjdma-b21243f72b48.json')) I need to enter once my user credentials and the login is not longer required dring the whole session. -
File, Folder and Directory traversing of linux folers in Django and display in HTML
I am beginner in django and want to display linux server files and folders in html and want to traverse and come back to previous location when a 'back' button is clicked. Can anyone help me out with this? -
Bootstrap table - numbers in accounting format
How can I write numbers in a cell inside Bootstrap table in accounting format? For example: one million should be shown as 1,000,000 and not 1000000 (notice commas ',' between digits). Please note that data data is getting filled by Django app. Example: <tbody> {% for row in tbl_list %} <tr id="port_row_{{row.stock}}_{{index}}"> {% if row.stock == 'TOTAL'%} <td> {{row.stock}}</td> {% else %} <td> <a target="_blank" style="color:blue;" href="https://www.google.com/finance?q=NSE:{{ row.stock }}">{{row.stock}}</a></td> {% endif %} <td>{{row.name}}</td> <td>{{row.investment_amount}}</td> <td> {% if row.weekly_gain >= 0 %} <div style="color:green"> +{{row.weekly_gain}} <i class="fa fa-arrow-up"></i> </div> {% else %} <div style="color:tomato"> {{row.weekly_gain}} <i class="fa fa-arrow-down"></i> </div> {% endif %} </td> <td>{{row.percentage}}</td> <td>{{row.percentage_of_portfolio}}</td> </tr> {% endfor %} </tbody> -
How to pass # in url as a parameter in django 2
I am trying to pass a code "Req-2019#000001" Django URL. I want to pass this code as well as normal string and number also in URL as arguments. path('generateBomForSingleProduct/<requisition_no>/' , views.generateBomForSingleProduct, name='generateBomForSingleProduct'), Its work properly but the problem is its add extra / before # My URL is now this http://127.0.0.1:8000/production/generateBomForSingleProduct/Req-2019/#000001 But I want to like this http://127.0.0.1:8000/production/generateBomForSingleProduct/Req-2019#000001 Not an extra "/" before my "#" -
Whats the best rest pattern for tradeable items in django?
I want to create a website where users can buy virtual items with virtual money. I would also like to use django_restframework with a proper design pattern. The Items should be able to be created for money under certain circumstances, bought and sold (in effect switch users) and liquidated (destroyed for money). So in total the owner can create, sell, buy and destroy his items. Since in essence rest is supposed to create, post,put, patch and delete objects, how can I most elegantly feat the these four features into this pattern? Do I just allow the user to create and delete objects and override the ModelViewSet methods accordingly? Do I create 4 different post views that execute these operations? Do I allow the User to set the new owner of an item in a post request? Whats the most elegant solution here? -
How to submit post/put request to Django rest API via React front end?
I'm new to Django, this is hopefully an easy question for the advanced users. I'm trying to submit a post/put request to a nested object in Django rest API using a React form (front end). Below is how the nested object looks like, the table is called person. It's joins to the address table to get information such as street, suburb etc.. { "id": 3, "last_name": "Kidd", "first_name": "Jason", "address": [ { "id": 5, "street": "13 Sunrise Road", "suburb": "Greenhithe", "town": "Christchurch", "postcode": "2234", "address_type": "w" } ], "group": "Customer" } I used a package called drf_writable_nested to write to the nested object. This is the code for person serializer. from drf_writable_nested import WritableNestedModelSerializer class PersonSerializer(WritableNestedModelSerializer): last_name = serializers.CharField(required=True, max_length=100) first_name = serializers.CharField(required=True, max_length=100) address = AddressSerializer(many=True) class Meta: model = Person fields = ('id', 'last_name', 'first_name', 'address', 'group') Below is the front end code for handling the submit request, such pattern works fine if the object it submits to is flat (not nested). class ClientForm extends React.Component { handleFormSubmit = (event, requestType, id) => { event.preventDefault(); const last_name = event.target.elements.last_name.value; const first_name = event.target.elements.first_name.value; console.log(last_name, first_name); switch ( requestType ) { case 'post': return axios.post('http://127.0.0.1:8000/api/person/', { last_name: last_name, first_name: … -
Is there a way to register new users with Django registration templates that would prevent them from logging in until admin has manually reviewed?
I'm working on login/registration views in Django in a project that requires that the admin manually reviews the application before the user can actually login...while saving the information they provided at the registration page. In the past I didn't have projects that required the users be reviewed manually by the admins. def register(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): new_user = form.save() login(request, new_user) return index(request) else: form = UserCreationForm() return render(request, "registration/register.html", {"form": form}) This is what I would normally write...but even if I don't include the login(request, new_user), the new_user would be able to do so himself after the new_user is created... I need to make sure they still can't login until the admin has manually reviewed his application to join.