Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
moving back to web pages after logout is callled
at login, the key to the department is stored in secession and is redirected to the desired department of the user in login_validation check = models.user.authenticate(password_entered, username_entered) if check: print('valid login') # check the type of user request.session['department'] = check['department'] request.session.modified = True and at logout the the department key is deleted def logout(request): if request.session.has_key('department'): del request.session['department'] request.session.modified = True return render(request, 'login.html', {'login_form': forms.login_form}) and each page inside the website is checked if department key present if not the user is redirected to login page def parts_home(request): try: department= request.session['department'] if department != 'parts': raise Exception except: return HttpResponseRedirect(reverse('main:login_page')) this works fine while hardcoding the url of department in address bar but after pressing back button after logut is called the department key is not checked and the department page is loaded instead of login page. what is the solution? -
send data from an api every time a user crosses 5km
The current location of user might change in a minutes. For example if a user is in location A, he will get the list of property around 15km from his current location but if he is moving now and has crossed the 5km from the previous location now show the property around 15km from the new location. How can i handle such situation? Right now this is my code to find nearby property around 15km. @api_view(['GET', ]) def nearby_property_finder(request, current_latitude, current_longitude): user_location = Point(float(current_longitude), float(current_latitude)) distance_from_point = {'km': 15} properties = Property.gis.filter(location__distance_lte=(user_location,D(**distance_from_point))) properties = properties.distance(user_location).order_by('distance') if properties.exists(): paginator = ResultInPagination() paginated_properties = paginator.paginate_queryset(properties, request) serializer=PropertySerializer(paginated_properties, many=True) return paginator.get_paginated_response(serializer.data) else: return Response({}, status=status.HTTP_200_OK) -
How can I flatten a foreignkey object with django-rest-framework-(gis)
I have searched long and far for a solution that is up to date and specific to my problem but have yet not found a solution or a clear documentation on what I really need to do in order to flatten a relationship to become geojson compliant. This question is almost identical to mine, however the solutions or answers does not solve the problem and still produces invalid GeoJSON. django-rest-framework-gis related field Problem I have a Location model that holds a pointfield with SRID=4326. I also have a TrainStation model that has location field as foreign key to Location. When I serialize the TrainStation via the GeoFeatureModelSerializer it produces invalid GeoJSON (see example below "invalid geojson"). (Valid GeoJSON can of course be obtained if I where to store the PointField in the TrainStation model, but in my case I cannot do that so I need to flatten it somehow.) Question How do I achieve output like the "Valid GeoJSON" example below? Research I am a newcomer to both python and django thus I am yet not very good at reading other peoples source code, however I think I can conclude that I need to somehow override the to_representation() method in … -
apache test page show up on my non-apache server straight outta nowhere
I'm having a very weird problem right now. So I'm running a Django server using Gunicorn and Nginx with Ubuntu 16.04. NO Apache is anywhere in the server, neither is CentOS. But for some reason, my website occasionally loads the test page for a Apache server outta nowhere, and I have no idea where it's coming from. What is going on, and how do I get rid of the test page? -
Created related objects using django createview
Hey All I am using Django 1.10.7 I am creating a form that creates a store location to a store. Now what I want to happen is to have the store already associated with the store location when the form is loaded. The url has the proper id of the foreign key of the store ex: localhost:8000//office/dealer/1/location/create. and I see that that the store key is in the request keyword arguments. But I can't get how to associate that into the form. Any help would be really appreciated Here is how I have my code #views.py class DealerLocationCreateView(CreateView): model = models.DealerLocation fields = ['dealer' 'dealer_location_name', 'dealer_location_mailing_address', 'dealer_location_mailing_city', 'dealer_location_mailing_state', 'dealer_location_mailing_zipcode', 'dealer_location_mailing_phone', 'dealer_location_shipping_address', 'dealer_location_shipping_city', 'dealer_location_shipping_state', 'dealer_location_shipping_zipcode', 'dealer_location_shipping_phone' ] def form_valid(self, form): form.instance.dealer = self.request.dealer_pk return super(DealerLocationCreateView, self).form_valid(form) - # urls.py url(r'^dealer/(?P<dealer_pk>\d+)/location/create', DealerLocationCreateView.as_view(), name='new-location'), -
Build a secure one-to-one chat app
Hey I am working to make a one-to-one chat apps with Django/Python that allows the users of my website to chat together , but I have no idea from where to start ? Which protocol communication to choose(I wanted to use web sockets until I hears in somewhere that it's not safe I mean Privacy ) ? , what are the things should I consider to not get leak informations ? , ... etc . Thanks guys . Ps : I am using a third party web server provider to run my website . -
implementing a form in base template django
I'm running a Django server hosted with Nginx and Gunicorn, and I ran into a bit of a dilemma. I tried implementing a form in my project's root template, the one that all my other templates inherit from. I set up the form through the view for /, but the issue is that I can't get the same form to work on any of my other views without implementing the same view-side form code on all my other views. (Otherwise, form isn't defined and the page fails to load) Is there a way I can implement the form in my root template such that I don't have to re-setup the form on all my other views? -
Building A Full Backend API Token System
Hi I built a platform using python django and i have integrated a restful api into the platform and also integrated jwt into the platform also but my question is after a user has input their username and password and the platforms generates a signed token for them to copy, how can i pass all of these information into their url so that the url now becomes for example www.mywebsite.com/api/auth?user=this_user&token="some-random-chars" All i need is building a full authentication backend token system so that i could allow people to use my database content over an api after they have signup and loggedin -
How do I create a form allowing a user to select a single model object using multiple select inputs listing its attributes?
Given the following models: class Product(models.Model): sku = models.CharField(unique=True, max_length=50) name = models.CharField(max_length=4000) price = models.DecimalField(max_digits=20, decimal_places=2, default=0.0) class Location(models.Model): name = models.CharField(max_length=255) class Stock(models.Model): class Meta: unique_together = (('product', 'location', 'batch_code'),) product = models.ForeignKey(Product) location = models.ForeignKey(Location) batch_code = models.CharField(max_length=255) qty_on_hand = models.DecimalField(max_digits=20, decimal_places=5, default=0) class SaleLine(models.Model): sale = models.ForeignKey(Sale) stock = models.ForeignKey(Stock) item_price = models.DecimalField(max_digits=20, decimal_places=2) discount = models.DecimalField(max_digits=5, decimal_places=2) qty = models.DecimalField(max_digits=20, decimal_places=4) I need to create an inline form for SaleLine objects that allows the user to first select a Product.sku then a Stock.batch_code (restricted to valid batch codes for the selected sku) and a Stock.location (restricted to valid locations for the selected sku and batch_code). Then use those 3 selections to populate the SaleLine.stock attribute when the form is submitted. Before I go down the path of lots of custom Javascript and view code I'd like to know if there is a native Django way to do this? -
Django, how do I split up a model's column into three text fields?
I have an issue with splitting up a column in a model into three separate text fields. Right now, I have this: class Software(models.Model): version = models.CharField(max_length = 10) And, then in the admin panel, for the program's version, you get one text field. So, if you have a version like this: 1.2.3 I want a text box for 1, another for 2, and the last one for 3. So, it might look like this: |1|.|2|.|3| Then, when I get the values of all three text fields, I will combine them to make this string: '1.2.3' Does anybody know how to do this? Thanks. -
Django - template containing model's 'table'
Here's my problem: I want to print a table in template which contains every object with every field Here's my solution: views.py def start(request): all_rows = Person.objects.all() all_fields_names = Person._meta.get_fields() content = { 'all_rows': all_rows, 'all_fields_names': all_fields_names } return render(request, 'start.html', content) start.html <table class="table table-striped table-hover table-responsive"> <thead> {% for names in all_fields_names %}<th>{{ names.name |title }}</th>{% endfor %} </thead> <tbody> {% for row in all_rows %} <tr> <td>{{ row.name }}</td> <td>{{ row.yabadiba }}</td> <td>{{ row.value1 }}</td> <td>{{ row.value2 }}</td> </tr> {% endfor %} </tbody> </table> Everything works perfectly. The problem is, when I don't know exactly how many fields is in the class. Second of all, my solution break the DRY rule. I've tried: getattr(row, names) and nested loops, with no success. Is there any simple solution? Moreover: How to print such view for every class? -
Django bootstrap to have both call a view and modal in same anchor tag
I am using Django and pretty new to it. My purpose is to trigger an asynchronous view from the template and stay in the same page showing a pop up that the process is triggered. I searched a lot for a solution but couldn't work it out. I am able to stay in the same page and trigger the view asynchronously using Celery but my problem is my modal is displaying the content of my web page and not the content I have mentioned in the modal content. I am passing the view in the anchor tag href and modal in data-target. Below is the code of my template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>DashBoard</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#topNavBar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">DashBoard</a> </div> <div class="collapse navbar-collapse" id="topNavBar"> <ul class="nav navbar-nav"> <li class="active"> <a href="#"> <span class="#" aria-hidden="true"></span>&nbsp; Reports </a> </li> <li class=""> <a href="#"> <span class="#" aria-hidden="true"></span>&nbsp; Projects </a> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li class=""> <li class=""> <a data-toggle="modal" href="{% url 'update-field' %}" data-target="#myModal"> <span class="glyphicon glyphicon-refresh" aria-hidden="true"></span>&nbsp; Update-Fields </a> <!-- Modal … -
HTML doens't parse marked text with Stack Overflow django-pagedown app
I am trying to make a comment using Markup parser and i have a strange problem that i don't know how to fix it. This is the main code that i implemented the widgets in form.py: from django import forms from pagedown.widgets import PagedownWidget from .models import Post class PostForm(forms.ModelForm): content = forms.CharField(widget=PagedownWidget) publish = forms.DateField(widget=forms.SelectDateWidget) class Meta: model = Post fields = [ "title", "content", "image", "draft", "publish", ] This is the code from base.html file that makes me use the widgets: <script type="text/javascript"> $(document).ready(function () { $(".content-markdown").each(function(){ var content = $(this).text() console.log(content) var markedContent = marked(content) console.log(markedContent) $(this).html(markedContent) }) }) This is the code from post_detail.html that allows me to implement in the comment: <div class="'row"> <div class="col-sm-12 content-markdown"> {{ instance.content }} This is the text i want to parse: ***Example:*** # H1 ## H2 ### H3 #### H4 ##### H5 ###### H6 Alternatively, for H1 and H2, an underline-ish style: Alt-H1 ====== Alt-H2 ------ And this is the ouput that i am getting in my Chrome console log: <div class="'row"> <div class="col-sm-12 content-markdown"> ***Example:*** # H1 ## H2 ### H3 #### H4 ##### H5 ###### H6 Alternatively, for H1 and H2, an underline-ish style: Alt-H1 ====== Alt-H2 -
Rating using Django Model System
class User(models.Model): username = models.CharField(max_length=150) email = models.EmailField(max_length=150) class Recipes(models.Model): title = models.CharField(max_length=150) user = models.ForeignKey(User, related_name='user', on_delete=models.CASCADE, null=True) created = models.DateTimeField(auto_now=True, auto_now_add=False) updated = models.DateTimeField(auto_now=False, auto_now_add=True) class FavoriteRecipes(models.Model): user = models.ForeignKey(User,related_name='user_recipe' on_delete=models.CASCADE, null=True) recipe = models.ForeignKey(Recipes, on_delete=models.CASCADE, null=True) class FavoriteChef(models.Model): user = models.ForeignKey(User, related_name='user', on_delete=models.CASCADE) favorite = models.ForeignKey(User, related_name='favorite', on_delete=models.CASCADE) I am trying to create a rating system to recipes and users. I am not sure if this is the best approach or not, but his are my questions: how I count the ammount of recipes liked by different user, example: user 1 liked recipe 1 user 2 liked recipe 1 recipe 1 is liekd by 2. how to limit the user from voting may times using this approach, since django generates its own pk entries like this can exists: pk:1 user 1 liked recipe 1 pk:2 user 1 liked recipe 1 and thanks -
django - type error string or buffer expected
mail=EmailMessage(subject,template_content,getjdets.journalheadmail,[tuple1[1],]) docfile = default_storage.open(getattachment[0], 'r') if docfile: mail.attach(docfile,docfile.read()) else: pass mail.send() Above is my code to send a mail with attachment retrieved from amazon s3, i was getting this error saying typerror, string or buffer expected. I could n't figure a solution, -
Django 'getattr(row,', expected 'empty' or 'endfor''
Code I'm working with: {% for row in all_rows %} <tr> {% for names in all_fields_names %} <td> {% getattr(row, names) %} </td> {% endfor %} </tr> {% endfor %} I get error: 'getattr(row,', expected 'empty' or 'endfor' I've tried: {% for row, names in (all_rows, all_fields_names) %} <tr> <td> {% getattr(row, names) %} </td> </tr> {% endfor %} With no success. Any ideas? -
extracting db log from main log django logging
My main goal is simple: Create three different logs with a different meaning to each: app log - a log that will simply be used as the main log of the program. rest log - a log that will log all incoming requests and responses. db log - a log that will log all database activity. I have created the following logging config in my settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, }, 'handlers': { 'default': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'static/ship_dropper.log', 'maxBytes': 1024 * 1024 * 5, # 5 MB 'backupCount': 5, 'formatter': 'standard', }, 'request_handler': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'static/ship_dropper_request.log', 'maxBytes': 1024 * 1024 * 50, # 50 MB 'backupCount': 5, 'formatter': 'standard', }, 'db_handler': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'static/ship_dropper_db.log', 'maxBytes': 1024 * 1024 * 50, # 50 MB 'backupCount': 5, 'formatter': 'standard', }, }, 'loggers': { '': { 'handlers': ['default'], 'level': 'DEBUG', }, 'django.request': { 'handlers': ['request_handler'], 'level': 'DEBUG', }, 'django.db.backends': { 'handlers': ['db_handler'], 'level': 'DEBUG', }, } } but that creates a few issues: The default log, contains all the data from all the logs (I know its … -
django collectstatic: How to keep the project structure?
Currently, collecstatic gathers all files of the project's Apps in one directory (STATIC_ROOT). What should be done to keep the project structure for the static files: STATIC_ROOT/App1 .. STATIC_ROOT/Appn STATIC_ROOT/App3 thanks -
Django Rest Framework - serializing a ManyToManyField with the default 'through'
Hello I'm new to DRF and I can serialize a table with a foreign key, but when it comes to a many to many field, in this case: Package <> Package_product_atom <> Product_atom How would I go around serializing this? So far what I'm trying is: class Product_atomSerializer(serializers.ModelSerializer): class Meta: model = Product_atom ready_only = True fields = ('id','title', 'title_override', 'price', 'price_override', 'description', 'description_override','image', 'image_override' ,'tags', 'product_alt', 'date_modified', 'date_created') class PackageSerializer(serializers.ModelSerializer): atomics = Product_atomSerializer(many=True) class Meta: model = Package ready_only = True fields = ('id', 'title', 'price', 'discount', 'image', 'tags', 'atomics', 'date_modified', 'date_created') My models are: class Product_atom(models.Model): title = models.CharField(max_length=255, blank=False) title_override = models.BooleanField(default=False, blank=False) price = models.SmallIntegerField(default=0, blank=False) price_override = models.BooleanField(default=False, blank=False) description = models.TextField(blank=True) description_override = models.BooleanField(default=False, blank=False) image = models.ImageField(upload_to = 'uploads', default = '', blank=True) image_override = models.BooleanField(default=False, blank=False) tags = models.CharField(max_length=255, blank=False) active = models.BooleanField(default=True, blank=False) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) product_alt = models.ForeignKey(Product_alt, related_name='atomics', on_delete=models.CASCADE) default_provider = models.ForeignKey(Provider, on_delete=models.CASCADE) def __str__(self): return "{}".format(self.title) class Package(models.Model): title = models.CharField(max_length=255, blank=False) price = models.SmallIntegerField(default=0, blank=False) discount = models.SmallIntegerField(default=10, blank=False) image = models.ImageField(upload_to = 'uploads', default = '', blank=True) tags = models.CharField(max_length=255, blank=False) active = models.BooleanField(default=True, blank=False) date_created = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) zone = … -
Add a title to a PDF in Django using repotlab
I have made a simple table to printed in a pdf file,I want to give a title to the pdf for which I wrote: response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename='+Username+'.pdf' styles = getSampleStyleSheet() styles.add(ParagraphStyle( name="ParagraphTitle", fontSize=11, alignment=TA_JUSTIFY, fontName="FreeSansBold")) Paragraph('Paragraph example', styles['Title']) elements = [] doc = SimpleDocTemplate(response, rightMargin=0, leftMargin=6.5 * cm, topMargin=0.6 * cm, bottomMargin=0) data=[(1,2),(3,4)] table = Table(data, colWidths=270, rowHeights=79) elements.append(table) doc.build(elements,Paragraph) return response But,there is an error:name 'getSampleStyleSheet' is not defined I tried to find the header file for getSampleStyleSheet but couldn't find. Please provide the file to import for this and is this the right way of adding a title and a table to a pdf? Thanks. -
django-filter: How to filter by field A but display field B as corresponding filter option/text?
I have a Django Post model with a fk to a Category model with a category name and a category slug. Now I filter these posts by category via django-filter and the LinkWidget. That's fine and worked via name="categories__name" out of the box: # models.py class Category(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(unique=True) class Post(models.Model): categories = models.ForeignKey(Post) # filters.py class PostFilter(django_filters.FilterSet): categories = AllValuesFilter( name="categories__name", label="Categories", widget=LinkWidget(), ) class Meta: model = Post fields = ['categories',] But now I would like to eliminate the categories__name as the GET parameter and use categories__slug instead - but keep the more human readable categories__name as the link text in the LinkWidget - but I have no idea how to achieve this, any hints? -
How do you do Rails' polymorphism/STI in Django?
I came across Proxy models in Django but they don't create the single-table polymorphic columns (polymorphable_id, polymorphable_type). Is there any way to create sti/polymorphism in Django? -
Search engine used by Django website and Zinnia?
What search engine app does the Django project uses itself in their website? The search form in https://docs.djangoproject.com/en/1.11/ Is that search engine good for blogs? Or the one used by Zinnia (what app is that?) is better? -
TypeError function SwaggerSchemaView not JSON serializable
TypeError at /docs/ is not JSON serializable Here's my code def schema_view(request): schema_view = get_swagger_view(title='Docs API') return Response(schema_view) -
Secure way to POST to Django from a trusted external (Node-RED) server?
What I want I have a Node-RED instance on one server doing real-time analysis of a data stream. I want it to securely notify a Django app on a different server of any actionable findings. Problem By default Django protects against cross-site request forgeries by requiring "unsafe" requests (like POST) to contain a CSRF token/secret that Django provides (as a cookie? rendered into the page?) when rendering an HTML form containing the {% csrf_token %} template tag or a view decorated with csrf_protect. The above seems like it will only allow POSTS starting from pages that the Django app itself served (that's probably the point). My Node-RED instance is not requesting a page from Django to start with, so it has no token/secret to include in a POST. Approaches considered so far: Use GET requests instead The requests Node-RED would be sending will cause side-effects in Django, and I don't want a third party sending bogus requests and making Django do somersaults for no reason. Remove check using Django's csrf_exempt decorator See above. Use HTTP basic authentication The Node-RED http request node has an option to set a username/password to be sent in (I think) the WWW-Authenticate header and I …