Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create new AutoField using migration
From collegues I inherited multiple identical MySQL databases. Using DJANGO's inspectdb I derived the data models for it, and created a web interface to view the data. When instantiating the model structure again, DJANGO failed to create a unique_together contraint for 2 fields. Problem: I want to get rid of the existing unique_together and the 2 primary keys, as DJANGO does not support mutiple primary keys. For example with the DJANGO auto generated id field (as primary key). Is this possible, and how should I do it? Writing a custom migration would be an option, but how? Contraints Data loss is not an option, so I cannot just drop tables. Also the migration history should be maintained. What I have is: class MyModel(models.Model): sessionid = models.ForeignKey('Session', models.DO_NOTHING, db_column='sessionID', primary_key=True) datetime = models.BigIntegerField(primary_key=True) class Meta: unique_together = (('sessionid', 'datetime'),) But it should become something like: class MyModel(models.Model): sessionid = models.ForeignKey('Session', models.DO_NOTHING, db_column='sessionID') datetime = models.BigIntegerField() Any help is highly appreciated! -
Django 1.11.7 - staticfiles_dir issue
I'm developing with django first time. I have read what is : STATIC_ROOT / STATICFILES_DIR / STATIC_URL, I know what purpose for each of them. I have a problem which I keep getting 404 on browser trying to get the css files. setting.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) PROJECT_DIR = os.path.dirname(os.path.abspath(file)) STATIC_URL = '/static/' STATIC_ROOT = '%s/online_static/' % (BASE_DIR) STATICFILES_DIRS = ['%s/bootstrap/' % (PROJECT_DIR),] index.html <head> {% load staticfiles %} <meta charset="UTF-8"> <title>{% block title%}Default title{% endblock title %}</title> <meta name="description" content="{% block metadescription%}{% endblock metadescription %}"> <meta name="keywords" content="{% block metakeywords%}{% endblock metakeywords %}"> <meta name="author" content="alme7airbi9357@gmail.com"> <!-- Bootstrap core CSS --> <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" type="text/css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="{% static 'css/shop-homepage.css' %}" rel="stylesheet" type="text/css"> <!-- Bootstrap core JavaScript --> <script src="{% static 'vendor/jquery/jquery.min.js' %}"></script> <script src="{% static 'vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script> </head> what I did after setting this params I have run the python manage.py collectstatic Note : DEBUG = False -
Django's prefetch_related and select_related on more complex relationships in Admin
I have a somewhat complex relationship between multiple models. A simplified example: class Country(models.Model): name = models.CharField([...]) [...] def __ str__(self): return f'{self.name}' class Region(models.Model): country = models.ForeignKey(Country) name = models.CharField([...]) [...] def __ str__(self): return f'{self.name}' class CityManager(models.Manager): def get_queryset(self): return super().get_queryset().select_related('region', 'region__country') class City(models.Model): name = models.CharField([...]) region = models.ForeignKey(Region) objects = CityManager() def __str__(self): return f'{self.region.country} - {self.region} - {self.name}' Hence when I want to display some kind of list of cities (e.g. list all cities in Germany), I have to use select_related to be even remotely efficient otherwise I query for Country each time the __str__ is called. This is not the problem. The problem is that when I have unrelated group of models and I want to FK to City, such as: class Tour(models.Model): [...] class TourItem(models.Model): tour = models.ForeignKey(Tour) city = models.ForeignKey(City) [...] Tour would represent a planned tour for some music band; and TourItem would be a specific tour in a given city. I have a simple admin interface for this, so that TourItem is an inline field for the Tour (ie. so multiple tour items can be edited/added simultaneously). The problem is that now there are multiple queries firing for same Country … -
pycharm importable Django
This question has been asked here: Pycharm error Django is not importable in this environment However my requirement is more specific. Sadly, our repo has a copy of Django inside it for some long lost legacy versioning requirement which probably originated from the muffled gargles of a previous developer choking on her coffee being mistaken for approval of this idea. Let's say it isn't feasible for django to exist anywhere but the src folder of this project (for now) ... How can I get Pycharm to stop complaining about this every time I launch tests or anything else? The 2 seconds to close that dialog are quickly adding up. -
Is it possible to build a Case, When statement as string and run it in annotation
I am trying to dynamically build an expression and annotate it to query result. the code is: annotate_string = "Case(" for any_threshold in Threshold.objects.all(): annotate_string += "When(Possibility__lte= F('%i'),Intensity__lte= F('%i'),then=Value(F('%s'))),"\ %(Avalue,Bvalue,label) annotate_string += "default=Value(''))," and in the query I have: query.annotate( label = annotate_string ) However the error I get is: AttributeError: 'str' object has no attribute 'resolve_expression' I tried to use eval() or exec() to make string executable. P.S: You can find the question that led to this one here. -
how to create a field in django that is only enabled after filling in the previous one?
I want to enable in django admin the "registration" field only if "bond" is filled in as "outsourced". class Contato(models.Model): BOND_CHOICES = ( ('server', 'Servidor'), ('outsourced', 'Terceirizado'), ('trainee', 'Estagiário'), ) name = models.CharField(verbose_name='Nome', max_length=100) date = models.DateField(verbose_name='Data de Nascimento') email = models.CharField(verbose_name='Email', max_length=100) branchLine = models.DecimalField(verbose_name='Ramal', max_digits=4, decimal_places=0) bond = models.CharField(verbose_name='Vínculo', max_length=10, choices=BOND_CHOICES) registration = models.CharField(verbose_name='Matrícula', max_length=20) -
How to pagination the nested-relationships?
I read the django-rest-framework nested-relationships : You can see the tracks in AlbumSerializer: class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ('order', 'title', 'duration') class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True, read_only=True) class Meta: model = Album fields = ('album_name', 'artist', 'tracks') The official website do not give a method to pagination the tracks in AlbumSerializer, if the tracks count is too large, how to realize the pagination for tracks? -
Transfer pandas df to db.sqlite3 using django models
I have the following df: Year JAN FEB MAR APR MAY JUN JUL AUG SEP 0 1910 6.1 7.2 8.9 9.6 14.5 17.1 17.3 16.9 15.6 1 1911 5.8 6.5 7.5 9.7 16.2 17.8 21.7 21.4 17.3 2 1912 6.0 7.5 9.1 12.5 14.4 16.0 18.4 15.0 13.7 3 1913 6.7 7.2 8.5 10.4 13.8 16.5 17.6 18.5 16.5 I need to put it into the sqlite3 database that comes with django using the following models: from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator class Location(models.Model): LOCATIONS = ( ('EN', 'England'), ('SC', 'Scotland'), ('WA', 'Wales'), ('UK', 'United Kingdom'), ) location = models.CharField(max_length=2, choices=LOCATIONS) class Meta: verbose_name_plural = "Location" def __str__(self): return self.location class Max_temp(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE) year = models.IntegerField( default=0, validators=[MaxValueValidator(9999), MinValueValidator(0)] ) MONTH_OR_SEASON = ( ("JAN", "January"), ("FEB", "February"), ("MAR", "March"), ("APR", "April"), ("MAY", "May"), ("JUN", "June"), ("JUL", "July"), ("AUG", "August"), ("SEP", "September"), ("OCT", "October"), ("NOV", "November"), ("DEC", "December"), ("WIN", "Winter"), ("SPR", "Spring"), ("SUM", "Summer"), ("AUT", "Autumn"), ("ANN", "Annual"), ) month_or_season = models.CharField(max_length=3, choices=MONTH_OR_SEASON) class Meta: verbose_name_plural = "Maximum Temperature" def __str__(self): return self.year class Min_temp(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE) year = models.IntegerField( default=0, validators=[MaxValueValidator(9999), MinValueValidator(0)] ) MONTH_OR_SEASON = ( ("JAN", "January"), ("FEB", "February"), ("MAR", "March"), … -
How to return the Comment list by WorkOrder?
I have such a case: I have a WorkOrder class: class WorkOrder(models.Model): workorder_num = models.CharField(max_length=64, help_text="workorder number") name = models.CharField(max_length=32, help_text="name") content = models.TextField(help_text="content") And I also have a WorkOrderComment class: class WorkOrderComment(models.Model): """ comment """ workorder = models.ForeignKey(WorkOrder, help_text="belong to which order" ) comment_user = models.OneToOneField(User, help_text="comment user") content = models.CharField(max_length=256, help_text="content") So, there is a requirement, I want to list the workorder comments, so I write the serializers and views: serializer: class WorkOrderCommentSerializer(ModelSerializer): class Meta: model = WorkOrderComment fields = "__all__" view: class WorkOrderCommentListAPIView(ListAPIView): serializer_class = WorkOrderCommentSerializer permission_classes = [] queryset = WorkOrderComment.objects.filter() But if I list workorder comment, you know it will list all the comments, no organization. I want to through workorder to get its comments how to do with that? -
How is MultiValueDictKeyError and AttributeError related in Django here?
I have a function in Django that I am trying to solve from my previous question here. While trying out my own solutions, I have made significant updates but I encounter an error. I'm trying this out right now: def view_routes(request, query=None): routes = None if query is None: routes = Route.objects.all() else: #View: Routes in Queried Boundary if request.method == 'POST': return HttpResponse("OK") elif request.method == 'GET': json_feature = json.loads(request.GET.get('geo_obj', False)) #json_feature = json.loads(request.GET['geo_obj']) geom = make_geometry_from_feature(json_feature) routes = Route.objects.filter(wkb_geometry__within=geom[0]) print("Total Routes Filtered: " + str(Route.objects.filter(wkb_geometry__within=geom[0]).count())) #Render to Django View routes_json = serialize('geojson', routes, fields=('route_type', 'route_long', 'route_id', 'wkb_geometry',)) routes_geojson = json.loads(routes_json) routes_geojson.pop('crs', None) routes_geojson = json.dumps(routes_geojson) #return render(request, 'plexus/view_routes.html', {'routes':routes}) return redirect('routes_view', query) I am having trouble switching/commenting out between these two lines: json_feature = json.loads(request.GET.get('geo_obj', False)) json_feature = json.loads(request.GET['geo_obj']) Both presents an error respectively: TypeError: the JSON object must be str, not 'bool' django.utils.datastructures.MultiValueDictKeyError: "'geo_obj'" -
Django cant find pip3 installed module
I created a Python module and installed it using pip3. If i check on dist-package folder its there. If i import this module into a new Python project its ok. Problem: I would like to use this module on my Django project, but when i try to import it can't be found. Already tried: If i copy the module to site-package, it works but i don't get why i have to do this. I would like that this Python module installed with pip3 is visible for everyone without the need to copy/paste from dist folder. -
Multiple dropdown menu filter in html using Django
I am new to Django and trying to create a view where the user can have options to select the values. Can someone guide on how to proceed with it? I have attached the model for your reference, the user should be able to select the value for the BU, Team,Level, Product and Channel. Also, on selecting BU the teams should get updated and so on. Please suggest. class Master_Table(models.Model): Key_Variable=models.CharField(max_length=255,primary_key=True) BU = models.CharField(max_length=20) Team = models.CharField(max_length=20) Level = models.CharField(max_length=20) Product= models.CharField(max_length=20) Channel = models.CharField(max_length=20) -
How to change admin password of a Django application after deploying it on pivotal cloud foundry?
I have deployed a simple blog application( using tutorials and python buildpack) using Django and deployed it on Pivotal Cloud Foundry. But I am unable to log in using the same admin credentials after it is in the cloud. How can I change the admin superuser credentials? -
Python function for getting a list of the past X months
Trying to make a template tag for my Django blog archive to show the last four months of the year, ie: <a>October 2017</a> <a>September 2017</a> <a>August 2017</a> <a>July 2017</a> I'm certain that it's so simple it's stupid but I'm just not getting it! Here's what I've got so far: @register.simple_tag def last_four_months(format): today = datetime.today() four_months = today - relativedelta(months=4) for month in four_months: return four_months.strftime(format) This throws a TypeError - 'datetime.datetime' object is not iterable -
Django/Python additional parameter causes internal server error
For class Notification I have @classmethod def notify(cls, msg_or_mid, target, sender=None, types=['SYS'], **kargs): that works if called as Notification.notify( msg, employee_from_user(solicitante), chamado=self.chamado.cache_numero, previsao=DateUtils.date_to_str(self.previsao_fim) ) but causes internal server error if called with an extra parameter, 'SYS': Notification.notify( msg, employee_from_user(solicitante), chamado=self.chamado.cache_numero, previsao=DateUtils.date_to_str(self.previsao_fim), 'SYS' ) Since I am a newbie I am completely lost. Any help is much appreciated. -
django how to implement a dynamic (bootstrap) modal
I'm trying to change the interaction of a page so that additional info about a product appears in a modal rather than an element that is shown/hidden when a button is clicked. the bit I'm not sure about is making the modal adapt it's contents to each product. Previously I had the template: <div class="item price-2 col-md-4 col-12 text-center best-buy"> <div class="item-inner"> <div class="heading"> <h3 class="title"><b>Cheapest</b></h3> </div> {% include 'components/quote_summary_item.html' with quote=first_quote %} </div><!--//item-inner--> </div><!--//item--> {% include 'components/quote_detail.html' with quote=first_quote %} Where quote_summary_item.html is: <div> <div class="quotes-summary"><img src="{{ quote.ImageUrl }}" alt=""></div> <p></p> <p >......... </p> <a class="btn btn-quote-primary" href="{% url 'users:profile %}">Select</a></div> <div class="content"> <p><b>Your Quote Details</b></p> <p>{{ quote.Name }}<br/> {{ quote.Type }} <br/> ..... </p> <button class="btn btn-cta-secondary" data-id="{{ quote.priceId }}">Info</button> </div><!--//content--> and quote_detail is: <div class="quote" id="quote{{ quote.priceId }}" style="display:none"> <div > <p><b>About this quote:</b></p> {{ quote.synopsisText|safe }} </div> <div class="row"> <div class="col"> <table class="table"> <thead class="til-table-head"> <tr> <th>Information</th> </tr> </thead> <tbody> <tr> <td></td> <td>{{ quote.Something }}</td> </tr> <tr> <td>Name</td> <td>{{ quote.Name }}</td> </tr> <tr> <td></td> <td>{{ quote.payType }}</td> </tr> ....... </tbody> </table> </div> </div> </div> And the .js used was: <script type="text/javascript"> $(document).ready(function () { $('.btn-cta-secondary').click(function (e) { var id = $(e.currentTarget).data('id') $('.quote').hide() $('#quote' + id).show() }) … -
Is set a param for CharField like upload_to param for FileField possible?
I have a WorkOrderUploadFile model like bellow: class WorkOrderUploadFile(models.Model): wo_num = models.CharField(max_length="16") filepath = models.CharField(max_length=128, default="images/qiyun_admin_servicemanage_workorder/") file = models.FileField(upload_to=generate_files_directory) ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) You see, for the FileField there is a upload_to param, so I can use the generate_files_directory method to generate the file field value. Is is possible to set a method for CharField param? (because the wo_num CharField is need use a method to generate the number.) -
dynamic user form field populating with Django
I have a model: class ok(models.Model): name = models.CharField(max_length=255) project = models.CharField(max_length=255) story = models.CharField(max_length=500) depends_on = models.CharField(max_length=500, default='') rfc = models.CharField(max_length=255) I have model form. class okForm(ModelForm): class Meta: model = ok fields='__all__' I am getting first 3 fields: name, project, story from a backend api call. Now I want to populate the last two fields with respect to first three fields using AJAX call or jQuery or Javascript anything like that. I want to auto populate the last two fields from MySQL database in the front end itself before user submits the form. Kindly help. -
Create chat with WebSocket&Django, but without channels
I want to create chat with WebSocket and AJAX technologies and reconfigure Django's server to receive ws/wss protocols, but I need to do it without django-channels. I definitly don't understand channels' concepts, so I decided to work out with AJAX. I'm new to programming, so please be patient. -
filtering issue with a django template with two querysets - django
I have a dango template that I want to use to filter objects in a query sets. I have a group that I want ot add new members to. I have a list of member objects that are used to keep track of the groups members that were added when the group was created. The members were added by displaying a list of users friends with a checkbox next to their names. I now want to display a list of friends that are not already members of the group adn then add them to the group if they are selected. I am getting an issue with the html template filtering system that I have created to just show the list of friends that are not already members... can anyone help me figure this out. I have all the code below: here is the queries that were passed: # grab the group members members = Member.objects.filter(group = group).all() # grab all of the friends fo the logged in user friender = Friend.objects.filter(user = user.username).all() friended = Friend.objects.filter(friend = user).all() friends = friender | friended # the required parameters for this form parameters = { 'friends':friends, 'members':members, 'group':group, 'message':message, } return render(request, … -
Issue on Put method for creating a tracking option - Python
I want to create a tracking option ((i.e) Add tracking option) under the respective tracking category, using Xero tracking category API for my organisation. But while creating data using 'put' Requests method, it is not creating. I am using the below condition in python: response = requests.put(url=url, auth=oauth, data=xml_string) I want to know, what is the format for the data to be updated in the requests, for both content type xml/text and application/json. xml_string and url, I given is below: xml_string='<Option><Name>S11963</Name></Option>' url = 'https://api.xero.com/api.xro/2.0/TrackingCategories/{Tracking_Category}/Options' where Tracking_Category='620815a2-a7c6-4b85-8b01-ffb254ab34ad' Error: <ApiException xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\r\n <ErrorNumber>500</ErrorNumber>\r\n <Type>UnknownErrorException</Type>\r\n <Message>An error occurred in Xero. Check the API Status page http://status.developer.xero.com for current service status. Contact the API support team at api@xero.com for more assistance.</Message>\r\n</ApiException> Thanks -
Rendering/Redirecting Django in AJAX Success function
Trying my best to understand more between Django and Ajax but now I'm having a problem how to use (or what to use) between render to window.location.url in the ajax function. This is something along the lines of this similar question. To put it simply my situation is this: I'd like to pass a json to Django view so I used AJAX. "POST" Then from the url passed in AJAX it goes to view_routes view. I know that AJAX is expecting a response data so what I know is using HTTPResponse Problem: I want to pass routes (Objects) and routes_geojson (JSON) to the url where it will redirect to an HTML Page. (So I can use routes normally with {%%} tags and routes_geojson for its own purpose.) The said HTML page will also use view_routesviewif I usewindow.location.href = url`. How can I pass it from ajax? Use another ajax now with type:"GET"? Am I on the right track? Also if you have a suggested reading particulary on AJAX and Django that would be nice. :) Thank you! def view_routes(request, query=None): routes = None if query is None: routes = Route.objects.all() else: #View: Routes in Queried Boundary if request.method == 'POST': … -
Django clean password 'ValidationError' object has no attribute 'get'
I am using django-custom-user to make login with e-mail. I have 2 models CustomUser and ClientData: models.py class CustomUser(AbstractEmailUser): first_name = models.CharField(max_length=200, blank=True, null=True, default=None) last_name = models.CharField(max_length=200, blank=True, null=True, default=None) phone = models.CharField(max_length=20, blank=True, null=True, default=None) class ClientData(models.Model): user = models.OneToOneField(CustomUser) company = models.CharField(max_length=200, blank=True, null=True, default=None) bank_account = models.CharField(max_length=25, blank=True, null=True, default=None) I am trying to make a register form with both models and i have managed to do that, i have also made a clean password function, everything works, but when i purposely give 2 different password i get: 'ValidationError' object has no attribute 'get' forms.py class UserRegistrationForm(forms.ModelForm): email = forms.EmailField(required=True, max_length=150) first_name = forms.CharField(required=True, max_length=100) last_name = forms.CharField(required=True, max_length=100) password1 = forms.CharField(required=True, label='Password', max_length=100, widget=forms.PasswordInput()) password2 = forms.CharField(required=True, label='Confirm Password', max_length=100, widget=forms.PasswordInput()) phone = forms.CharField(required=True, max_length=20) class Meta: model = CustomUser fields = ['email', 'first_name', 'last_name', 'password1', 'password2', 'phone'] def clean(self): cleaned_data = super(UserRegistrationForm, self).clean() password1 = cleaned_data.get('password1') password2 = cleaned_data.get('password2') if password1 != password2: return forms.ValidationError('Password did not match.') return cleaned_data class UserDataRegistrationForm(forms.ModelForm): class Meta: model = ClientData fields = ['company', 'bank_account'] and this is the view i've made: views.py def register(request): data = dict() if request.method == 'POST': user_form = UserRegistrationForm(request.POST) data_form = UserDataRegistrationForm(request.POST) … -
How to make invisiable some item from select
I have Reporter model, and when I create News model, I have to choose reporter for this news, and I want to disappear Jimmy Olson from choose, but he must be in db, but not in choose list. how to make it? -
I want to return json response for manifest file in context processor request
I want to make a dynamic manifest file and provide on every page. For this i have to make json in manifest file dynamic. Solution which i have in my mind is to make a json response and provide through context processor.but how to pass content type in it.